babylon.max.js 5.7 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545104546104547104548104549104550104551104552104553104554104555104556104557104558104559104560104561104562104563104564104565104566104567104568104569104570104571104572104573104574104575104576104577104578104579104580104581104582104583104584104585104586104587104588104589104590104591104592104593104594104595104596104597104598104599104600104601104602104603104604104605104606104607104608104609104610104611104612104613104614104615104616104617104618104619104620104621104622104623104624104625104626104627104628104629104630104631104632104633104634104635104636104637104638104639104640104641104642104643104644104645104646104647104648104649104650104651104652104653104654104655104656104657104658104659104660104661104662104663104664104665104666104667104668104669104670104671104672104673104674104675104676104677104678104679104680104681104682104683104684104685104686104687104688104689104690104691104692104693104694104695104696104697104698104699104700104701104702104703104704104705104706104707104708104709104710104711104712104713104714104715104716104717104718104719104720104721104722104723104724104725104726104727104728104729104730104731104732104733104734104735104736104737104738104739104740104741104742104743104744104745104746104747104748104749104750104751104752104753104754104755104756104757104758104759104760104761104762104763104764104765104766104767104768104769104770104771104772104773104774104775104776104777104778104779104780104781104782104783104784104785104786104787104788104789104790104791104792104793104794104795104796104797104798104799104800104801104802104803104804104805104806104807104808104809104810104811104812104813104814104815104816104817104818104819104820104821104822104823104824104825104826104827104828104829104830104831104832104833104834104835104836104837104838104839104840104841104842104843104844104845104846104847104848104849104850104851104852104853104854104855104856104857104858104859104860104861104862104863104864104865104866104867104868104869104870104871104872104873104874104875104876104877104878104879104880104881104882104883104884104885104886104887104888104889104890104891104892104893104894104895104896104897104898104899104900104901104902104903104904104905104906104907104908104909104910104911104912104913104914104915104916104917104918104919104920104921104922104923104924104925104926104927104928104929104930104931104932104933104934104935104936104937104938104939104940104941104942104943104944104945104946104947104948104949104950104951104952104953104954104955104956104957104958104959104960104961104962104963104964104965104966104967104968104969104970104971104972104973104974104975104976104977104978104979104980104981104982104983104984104985104986104987104988104989104990104991104992104993104994104995104996104997104998104999105000105001105002105003105004105005105006105007105008105009105010105011105012105013105014105015105016105017105018105019105020105021105022105023105024105025105026105027105028105029105030105031105032105033105034105035105036105037105038105039105040105041105042105043105044105045105046105047105048105049105050105051105052105053105054105055105056105057105058105059105060105061105062105063105064105065105066105067105068105069105070105071105072105073105074105075105076105077105078105079105080105081105082105083105084105085105086105087105088105089105090105091105092105093105094105095105096105097105098105099105100105101105102105103105104105105105106105107105108105109105110105111105112105113105114105115105116105117105118105119105120105121105122105123105124105125105126105127105128105129105130105131105132105133105134105135105136105137105138105139105140105141105142105143105144105145105146105147105148105149105150105151105152105153105154105155105156105157105158105159105160105161105162105163105164105165105166105167105168105169105170105171105172105173105174105175105176105177105178105179105180105181105182105183105184105185105186105187105188105189105190105191105192105193105194105195105196105197105198105199105200105201105202105203105204105205105206105207105208105209105210105211105212105213105214105215105216105217105218105219105220105221105222105223105224105225105226105227105228105229105230105231105232105233105234105235105236105237105238105239105240105241105242105243105244105245105246105247105248105249105250105251105252105253105254105255105256105257105258105259105260105261105262105263105264105265105266105267105268105269105270105271105272105273105274105275105276105277105278105279105280105281105282105283105284105285105286105287105288105289105290105291105292105293105294105295105296105297105298105299105300105301105302105303105304105305105306105307105308105309105310105311105312105313105314105315105316105317105318105319105320105321105322105323105324105325105326105327105328105329105330105331105332105333105334105335105336105337105338105339105340105341105342105343105344105345105346105347105348105349105350105351105352105353105354105355105356105357105358105359105360105361105362105363105364105365105366105367105368105369105370105371105372105373105374105375105376105377105378105379105380105381105382105383105384105385105386105387105388105389105390105391105392105393105394105395105396105397105398105399105400105401105402105403105404105405105406105407105408105409105410105411105412105413105414105415105416105417105418105419105420105421105422105423105424105425105426105427105428105429105430105431105432105433105434105435105436105437105438105439105440105441105442105443105444105445105446105447105448105449105450105451105452105453105454105455105456105457105458105459105460105461105462105463105464105465105466105467105468105469105470105471105472105473105474105475105476105477105478105479105480105481105482105483105484105485105486105487105488105489105490105491105492105493105494105495105496105497105498105499105500105501105502105503105504105505105506105507105508105509105510105511105512105513105514105515105516105517105518105519105520105521105522105523105524105525105526105527105528105529105530105531105532105533105534105535105536105537105538105539105540105541105542105543105544105545105546105547105548105549105550105551105552105553105554105555105556105557105558105559105560105561105562105563105564105565105566105567105568105569105570105571105572105573105574105575105576105577105578105579105580105581105582105583105584105585105586105587105588105589105590105591105592105593105594105595105596105597105598105599105600105601105602105603105604105605105606105607105608105609105610105611105612105613105614105615105616105617105618105619105620105621105622105623105624105625105626105627105628105629105630105631105632105633105634105635105636105637105638105639105640105641105642105643105644105645105646105647105648105649105650105651105652105653105654105655105656105657105658105659105660105661105662105663105664105665105666105667105668105669105670105671105672105673105674105675105676105677105678105679105680105681105682105683105684105685105686105687105688105689105690105691105692105693105694105695105696105697105698105699105700105701105702105703105704105705105706105707105708105709105710105711105712105713105714105715105716105717105718105719105720105721105722105723105724105725105726105727105728105729105730105731105732105733105734105735105736105737105738105739105740105741105742105743105744105745105746105747105748105749105750105751105752105753105754105755105756105757105758105759105760105761105762105763105764105765105766105767105768105769105770105771105772105773105774105775105776105777105778105779105780105781105782105783105784105785105786105787105788105789105790105791105792105793105794105795105796105797105798105799105800105801105802105803105804105805105806105807105808105809105810105811105812105813105814105815105816105817105818105819105820105821105822105823105824105825105826105827105828105829105830105831105832105833105834105835105836105837105838105839105840105841105842105843105844105845105846105847105848105849105850105851105852105853105854105855105856105857105858105859105860105861105862105863105864105865105866105867105868105869105870105871105872105873105874105875105876105877105878105879105880105881105882105883105884105885105886105887105888105889105890105891105892105893105894105895105896105897105898105899105900105901105902105903105904105905105906105907105908105909105910105911105912105913105914105915105916105917105918105919105920105921105922105923105924105925105926105927105928105929105930105931105932105933105934105935105936105937105938105939105940105941105942105943105944105945105946105947105948105949105950105951105952105953105954105955105956105957105958105959105960105961105962105963105964105965105966105967105968105969105970105971105972105973105974105975105976105977105978105979105980105981105982105983105984105985105986105987105988105989105990105991105992105993105994105995105996105997105998105999106000106001106002106003106004106005106006106007106008106009106010106011106012106013106014106015106016106017106018106019106020106021106022106023106024106025106026106027106028106029106030106031106032106033106034106035106036106037106038106039106040106041106042106043106044106045106046106047106048106049106050106051106052106053106054106055106056106057106058106059106060106061106062106063106064106065106066106067106068106069106070106071106072106073106074106075106076106077106078106079106080106081106082106083106084106085106086106087106088106089106090106091106092106093106094106095106096106097106098106099106100106101106102106103106104106105106106106107106108106109106110106111106112106113106114106115106116106117106118106119106120106121106122106123106124106125106126106127106128106129106130106131106132106133106134106135106136106137106138106139106140106141106142106143106144106145106146106147106148106149106150106151106152106153106154106155106156106157106158106159106160106161106162106163106164106165106166106167106168106169106170106171106172106173106174106175106176106177106178106179106180106181106182106183106184106185106186106187106188106189106190106191106192106193106194106195106196106197106198106199106200106201106202106203106204106205106206106207106208106209106210106211106212106213106214106215106216106217106218106219106220106221106222106223106224106225106226106227106228106229106230106231106232106233106234106235106236106237106238106239106240106241106242106243106244106245106246106247106248106249106250106251106252106253106254106255106256106257106258106259106260106261106262106263106264106265106266106267106268106269106270106271106272106273106274106275106276106277106278106279106280106281106282106283106284106285106286106287106288106289106290106291106292106293106294106295106296106297106298106299106300106301106302106303106304106305106306106307106308106309106310106311106312106313106314106315106316106317106318106319106320106321106322106323106324106325106326106327106328106329106330106331106332106333106334106335106336106337106338106339106340106341106342106343106344106345106346106347106348106349106350106351106352106353106354106355106356106357106358106359106360106361106362106363106364106365106366106367106368106369106370106371106372106373106374106375106376106377106378106379106380106381106382106383106384106385106386106387106388106389106390106391106392106393106394106395106396106397106398106399106400106401106402106403106404106405106406106407106408106409106410106411106412106413106414106415106416106417106418106419106420106421106422106423106424106425106426106427106428106429106430106431106432106433106434106435106436106437106438106439106440106441106442106443106444106445106446106447106448106449106450106451106452106453106454106455106456106457106458106459106460106461106462106463106464106465106466106467106468106469106470106471106472106473106474106475106476106477106478106479106480106481106482106483106484106485106486106487106488106489106490106491106492106493106494106495106496106497106498106499106500106501106502106503106504106505106506106507106508106509106510106511106512106513106514106515106516106517106518106519106520106521106522106523106524106525106526106527106528106529106530106531106532106533106534106535106536106537106538106539106540106541106542106543106544106545106546106547106548106549106550106551106552106553106554106555106556106557106558106559106560106561106562106563106564106565106566106567106568106569106570106571106572106573106574106575106576106577106578106579106580106581106582106583106584106585106586106587106588106589106590106591106592106593106594106595106596106597106598106599106600106601106602106603106604106605106606106607106608106609106610106611106612106613106614106615106616106617106618106619106620106621106622106623106624106625106626106627106628106629106630106631106632106633106634106635106636106637106638106639106640106641106642106643106644106645106646106647106648106649106650106651106652106653106654106655106656106657106658106659106660106661106662106663106664106665106666106667106668106669106670106671106672106673106674106675106676106677106678106679106680106681106682106683106684106685106686106687106688106689106690106691106692106693106694106695106696106697106698106699106700106701106702106703106704106705106706106707106708106709106710106711106712106713106714106715106716106717106718106719106720106721106722106723106724106725106726106727106728106729106730106731106732106733106734106735106736106737106738106739106740106741106742106743106744106745106746106747106748106749106750106751106752106753106754106755106756106757106758106759106760106761106762106763106764106765106766106767106768106769106770106771106772106773106774106775106776106777106778106779106780106781106782106783106784106785106786106787106788106789106790106791106792106793106794106795106796106797106798106799106800106801106802106803106804106805106806106807106808106809106810106811106812106813106814106815106816106817106818106819106820106821106822106823106824106825106826106827106828106829106830106831106832106833106834106835106836106837106838106839106840106841106842106843106844106845106846106847106848106849106850106851106852106853106854106855106856106857106858106859106860106861106862106863106864106865106866106867106868106869106870106871106872106873106874106875106876106877106878106879106880106881106882106883106884106885106886106887106888106889106890106891106892106893106894106895106896106897106898106899106900106901106902106903106904106905106906106907106908106909106910106911106912106913106914106915106916106917106918106919106920106921106922106923106924106925106926106927106928106929106930106931106932106933106934106935106936106937106938106939106940106941106942106943106944106945106946106947106948106949106950106951106952106953106954106955106956106957106958106959106960106961106962106963106964106965106966106967106968106969106970106971106972106973106974106975106976106977106978106979106980106981106982106983106984106985106986106987106988106989106990106991106992106993106994106995106996106997106998106999107000107001107002107003107004107005107006107007107008107009107010107011107012107013107014107015107016107017107018107019107020107021107022107023107024107025107026107027107028107029107030107031107032107033107034107035107036107037107038107039107040107041107042107043107044107045107046107047107048107049107050107051107052107053107054107055107056107057107058107059107060107061107062107063107064107065107066107067107068107069107070107071107072107073107074107075107076107077107078107079107080107081107082107083107084107085107086107087107088107089107090107091107092107093107094107095107096107097107098107099107100107101107102107103107104107105107106107107107108107109107110107111107112107113107114107115107116107117107118107119107120107121107122107123107124107125107126107127107128107129107130107131107132107133107134107135107136107137107138107139107140107141107142107143107144107145107146107147107148107149107150107151107152107153107154107155107156107157107158107159107160107161107162107163107164107165107166107167107168107169107170107171107172107173107174107175107176107177107178107179107180107181107182107183107184107185107186107187107188107189107190107191107192107193107194107195107196107197107198107199107200107201107202107203107204107205107206107207107208107209107210107211107212107213107214107215107216107217107218107219107220107221107222107223107224107225107226107227107228107229107230107231107232107233107234107235107236107237107238107239107240107241107242107243107244107245107246107247107248107249107250107251107252107253107254107255107256107257107258107259107260107261107262107263107264107265107266107267107268107269107270107271107272107273107274107275107276107277107278107279107280107281107282107283107284107285107286107287107288107289107290107291107292107293107294107295107296107297107298107299107300107301107302107303107304107305107306107307107308107309107310107311107312107313107314107315107316107317107318107319107320107321107322107323107324107325107326107327107328107329107330107331107332107333107334107335107336107337107338107339107340107341107342107343107344107345107346107347107348107349107350107351107352107353107354107355107356107357107358107359107360107361107362107363107364107365107366107367107368107369107370107371107372107373107374107375107376107377107378107379107380107381107382107383107384107385107386107387107388107389107390107391107392107393107394107395107396107397107398107399107400107401107402107403107404107405107406107407107408107409107410107411107412107413107414107415107416107417107418107419107420107421107422107423107424107425107426107427107428107429107430107431107432107433107434107435107436107437107438107439107440107441107442107443107444107445107446107447107448107449107450107451107452107453107454107455107456107457107458107459107460107461107462107463107464107465107466107467107468107469107470107471107472107473107474107475107476107477107478107479107480107481107482107483107484107485107486107487107488107489107490107491107492107493107494107495107496107497107498107499107500107501107502107503107504107505107506107507107508107509107510107511107512107513107514107515107516107517107518107519107520107521107522107523107524107525107526107527107528107529107530107531107532107533107534107535107536107537107538107539107540107541107542107543107544107545107546107547107548107549107550107551107552107553107554107555107556107557107558107559107560107561107562107563107564107565107566107567107568107569107570107571107572107573107574107575107576107577107578107579107580107581107582107583107584107585107586107587107588107589107590107591107592107593107594107595107596107597107598107599107600107601107602107603107604107605107606107607107608107609107610107611107612107613107614107615107616107617107618107619107620107621107622107623107624107625107626107627107628107629107630107631107632107633107634107635107636107637107638107639107640107641107642107643107644107645107646107647107648107649107650107651107652107653107654107655107656107657107658107659107660107661107662107663107664107665107666107667107668107669107670107671107672107673107674107675107676107677107678107679107680107681107682107683107684107685107686107687107688107689107690107691107692107693107694107695107696107697107698107699107700107701107702107703107704107705107706107707107708107709107710107711107712107713107714107715107716107717107718107719107720107721107722107723107724107725107726107727107728107729107730107731107732107733107734107735107736107737107738107739107740107741107742107743107744107745107746107747107748107749107750107751107752107753107754107755107756107757107758107759107760107761107762107763107764107765107766107767107768107769107770107771107772107773107774107775107776107777107778107779107780107781107782107783107784107785107786107787107788107789107790107791107792107793107794107795107796107797107798107799107800107801107802107803107804107805107806107807107808107809107810107811107812107813107814107815107816107817107818107819107820107821107822107823107824107825107826107827107828107829107830107831107832107833107834107835107836107837107838107839107840107841107842107843107844107845107846107847107848107849107850107851107852107853107854107855107856107857107858107859107860107861107862107863107864107865107866107867107868107869107870107871107872107873107874107875107876107877107878107879107880107881107882107883107884107885107886107887107888107889107890107891107892107893107894107895107896107897107898107899107900107901107902107903107904107905107906107907107908107909107910107911107912107913107914107915107916107917107918107919107920107921107922107923107924107925107926107927107928107929107930107931107932107933107934107935107936107937107938107939107940107941107942107943107944107945107946107947107948107949107950107951107952107953107954107955107956107957107958107959107960107961107962107963107964107965107966107967107968107969107970107971107972107973107974107975107976107977107978107979107980107981107982107983107984107985107986107987107988107989107990107991107992107993107994107995107996107997107998107999108000108001108002108003108004108005108006108007108008108009108010108011108012108013108014108015108016108017108018108019108020108021108022108023108024108025108026108027108028108029108030108031108032108033108034108035108036108037108038108039108040108041108042108043108044108045108046108047108048108049108050108051108052108053108054108055108056108057108058108059108060108061108062108063108064108065108066108067108068108069108070108071108072108073108074108075108076108077108078108079108080108081108082108083108084108085108086108087108088108089108090108091108092108093108094108095108096108097108098108099108100108101108102108103108104108105108106108107108108108109108110108111108112108113108114108115108116108117108118108119108120108121108122108123108124108125108126108127108128108129108130108131108132108133108134108135108136108137108138108139108140108141108142108143108144108145108146108147108148108149108150108151108152108153108154108155108156108157108158108159108160108161108162108163108164108165108166108167108168108169108170108171108172108173108174108175108176108177108178108179108180108181108182108183108184108185108186108187108188108189108190108191108192108193108194108195108196108197108198108199108200108201108202108203108204108205108206108207108208108209108210108211108212108213108214108215108216108217108218108219108220108221108222108223108224108225108226108227108228108229108230108231108232108233108234108235108236108237108238108239108240108241108242108243108244108245108246108247108248108249108250108251108252108253108254108255108256108257108258108259108260108261108262108263108264108265108266108267108268108269108270108271108272108273108274108275108276108277108278108279108280108281108282108283108284108285108286108287108288108289108290108291108292108293108294108295108296108297108298108299108300108301108302108303108304108305108306108307108308108309108310108311108312108313108314108315108316108317108318108319108320108321108322108323108324108325108326108327108328108329108330108331108332108333108334108335108336108337108338108339108340108341108342108343108344108345108346108347108348108349108350108351108352108353108354108355108356108357108358108359108360108361108362108363108364108365108366108367108368108369108370108371108372108373108374108375108376108377108378108379108380108381108382108383108384108385108386108387108388108389108390108391108392108393108394108395108396108397108398108399108400108401108402108403108404108405108406108407108408108409108410108411108412108413108414108415108416108417108418108419108420108421108422108423108424108425108426108427108428108429108430108431108432108433108434108435108436108437108438108439108440108441108442108443108444108445108446108447108448108449108450108451108452108453108454108455108456108457108458108459108460108461108462108463108464108465108466108467108468108469108470108471108472108473108474108475108476108477108478108479108480108481108482108483108484108485108486108487108488108489108490108491108492108493108494108495108496108497108498108499108500108501108502108503108504108505108506108507108508108509108510108511108512108513108514108515108516108517108518108519108520108521108522108523108524108525108526108527108528108529108530108531108532108533108534108535108536108537108538108539108540108541108542108543108544108545108546108547108548108549108550108551108552108553108554108555108556108557108558108559108560108561108562108563108564108565108566108567108568108569108570108571108572108573108574108575108576108577108578108579108580108581108582108583108584108585108586108587108588108589108590108591108592108593108594108595108596108597108598108599108600108601108602108603108604108605108606108607108608108609108610108611108612108613108614108615108616108617108618108619108620108621108622108623108624108625108626108627108628108629108630108631108632108633108634108635108636108637108638108639108640108641108642108643108644108645108646108647108648108649108650108651108652108653108654108655108656108657108658108659108660108661108662108663108664108665108666108667108668108669108670108671108672108673108674108675108676108677108678108679108680108681108682108683108684108685108686108687108688108689108690108691108692108693108694108695108696108697108698108699108700108701108702108703108704108705108706108707108708108709108710108711108712108713108714108715108716108717108718108719108720108721108722108723108724108725108726108727108728108729108730108731108732108733108734108735108736108737108738108739108740108741108742108743108744108745108746108747108748108749108750108751108752108753108754108755108756108757108758108759108760108761108762108763108764108765108766108767108768108769108770108771108772108773108774108775108776108777108778108779108780108781108782108783108784108785108786108787108788108789108790108791108792108793108794108795108796108797108798108799108800108801108802108803108804108805108806108807108808108809108810108811108812108813108814108815108816108817108818108819108820108821108822108823108824108825108826108827108828108829108830108831108832108833108834108835108836108837108838108839108840108841108842108843108844108845108846108847108848108849108850108851108852108853108854108855108856108857108858108859108860108861108862108863108864108865108866108867108868108869108870108871108872108873108874108875108876108877108878108879108880108881108882108883108884108885108886108887108888108889108890108891108892108893108894108895108896108897108898108899108900108901108902108903108904108905108906108907108908108909108910108911108912108913108914108915108916108917108918108919108920108921108922108923108924108925108926108927108928108929108930108931108932108933108934108935108936108937108938108939108940108941108942108943108944108945108946108947108948108949108950108951108952108953108954108955108956108957108958108959108960108961108962108963108964108965108966108967108968108969108970108971108972108973108974108975108976108977108978108979108980108981108982108983108984108985108986108987108988108989108990108991108992108993108994108995108996108997108998108999109000109001109002109003109004109005109006109007109008109009109010109011109012109013109014109015109016109017109018109019109020109021109022109023109024109025109026109027109028109029109030109031109032109033109034109035109036109037109038109039109040109041109042109043109044109045109046109047109048109049109050109051109052109053109054109055109056109057109058109059109060109061109062109063109064109065109066109067109068109069109070109071109072109073109074109075109076109077109078109079109080109081109082109083109084109085109086109087109088109089109090109091109092109093109094109095109096109097109098109099109100109101109102109103109104109105109106109107109108109109109110109111109112109113109114109115109116109117109118109119109120109121109122109123109124109125109126109127109128109129109130109131109132109133109134109135109136109137109138109139109140109141109142109143109144109145109146109147109148109149109150109151109152109153109154109155109156109157109158109159109160109161109162109163109164109165109166109167109168109169109170109171109172109173109174109175109176109177109178109179109180109181109182109183109184109185109186109187109188109189109190109191109192109193109194109195109196109197109198109199109200109201109202109203109204109205109206109207109208109209109210109211109212109213109214109215109216109217109218109219109220109221109222109223109224109225109226109227109228109229109230109231109232109233109234109235109236109237109238109239109240109241109242109243109244109245109246109247109248109249109250109251109252109253109254109255109256109257109258109259109260109261109262109263109264109265109266109267109268109269109270109271109272109273109274109275109276109277109278109279109280109281109282109283109284109285109286109287109288109289109290109291109292109293109294109295109296109297109298109299109300109301109302109303109304109305109306109307109308109309109310109311109312109313109314109315109316109317109318109319109320109321109322109323109324109325109326109327109328109329109330109331109332109333109334109335109336109337109338109339109340109341109342109343109344109345109346109347109348109349109350109351109352109353109354109355109356109357109358109359109360109361109362109363109364109365109366109367109368109369109370109371109372109373109374109375109376109377109378109379109380109381109382109383109384109385109386109387109388109389109390109391109392109393109394109395109396109397109398109399109400109401109402109403109404109405109406109407109408109409109410109411109412109413109414109415109416109417109418109419109420109421109422109423109424109425109426109427109428109429109430109431109432109433109434109435109436109437109438109439109440109441109442109443109444109445109446109447109448109449109450109451109452109453109454109455109456109457109458109459109460109461109462109463109464109465109466109467109468109469109470109471109472109473109474109475109476109477109478109479109480109481109482109483109484109485109486109487109488109489109490109491109492109493109494109495109496109497109498109499109500109501109502109503109504109505109506109507109508109509109510109511109512109513109514109515109516109517109518109519109520109521109522109523109524109525109526109527109528109529109530109531109532109533109534109535109536109537109538109539109540109541109542109543109544109545109546109547109548109549109550109551109552109553109554109555109556109557109558109559109560109561109562109563109564109565109566109567109568109569109570109571109572109573109574109575109576109577109578109579109580109581109582109583109584109585109586109587109588109589109590109591109592109593109594109595109596109597109598109599109600109601109602109603109604109605109606109607109608109609109610109611109612109613109614109615109616109617109618109619109620109621109622109623109624109625109626109627109628109629109630109631109632109633109634109635109636109637109638109639109640109641109642109643109644109645109646109647109648109649109650109651109652109653109654109655109656109657109658109659109660109661109662109663109664109665109666109667109668109669109670109671109672109673109674109675109676109677109678109679109680109681109682109683109684109685109686109687109688109689109690109691109692109693109694109695109696109697109698109699109700109701109702109703109704109705109706109707109708109709109710109711109712109713109714109715109716109717109718109719109720109721109722109723109724109725109726109727109728109729109730109731109732109733109734109735109736109737109738109739109740109741109742109743109744109745109746109747109748109749109750109751109752109753109754109755109756109757109758109759109760109761109762109763109764109765109766109767109768109769109770109771109772109773109774109775109776109777109778109779109780109781109782109783109784109785109786109787109788109789109790109791109792109793109794109795109796109797109798109799109800109801109802109803109804109805109806109807109808109809109810109811109812109813109814109815109816109817109818109819109820109821109822109823109824109825109826109827109828109829109830109831109832109833109834109835109836109837109838109839109840109841109842109843109844109845109846109847109848109849109850109851109852109853109854109855109856109857109858109859109860109861109862109863109864109865109866109867109868109869109870109871109872109873109874109875109876109877109878109879109880109881109882109883109884109885109886109887109888109889109890109891109892109893109894109895109896109897109898109899109900109901109902109903109904109905109906109907109908109909109910109911109912109913109914109915109916109917109918109919109920109921109922109923109924109925109926109927109928109929109930109931109932109933109934109935109936109937109938109939109940109941109942109943109944109945109946109947109948109949109950109951109952109953109954109955109956109957109958109959109960109961109962109963109964109965109966109967109968109969109970109971109972109973109974109975109976109977109978109979109980109981109982109983109984109985109986109987109988109989109990109991109992109993109994109995109996109997109998109999110000110001110002110003110004110005110006110007110008110009110010110011110012110013110014110015110016110017110018110019110020110021110022110023110024110025110026110027110028110029110030110031110032110033110034110035110036110037110038110039110040110041110042110043110044110045110046110047110048110049110050110051110052110053110054110055110056110057110058110059110060110061110062110063110064110065110066110067110068110069110070110071110072110073110074110075110076110077110078110079110080110081110082110083110084110085110086110087110088110089110090110091110092110093110094110095110096110097110098110099110100110101110102110103110104110105110106110107110108110109110110110111110112110113110114110115110116110117110118110119110120110121110122110123110124110125110126110127110128110129110130110131110132110133110134110135110136110137110138110139110140110141110142110143110144110145110146110147110148110149110150110151110152110153110154110155110156110157110158110159110160110161110162110163110164110165110166110167110168110169110170110171110172110173110174110175110176110177110178110179110180110181110182110183110184110185110186110187110188110189110190110191110192110193110194110195110196110197110198110199110200110201110202110203110204110205110206110207110208110209110210110211110212110213110214110215110216110217110218110219110220110221110222110223110224110225110226110227110228110229110230110231110232110233110234110235110236110237110238110239110240110241110242110243110244110245110246110247110248110249110250110251110252110253110254110255110256110257110258110259110260110261110262110263110264110265110266110267110268110269110270110271110272110273110274110275110276110277110278110279110280110281110282110283110284110285110286110287110288110289110290110291110292110293110294110295110296110297110298110299110300110301110302110303110304110305110306110307110308110309110310110311110312110313110314110315110316110317110318110319110320110321110322110323110324110325110326110327110328110329110330110331110332110333110334110335110336110337110338110339110340110341110342110343110344110345110346110347110348110349110350110351110352110353110354110355110356110357110358110359110360110361110362110363110364110365110366110367110368110369110370110371110372110373110374110375110376110377110378110379110380110381110382110383110384110385110386110387110388110389110390110391110392110393110394110395110396110397110398110399110400110401110402110403110404110405110406110407110408110409110410110411110412110413110414110415110416110417110418110419110420110421110422110423110424110425110426110427110428110429110430110431110432110433110434110435110436110437110438110439110440110441110442110443110444110445110446110447110448110449110450110451110452110453110454110455110456110457110458110459110460110461110462110463110464110465110466110467110468110469110470110471110472110473110474110475110476110477110478110479110480110481110482110483110484110485110486110487110488110489110490110491110492110493110494110495110496110497110498110499110500110501110502110503110504110505110506110507110508110509110510110511110512110513110514110515110516110517110518110519110520110521110522110523110524110525110526110527110528110529110530110531110532110533110534110535110536110537110538110539110540110541110542110543110544110545110546110547110548110549110550110551110552110553110554110555110556110557110558110559110560110561110562110563110564110565110566110567110568110569110570110571110572110573110574110575110576110577110578110579110580110581110582110583110584110585110586110587110588110589110590110591110592110593110594110595110596110597110598110599110600110601110602110603110604110605110606110607110608110609110610110611110612110613110614110615110616110617110618110619110620110621110622110623110624110625110626110627110628110629110630110631110632110633110634110635110636110637110638110639110640110641110642110643110644110645110646110647110648110649110650110651110652110653110654110655110656110657110658110659110660110661110662110663110664110665110666110667110668110669110670110671110672110673110674110675110676110677110678110679110680110681110682110683110684110685110686110687110688110689110690110691110692110693110694110695110696110697110698110699110700110701110702110703110704110705110706110707110708110709110710110711110712110713110714110715110716110717110718110719110720110721110722110723110724110725110726110727110728110729110730110731110732110733110734110735110736110737110738110739110740110741110742110743110744110745110746110747110748110749110750110751110752110753110754110755110756110757110758110759110760110761110762110763110764110765110766110767110768110769110770110771110772110773110774110775110776110777110778110779110780110781110782110783110784110785110786110787110788110789110790110791110792110793110794110795110796110797110798110799110800110801110802110803110804110805110806110807110808110809110810110811110812110813110814110815110816110817110818110819110820110821110822110823110824110825110826110827110828110829110830110831110832110833110834110835110836110837110838110839110840110841110842110843110844110845110846110847110848110849110850110851110852110853110854110855110856110857110858110859110860110861110862110863110864110865110866110867110868110869110870110871110872110873110874110875110876110877110878110879110880110881110882110883110884110885110886110887110888110889110890110891110892110893110894110895110896110897110898110899110900110901110902110903110904110905110906110907110908110909110910110911110912110913110914110915110916110917110918110919110920110921110922110923110924110925110926110927110928110929110930110931110932110933110934110935110936110937110938110939110940110941110942110943110944110945110946110947110948110949110950110951110952110953110954110955110956110957110958110959110960110961110962110963110964110965110966110967110968110969110970110971110972110973110974110975110976110977110978110979110980110981110982110983110984110985110986110987110988110989110990110991110992110993110994110995110996110997110998110999111000111001111002111003111004111005111006111007111008111009111010111011111012111013111014111015111016111017111018111019111020111021111022111023111024111025111026111027111028111029111030111031111032111033111034111035111036111037111038111039111040111041111042111043111044111045111046111047111048111049111050111051111052111053111054111055111056111057111058111059111060111061111062111063111064111065111066111067111068111069111070111071111072111073111074111075111076111077111078111079111080111081111082111083111084111085111086111087111088111089111090111091111092111093111094111095111096111097111098111099111100111101111102111103111104111105111106111107111108111109111110111111111112111113111114111115111116111117111118111119111120111121111122111123111124111125111126111127111128111129111130111131111132111133111134111135111136111137111138111139111140111141111142111143111144111145111146111147111148111149111150111151111152111153111154111155111156111157111158111159111160111161111162111163111164111165111166111167111168111169111170111171111172111173111174111175111176111177111178111179111180111181111182111183111184111185111186111187111188111189111190111191111192111193111194111195111196111197111198111199111200111201111202111203111204111205111206111207111208111209111210111211111212111213111214111215111216111217111218111219111220111221111222111223111224111225111226111227111228111229111230111231111232111233111234111235111236111237111238111239111240111241111242111243111244111245111246111247111248111249111250111251111252111253111254111255111256111257111258111259111260111261111262111263111264111265111266111267111268111269111270111271111272111273111274111275111276111277111278111279111280111281111282111283111284111285111286111287111288111289111290111291111292111293111294111295111296111297111298111299111300111301111302111303111304111305111306111307111308111309111310111311111312111313111314111315111316111317111318111319111320111321111322111323111324111325111326111327111328111329111330111331111332111333111334111335111336111337111338111339111340111341111342111343111344111345111346111347111348111349111350111351111352111353111354111355111356111357111358111359111360111361111362111363111364111365111366111367111368111369111370111371111372111373111374111375111376111377111378111379111380111381111382111383111384111385111386111387111388111389111390111391111392111393111394111395111396111397111398111399111400111401111402111403111404111405111406111407111408111409111410111411111412111413111414111415111416111417111418111419111420111421111422111423111424111425111426111427111428111429111430111431111432111433111434111435111436111437111438111439111440111441111442111443111444111445111446111447111448111449111450111451111452111453111454111455111456111457111458111459111460111461111462111463111464111465111466111467111468111469111470111471111472111473111474111475111476111477111478111479111480111481111482111483111484111485111486111487111488111489111490111491111492111493111494111495111496111497111498111499111500111501111502111503111504111505111506111507111508111509111510111511111512111513111514111515111516111517111518111519111520111521111522111523111524111525111526111527111528111529111530111531111532111533111534111535111536111537111538111539111540111541111542111543111544111545111546111547111548111549111550111551111552111553111554111555111556111557111558111559111560111561111562111563111564111565111566111567111568111569111570111571111572111573111574111575111576111577111578111579111580111581111582111583111584111585111586111587111588111589111590111591111592111593111594111595111596111597111598111599111600111601111602111603111604111605111606111607111608111609111610111611111612111613111614111615111616111617111618111619111620111621111622111623111624111625111626111627111628111629111630111631111632111633111634111635111636111637111638111639111640111641111642111643111644111645111646111647111648111649111650111651111652111653111654111655111656111657111658111659111660111661111662111663111664111665111666111667111668111669111670111671111672111673111674111675111676111677111678111679111680111681111682111683111684111685111686111687111688111689111690111691111692111693111694111695111696111697111698111699111700111701111702111703111704111705111706111707111708111709111710111711111712111713111714111715111716111717111718111719111720111721111722111723111724111725111726111727111728111729111730111731111732111733111734111735111736111737111738111739111740111741111742111743111744111745111746111747111748111749111750111751111752111753111754111755111756111757111758111759111760111761111762111763111764111765111766111767111768111769111770111771111772111773111774111775111776111777111778111779111780111781111782111783111784111785111786111787111788111789111790111791111792111793111794111795111796111797111798111799111800111801111802111803111804111805111806111807111808111809111810111811111812111813111814111815111816111817111818111819111820111821111822111823111824111825111826111827111828111829111830111831111832111833111834111835111836111837111838111839111840111841111842111843111844111845111846111847111848111849111850111851111852111853111854111855111856111857111858111859111860111861111862111863111864111865111866111867111868111869111870111871111872111873111874111875111876111877111878111879111880111881111882111883111884111885111886111887111888111889111890111891111892111893111894111895111896111897111898111899111900111901111902111903111904111905111906111907111908111909111910111911111912111913111914111915111916111917111918111919111920111921111922111923111924111925111926111927111928111929111930111931111932111933111934111935111936111937111938111939111940111941111942111943111944111945111946111947111948111949111950111951111952111953111954111955111956111957111958111959111960111961111962111963111964111965111966111967111968111969111970111971111972111973111974111975111976111977111978111979111980111981111982111983111984111985111986111987111988111989111990111991111992111993111994111995111996111997111998111999112000112001112002112003112004112005112006112007112008112009112010112011112012112013112014112015112016112017112018112019112020112021112022112023112024112025112026112027112028112029112030112031112032112033112034112035112036112037112038112039112040112041112042112043112044112045112046112047112048112049112050112051112052112053112054112055112056112057112058112059112060112061112062112063112064112065112066112067112068112069112070112071112072112073112074112075112076112077112078112079112080112081112082112083112084112085112086112087112088112089112090112091112092112093112094112095112096112097112098112099112100112101112102112103112104112105112106112107112108112109112110112111112112112113112114112115112116112117112118112119112120112121112122112123112124112125112126112127112128112129112130112131112132112133112134112135112136112137112138112139112140112141112142112143112144112145112146112147112148112149112150112151112152112153112154112155112156112157112158112159112160112161112162112163112164112165112166112167112168112169112170112171112172112173112174112175112176112177112178112179112180112181112182112183112184112185112186112187112188112189112190112191112192112193112194112195112196112197112198112199112200112201112202112203112204112205112206112207112208112209112210112211112212112213112214112215112216112217112218112219112220112221112222112223112224112225112226112227112228112229112230112231112232112233112234112235112236112237112238112239112240112241112242112243112244112245112246112247112248112249112250112251112252112253112254112255112256112257112258112259112260112261112262112263112264112265112266112267112268112269112270112271112272112273112274112275112276112277112278112279112280112281112282112283112284112285112286112287112288112289112290112291112292112293112294112295112296112297112298112299112300112301112302112303112304112305112306112307112308112309112310112311112312112313112314112315112316112317112318112319112320112321112322112323112324112325112326112327112328112329112330112331112332112333112334112335112336112337112338112339112340112341112342112343112344112345112346112347112348112349112350112351112352112353112354112355112356112357112358112359112360112361112362112363112364112365112366112367112368112369112370112371112372112373112374112375112376112377112378112379112380112381112382112383112384112385112386112387112388112389112390112391112392112393112394112395112396112397112398112399112400112401112402112403112404112405112406112407112408112409112410112411112412112413112414112415112416112417112418112419112420112421112422112423112424112425112426112427112428112429112430112431112432112433112434112435112436112437112438112439112440112441112442112443112444112445112446112447112448112449112450112451112452112453112454112455112456112457112458112459112460112461112462112463112464112465112466112467112468112469112470112471112472112473112474112475112476112477112478112479112480112481112482112483112484112485112486112487112488112489112490112491112492112493112494112495112496112497112498112499112500112501112502112503112504112505112506112507112508112509112510112511112512112513112514112515112516112517112518112519112520112521112522112523112524112525112526112527112528112529112530112531112532112533112534112535112536112537112538112539112540112541112542112543112544112545112546112547112548112549112550112551112552112553112554112555112556112557112558112559112560112561112562112563112564112565112566112567112568112569112570112571112572112573112574112575112576112577112578112579112580112581112582112583112584112585112586112587112588112589112590112591112592112593112594112595112596112597112598112599112600112601112602112603112604112605112606112607112608112609112610112611112612112613112614112615112616112617112618112619112620112621112622112623112624112625112626112627112628112629112630112631112632112633112634112635112636112637112638112639112640112641112642112643112644112645112646112647112648112649112650112651112652112653112654112655112656112657112658112659112660112661112662112663112664112665112666112667112668112669112670112671112672112673112674112675112676112677112678112679112680112681112682112683112684112685112686112687112688112689112690112691112692112693112694112695112696112697112698112699112700112701112702112703112704112705112706112707112708112709112710112711112712112713112714112715112716112717112718112719112720112721112722112723112724112725112726112727112728112729112730112731112732112733112734112735112736112737112738112739112740112741112742112743112744112745112746112747112748112749112750112751112752112753112754112755112756112757112758112759112760112761112762112763112764112765112766112767112768112769112770112771112772112773112774112775112776112777112778112779112780112781112782112783112784112785112786112787112788112789112790112791112792112793112794112795112796112797112798112799112800112801112802112803112804112805112806112807112808112809112810112811112812112813112814112815112816112817112818112819112820112821112822112823112824112825112826112827112828112829112830112831112832112833112834112835112836112837112838112839112840112841112842112843112844112845112846112847112848112849112850112851112852112853112854112855112856112857112858112859112860112861112862112863112864112865112866112867112868112869112870112871112872112873112874112875112876112877112878112879112880112881112882112883112884112885112886112887112888112889112890112891112892112893112894112895112896112897112898112899112900112901112902112903112904112905112906112907112908112909112910112911112912112913112914112915112916112917112918112919112920112921112922112923112924112925112926112927112928112929112930112931112932112933112934112935112936112937112938112939112940112941112942112943112944112945112946112947112948112949112950112951112952112953112954112955112956112957112958112959112960112961112962112963112964112965112966112967112968112969112970112971112972112973112974112975112976112977112978112979112980112981112982112983112984112985112986112987112988112989112990112991112992112993112994112995112996112997112998112999113000113001113002113003113004113005113006113007113008113009113010113011113012113013113014113015113016113017113018113019113020113021113022113023113024113025113026113027113028113029113030113031113032113033113034113035113036113037113038113039113040113041113042113043113044113045113046113047113048113049113050113051113052113053113054113055113056113057113058113059113060113061113062113063113064113065113066113067113068113069113070113071113072113073113074113075113076113077113078113079113080113081113082113083113084113085113086113087113088113089113090113091113092113093113094113095113096113097113098113099113100113101113102113103113104113105113106113107113108113109113110113111113112113113113114113115113116113117113118113119113120113121113122113123113124113125113126113127113128113129113130113131113132113133113134113135113136113137113138113139113140113141113142113143113144113145113146113147113148113149113150113151113152113153113154113155113156113157113158113159113160113161113162113163113164113165113166113167113168113169113170113171113172113173113174113175113176113177113178113179113180113181113182113183113184113185113186113187113188113189113190113191113192113193113194113195113196113197113198113199113200113201113202113203113204113205113206113207113208113209113210113211113212113213113214113215113216113217113218113219113220113221113222113223113224113225113226113227113228113229113230113231113232113233113234113235113236113237113238113239113240113241113242113243113244113245113246113247113248113249113250113251113252113253113254113255113256113257113258113259113260113261113262113263113264113265113266113267113268113269113270113271113272113273113274113275113276113277113278113279113280113281113282113283113284113285113286113287113288113289113290113291113292113293113294113295113296113297113298113299113300113301113302113303113304113305113306113307113308113309113310113311113312113313113314113315113316113317113318113319113320113321113322113323113324113325113326113327113328113329113330113331113332113333113334113335113336113337113338113339113340113341113342113343113344113345113346113347113348113349113350113351113352113353113354113355113356113357113358113359113360113361113362113363113364113365113366113367113368113369113370113371113372113373113374113375113376113377113378113379113380113381113382113383113384113385113386113387113388113389113390113391113392113393113394113395113396113397113398113399113400113401113402113403113404113405113406113407113408113409113410113411113412113413113414113415113416113417113418113419113420113421113422113423113424113425113426113427113428113429113430113431113432113433113434113435113436113437113438113439113440113441113442113443113444113445113446113447113448113449113450113451113452113453113454113455113456113457113458113459113460113461113462113463113464113465113466113467113468113469113470113471113472113473113474113475113476113477113478113479113480113481113482113483113484113485113486113487113488113489113490113491113492113493113494113495113496113497113498113499113500113501113502113503113504113505113506113507113508113509113510113511113512113513113514113515113516113517113518113519113520113521113522113523113524113525113526113527113528113529113530113531113532113533113534113535113536113537113538113539113540113541113542113543113544113545113546113547113548113549113550113551113552113553113554113555113556113557113558113559113560113561113562113563113564113565113566113567113568113569113570113571113572113573113574113575113576113577113578113579113580113581113582113583113584113585113586113587113588113589113590113591113592113593113594113595113596113597113598113599113600113601113602113603113604113605113606113607113608113609113610113611113612113613113614113615113616113617113618113619113620113621113622113623113624113625113626113627113628113629113630113631113632113633113634113635113636113637113638113639113640113641113642113643113644113645113646113647113648113649113650113651113652113653113654113655113656113657113658113659113660113661113662113663113664113665113666113667113668113669113670113671113672113673113674113675113676113677113678113679113680113681113682113683113684113685113686113687113688113689113690113691113692113693113694113695113696113697113698113699113700113701113702113703113704113705113706113707113708113709113710113711113712113713113714113715113716113717113718113719113720113721113722113723113724113725113726113727113728113729113730113731113732113733113734113735113736113737113738113739113740113741113742113743113744113745113746113747113748113749113750113751113752113753113754113755113756113757113758113759113760113761113762113763113764113765113766113767113768113769113770113771113772113773113774113775113776113777113778113779113780113781113782113783113784113785113786113787113788113789113790113791113792113793113794113795113796113797113798113799113800113801113802113803113804113805113806113807113808113809113810113811113812113813113814113815113816113817113818113819113820113821113822113823113824113825113826113827113828113829113830113831113832113833113834113835113836113837113838113839113840113841113842113843113844113845113846113847113848113849113850113851113852113853113854113855113856113857113858113859113860113861113862113863113864113865113866113867113868113869113870113871113872113873113874113875113876113877113878113879113880113881113882113883113884113885113886113887113888113889113890113891113892113893113894113895113896113897113898113899113900113901113902113903113904113905113906113907113908113909113910113911113912113913113914113915113916113917113918113919113920113921113922113923113924113925113926113927113928113929113930113931113932113933113934113935113936113937113938113939113940113941113942113943113944113945113946113947113948113949113950113951113952113953113954113955113956113957113958113959113960113961113962113963113964113965113966113967113968113969113970113971113972113973113974113975113976113977113978113979113980113981113982113983113984113985113986113987113988113989113990113991113992113993113994113995113996113997113998113999114000114001114002114003114004114005114006114007114008114009114010114011114012114013114014114015114016114017114018114019114020114021114022114023114024114025114026114027114028114029114030114031114032114033114034114035114036114037114038114039114040114041114042114043114044114045114046114047114048114049114050114051114052114053114054114055114056114057114058114059114060114061114062114063114064114065114066114067114068114069114070114071114072114073114074114075114076114077114078114079114080114081114082114083114084114085114086114087114088114089114090114091114092114093114094114095114096114097114098114099114100114101114102114103114104114105114106114107114108114109114110114111114112114113114114114115114116114117114118114119114120114121114122114123114124114125114126114127114128114129114130114131114132114133114134114135114136114137114138114139114140114141114142114143114144114145114146114147114148114149114150114151114152114153114154114155114156114157114158114159114160114161114162114163114164114165114166114167114168114169114170114171114172114173114174114175114176114177114178114179114180114181114182114183114184114185114186114187114188114189114190114191114192114193114194114195114196114197114198114199114200114201114202114203114204114205114206114207114208114209114210114211114212114213114214114215114216114217114218114219114220114221114222114223114224114225114226114227114228114229114230114231114232114233114234114235114236114237114238114239114240114241114242114243114244114245114246114247114248114249114250114251114252114253114254114255114256114257114258114259114260114261114262114263114264114265114266114267114268114269114270114271114272114273114274114275114276114277114278114279114280114281114282114283114284114285114286114287114288114289114290114291114292114293114294114295114296114297114298114299114300114301114302114303114304114305114306114307114308114309114310114311114312114313114314114315114316114317114318114319114320114321114322114323114324114325114326114327114328114329114330114331114332114333114334114335114336114337114338114339114340114341114342114343114344114345114346114347114348114349114350114351114352114353114354114355114356114357114358114359114360114361114362114363114364114365114366114367114368114369114370114371114372114373114374114375114376114377114378114379114380114381114382114383114384114385114386114387114388114389114390114391114392114393114394114395114396114397114398114399114400114401114402114403114404114405114406114407114408114409114410114411114412114413114414114415114416114417114418114419114420114421114422114423114424114425114426114427114428114429114430114431114432114433114434114435114436114437114438114439114440114441114442114443114444114445114446114447114448114449114450114451114452114453114454114455114456114457114458114459114460114461114462114463114464114465114466114467114468114469114470114471114472114473114474114475114476114477114478114479114480114481114482114483114484114485114486114487114488114489114490114491114492114493114494114495114496114497114498114499114500114501114502114503114504114505114506114507114508114509114510114511114512114513114514114515114516114517114518114519114520114521114522114523114524114525114526114527114528114529114530114531114532114533114534114535114536114537114538114539114540114541114542114543114544114545114546114547114548114549114550114551114552114553114554114555114556114557114558114559114560114561114562114563114564114565114566114567114568114569114570114571114572114573114574114575114576114577114578114579114580114581114582114583114584114585114586114587114588114589114590114591114592114593114594114595114596114597114598114599114600114601114602114603114604114605114606114607114608114609114610114611114612114613114614114615114616114617114618114619114620114621114622114623114624114625114626114627114628114629114630114631114632114633114634114635114636114637114638114639114640114641114642114643114644114645114646114647114648114649114650114651114652114653114654114655114656114657114658114659114660114661114662114663114664114665114666114667114668114669114670114671114672114673114674114675114676114677114678114679114680114681114682114683114684114685114686114687114688114689114690114691114692114693114694114695114696114697114698114699114700114701114702114703114704114705114706114707114708114709114710114711114712114713114714114715114716114717114718114719114720114721114722114723114724114725114726114727114728114729114730114731114732114733114734114735114736114737114738114739114740114741114742114743114744114745114746114747114748114749114750114751114752114753114754114755114756114757114758114759114760114761114762114763114764114765114766114767114768114769114770114771114772114773114774114775114776114777114778114779114780114781114782114783114784114785114786114787114788114789114790114791114792114793114794114795114796114797114798114799114800114801114802114803114804114805114806114807114808114809114810114811114812114813114814114815114816114817114818114819114820114821114822114823114824114825114826114827114828114829114830114831114832114833114834114835114836114837114838114839114840114841114842114843114844114845114846114847114848114849114850114851114852114853114854114855114856114857114858114859114860114861114862114863114864114865114866114867114868114869114870114871114872114873114874114875114876114877114878114879114880114881114882114883114884114885114886114887114888114889114890114891114892114893114894114895114896114897114898114899114900114901114902114903114904114905114906114907114908114909114910114911114912114913114914114915114916114917114918114919114920114921114922114923114924114925114926114927114928114929114930114931114932114933114934114935114936114937114938114939114940114941114942114943114944114945114946114947114948114949114950114951114952114953114954114955114956114957114958114959114960114961114962114963114964114965114966114967114968114969114970114971114972114973114974114975114976114977114978114979114980114981114982114983114984114985114986114987114988114989114990114991114992114993114994114995114996114997114998114999115000115001115002115003115004115005115006115007115008115009115010115011115012115013115014115015115016115017115018115019115020115021115022115023115024115025115026115027115028115029115030115031115032115033115034115035115036115037115038115039115040115041115042115043115044115045115046115047115048115049115050115051115052115053115054115055115056115057115058115059115060115061115062115063115064115065115066115067115068115069115070115071115072115073115074115075115076115077115078115079115080115081115082115083115084115085115086115087115088115089115090115091115092115093115094115095115096115097115098115099115100115101115102115103115104115105115106115107115108115109115110115111115112115113115114115115115116115117115118115119115120115121115122115123115124115125115126115127115128115129115130115131115132115133115134115135115136115137115138115139115140115141115142115143115144115145115146115147115148115149115150115151115152115153115154115155115156115157115158115159115160115161115162115163115164115165115166115167115168115169115170115171115172115173115174115175115176115177115178115179115180115181115182115183115184115185115186115187115188115189115190115191115192115193115194115195115196115197115198115199115200115201115202115203115204115205115206115207115208115209115210115211115212115213115214115215115216115217115218115219115220115221115222115223115224115225115226115227115228115229115230115231115232115233115234115235115236115237115238115239115240115241115242115243115244115245115246115247115248115249115250115251115252115253115254115255115256115257115258115259115260115261115262115263115264115265115266115267115268115269115270115271115272115273115274115275115276115277115278115279115280115281115282115283115284115285115286115287115288115289115290115291115292115293115294115295115296115297115298115299115300115301115302115303115304115305115306115307115308115309115310115311115312115313115314115315115316115317115318115319115320115321115322115323115324115325115326115327115328115329115330115331115332115333115334115335115336115337115338115339115340115341115342115343115344115345115346115347115348115349115350115351115352115353115354115355115356115357115358115359115360115361115362115363115364115365115366115367115368115369115370115371115372115373115374115375115376115377115378115379115380115381115382115383115384115385115386115387115388115389115390115391115392115393115394115395115396115397115398115399115400115401115402115403115404115405115406115407115408115409115410115411115412115413115414115415115416115417115418115419115420115421115422115423115424115425115426115427115428115429115430115431115432115433115434115435115436115437115438115439115440115441115442115443115444115445115446115447115448115449115450115451115452115453115454115455115456115457115458115459115460115461115462115463115464115465115466115467115468115469115470115471115472115473115474115475115476115477115478115479115480115481115482115483115484115485115486115487115488115489115490115491115492115493115494115495115496115497115498115499115500115501115502115503115504115505115506115507115508115509115510115511115512115513115514115515115516115517115518115519115520115521115522115523115524115525115526115527115528115529115530115531115532115533115534115535115536115537115538115539115540115541115542115543115544115545115546115547115548115549115550115551115552115553115554115555115556115557115558115559115560115561115562115563115564115565115566115567115568115569115570115571115572115573115574115575115576115577115578115579115580115581115582115583115584115585115586115587115588115589115590115591115592115593115594115595115596115597115598115599115600115601115602115603115604115605115606115607115608115609115610115611115612115613115614115615115616115617115618115619115620115621115622115623115624115625115626115627115628115629115630115631115632115633115634115635115636115637115638115639115640115641115642115643115644115645115646115647115648115649115650115651115652115653115654115655115656115657115658115659115660115661115662115663115664115665115666115667115668115669115670115671115672115673115674115675115676115677115678115679115680115681115682115683115684115685115686115687115688115689115690115691115692115693115694115695115696115697115698115699115700115701115702115703115704115705115706115707115708115709115710115711115712115713115714115715115716115717115718115719115720115721115722115723115724115725115726115727115728115729115730115731115732115733115734115735115736115737115738115739115740115741115742115743115744115745115746115747115748115749115750115751115752115753115754115755115756115757115758115759115760115761115762115763115764115765115766115767115768115769115770115771115772115773115774115775115776115777115778115779115780115781115782115783115784115785115786115787115788115789115790115791115792115793115794115795115796115797115798115799115800115801115802115803115804115805115806115807115808115809115810115811115812115813115814115815115816115817115818115819115820115821115822115823115824115825115826115827115828115829115830115831115832115833115834115835115836115837115838115839115840115841115842115843115844115845115846115847115848115849115850115851115852115853115854115855115856115857115858115859115860115861115862115863115864115865115866115867115868115869115870115871115872115873115874115875115876115877115878115879115880115881115882115883115884115885115886115887115888115889115890115891115892115893115894115895115896115897115898115899115900115901115902115903115904115905115906115907115908115909115910115911115912115913115914115915115916115917115918115919115920115921115922115923115924115925115926115927115928115929115930115931115932115933115934115935115936115937115938115939115940115941115942115943115944115945115946115947115948115949115950115951115952115953115954115955115956115957115958115959115960115961115962115963115964115965115966115967115968115969115970115971115972115973115974115975115976115977115978115979115980115981115982115983115984115985115986115987115988115989115990115991115992115993115994115995115996115997115998115999116000116001116002116003116004116005116006116007116008116009116010116011116012116013116014116015116016116017116018116019116020116021116022116023116024116025116026116027116028116029116030116031116032116033116034116035116036116037116038116039116040116041116042116043116044116045116046116047116048116049116050116051116052116053116054116055116056116057116058116059116060116061116062116063116064116065116066116067116068116069116070116071116072116073116074116075116076116077116078116079116080116081116082116083116084116085116086116087116088116089116090116091116092116093116094116095116096116097116098116099116100116101116102116103116104116105116106116107116108116109116110116111116112116113116114116115116116116117116118116119116120116121116122116123116124116125116126116127116128116129116130116131116132116133116134116135116136116137116138116139116140116141116142116143116144116145116146116147116148116149116150116151116152116153116154116155116156116157116158116159116160116161116162116163116164116165116166116167116168116169116170116171116172116173116174116175116176116177116178116179116180116181116182116183116184116185116186116187116188116189116190116191116192116193116194116195116196116197116198116199116200116201116202116203116204116205116206116207116208116209116210116211116212116213116214116215116216116217116218116219116220116221116222116223116224116225116226116227116228116229116230116231116232116233116234116235116236116237116238116239116240116241116242116243116244116245116246116247116248116249116250116251116252116253116254116255116256116257116258116259116260116261116262116263116264116265116266116267116268116269116270116271116272116273116274116275116276116277116278116279116280116281116282116283116284116285116286116287116288116289116290116291116292116293116294116295116296116297116298116299116300116301116302116303116304116305116306116307116308116309116310116311116312116313116314116315116316116317116318116319116320116321116322116323116324116325116326116327116328116329116330116331116332116333116334116335116336116337116338116339116340116341116342116343116344116345116346116347116348116349116350116351116352116353116354116355116356116357116358116359116360116361116362116363116364116365116366116367116368116369116370116371116372116373116374116375116376116377116378116379116380116381116382116383116384116385116386116387116388116389116390116391116392116393116394116395116396116397116398116399116400116401116402116403116404116405116406116407116408116409116410116411116412116413116414116415116416116417116418116419116420116421116422116423116424116425116426116427116428116429116430116431116432116433116434116435116436116437116438116439116440116441116442116443116444116445116446116447116448116449116450116451116452116453116454116455116456116457116458116459116460116461116462116463116464116465116466116467116468116469116470116471116472116473116474116475116476116477116478116479116480116481116482116483116484116485116486116487116488116489116490116491116492116493116494116495116496116497116498116499116500116501116502116503116504116505116506116507116508116509116510116511116512116513116514116515116516116517116518116519116520116521116522116523116524116525116526116527116528116529116530116531116532116533116534116535116536116537116538116539116540116541116542116543116544116545116546116547116548116549116550116551116552116553116554116555116556116557116558116559116560116561116562116563116564116565116566116567116568116569116570116571116572116573116574116575116576116577116578116579116580116581116582116583116584116585116586116587116588116589116590116591116592116593116594116595116596116597116598116599116600116601116602116603116604116605116606116607116608116609116610116611116612116613116614116615116616116617116618116619116620116621116622116623116624116625116626116627116628116629116630116631116632116633116634116635116636116637116638116639116640116641116642116643116644116645116646116647116648116649116650116651116652116653116654116655116656116657116658116659116660116661116662116663116664116665116666116667116668116669116670116671116672116673116674116675116676116677116678116679116680116681116682116683116684116685116686116687116688116689116690116691116692116693116694116695116696116697116698116699116700116701116702116703116704116705116706116707116708116709116710116711116712116713116714116715116716116717116718116719116720116721116722116723116724116725116726116727116728116729116730116731116732116733116734116735116736116737116738116739116740116741116742116743116744116745116746116747116748116749116750116751116752116753116754116755116756116757116758116759116760116761116762116763116764116765116766116767116768116769116770116771116772116773116774116775116776116777116778116779116780116781116782116783116784116785116786116787116788116789116790116791116792116793116794116795116796116797116798116799116800116801116802116803116804116805116806116807116808116809116810116811116812116813116814116815116816116817116818116819116820116821116822116823116824116825116826116827116828116829116830116831116832116833116834116835116836116837116838116839116840116841116842116843116844116845116846116847116848116849116850116851116852116853116854116855116856116857116858116859116860116861116862116863116864116865116866116867116868116869116870116871116872116873116874116875116876116877116878116879116880116881116882116883116884116885116886116887116888116889116890116891116892116893116894116895116896116897116898116899116900116901116902116903116904116905116906116907116908116909116910116911116912116913116914116915116916116917116918116919116920116921116922116923116924116925116926116927116928116929116930116931116932116933116934116935116936116937116938116939116940116941116942116943116944116945116946116947116948116949116950116951116952116953116954116955116956116957116958116959116960116961116962116963116964116965116966116967116968116969116970116971116972116973116974116975116976116977116978116979116980116981116982116983116984116985116986116987116988116989116990116991116992116993116994116995116996116997116998116999117000117001117002117003117004117005117006117007117008117009117010117011117012117013117014117015117016117017117018117019117020117021117022117023117024117025117026117027117028117029117030117031117032117033117034117035117036117037117038117039117040117041117042117043117044117045117046117047117048117049117050117051117052117053117054117055117056117057117058117059117060117061117062117063117064117065117066117067117068117069117070117071117072117073117074117075117076117077117078117079117080117081117082117083117084117085117086117087117088117089117090117091117092117093117094117095117096117097117098117099117100117101117102117103117104117105117106117107117108117109117110117111117112117113117114117115117116117117117118117119117120117121117122117123117124117125117126117127117128117129117130117131117132117133117134117135117136117137117138117139117140117141117142117143117144117145117146117147117148117149117150117151117152117153117154117155117156117157117158117159117160117161117162117163117164117165117166117167117168117169117170117171117172117173117174117175117176117177117178117179117180117181117182117183117184117185117186117187117188117189117190117191117192117193117194117195117196117197117198117199117200117201117202117203117204117205117206117207117208117209117210117211117212117213117214117215117216117217117218117219117220117221117222117223117224117225117226117227117228117229117230117231117232117233117234117235117236117237117238117239117240117241117242117243117244117245117246117247117248117249117250117251117252117253117254117255117256117257117258117259117260117261117262117263117264117265117266117267117268117269117270117271117272117273117274117275117276117277117278117279117280117281117282117283117284117285117286117287117288117289117290117291117292117293117294117295117296117297117298117299117300117301117302117303117304117305117306117307117308117309117310117311117312117313117314117315117316117317117318117319117320117321117322117323117324117325117326117327117328117329117330117331117332117333117334117335117336117337117338117339117340117341117342117343117344117345117346117347117348117349117350117351117352117353117354117355117356117357117358117359117360117361117362117363117364117365117366117367117368117369117370117371117372117373117374117375117376117377117378117379117380117381117382117383117384117385117386117387117388117389117390117391117392117393117394117395117396117397117398117399117400117401117402117403117404117405117406117407117408117409117410117411117412117413117414117415117416117417117418117419117420117421117422117423117424117425117426117427117428117429117430117431117432117433117434117435117436117437117438117439117440117441117442117443117444117445117446117447117448117449117450117451117452117453117454117455117456117457117458117459117460117461117462117463117464117465117466117467117468117469117470117471117472117473117474117475117476117477117478117479117480117481117482117483117484117485117486117487117488117489117490117491117492117493117494117495117496117497117498117499117500117501117502117503117504117505117506117507117508117509117510117511117512117513117514117515117516117517117518117519117520117521117522117523117524117525117526117527117528117529117530117531117532117533117534117535117536117537117538117539117540117541117542117543117544117545117546117547117548117549117550117551117552117553117554117555117556117557117558117559117560117561117562117563117564117565117566117567117568117569117570117571117572117573117574117575117576117577117578117579117580117581117582117583117584117585117586117587117588117589117590117591117592117593117594117595117596117597117598117599117600117601117602117603117604117605117606117607117608117609117610117611117612117613117614117615117616117617117618117619117620117621117622117623117624117625117626117627117628117629117630117631117632117633117634117635117636117637117638117639117640117641117642117643117644117645117646117647117648117649117650117651117652117653117654117655117656117657117658117659117660117661117662117663117664117665117666117667117668117669117670117671117672117673117674117675117676117677117678117679117680117681117682117683117684117685117686117687117688117689117690117691117692117693117694117695117696117697117698117699117700117701117702117703117704117705117706117707117708117709117710117711117712117713117714117715117716117717117718117719117720117721117722117723117724117725117726117727117728117729117730117731117732117733117734117735117736117737117738117739117740117741117742117743117744117745117746117747117748117749117750117751117752117753117754117755117756117757117758117759117760117761117762117763117764117765117766117767117768117769117770117771117772117773117774117775117776117777117778117779117780117781117782117783117784117785117786117787117788117789117790117791117792117793117794117795117796117797117798117799117800117801117802117803117804117805117806117807117808117809117810117811117812117813117814117815117816117817117818117819117820117821117822117823117824117825117826117827117828117829117830117831117832117833117834117835117836117837117838117839117840117841117842117843117844117845117846117847117848117849117850117851117852117853117854117855117856117857117858117859117860117861117862117863117864117865117866117867117868117869117870117871117872117873117874117875117876117877117878117879117880117881117882117883117884117885117886117887117888117889117890117891117892117893117894117895117896117897117898117899117900117901117902117903117904117905117906117907117908117909117910117911117912117913117914117915117916117917117918117919117920117921117922117923117924117925117926117927117928117929117930117931117932117933117934117935117936117937117938117939117940117941117942117943117944117945117946117947117948117949117950117951117952117953117954117955117956117957117958117959117960117961117962117963117964117965117966117967117968117969117970117971117972117973117974117975117976117977117978117979117980117981117982117983117984117985117986117987117988117989117990117991117992117993117994117995117996117997117998117999118000118001118002118003118004118005118006118007118008118009118010118011118012118013118014118015118016118017118018118019118020118021118022118023118024118025118026118027118028118029118030118031118032118033118034118035118036118037118038118039118040118041118042118043118044118045118046118047118048118049118050118051118052118053118054118055118056118057118058118059118060118061118062118063118064118065118066118067118068118069118070118071118072118073118074118075118076118077118078118079118080118081118082118083118084118085118086118087118088118089118090118091118092118093118094118095118096118097118098118099118100118101118102118103118104118105118106118107118108118109118110118111118112118113118114118115118116118117118118118119118120118121118122118123118124118125118126118127118128118129118130118131118132118133118134118135118136118137118138118139118140118141118142118143118144118145118146118147118148118149118150118151118152118153118154118155118156118157118158118159118160118161118162118163118164118165118166118167118168118169118170118171118172118173118174118175118176118177118178118179118180118181118182118183118184118185118186118187118188118189118190118191118192118193118194118195118196118197118198118199118200118201118202118203118204118205118206118207118208118209118210118211118212118213118214118215118216118217118218118219118220118221118222118223118224118225118226118227118228118229118230118231118232118233118234118235118236118237118238118239118240118241118242118243118244118245118246118247118248118249118250118251118252118253118254118255118256118257118258118259118260118261118262118263118264118265118266118267118268118269118270118271118272118273118274118275118276118277118278118279118280118281118282118283118284118285118286118287118288118289118290118291118292118293118294118295118296118297118298118299118300118301118302118303118304118305118306118307118308118309118310118311118312118313118314118315118316118317118318118319118320118321118322118323118324118325118326118327118328118329118330118331118332118333118334118335118336118337118338118339118340118341118342118343118344118345118346118347118348118349118350118351118352118353118354118355118356118357118358118359118360118361118362118363118364118365118366118367118368118369118370118371118372118373118374118375118376118377118378118379118380118381118382118383118384118385118386118387118388118389118390118391118392118393118394118395118396118397118398118399118400118401118402118403118404118405118406118407118408118409118410118411118412118413118414118415118416118417118418118419118420118421118422118423118424118425118426118427118428118429118430118431118432118433118434118435118436118437118438118439118440118441118442118443118444118445118446118447118448118449118450118451118452118453118454118455118456118457118458118459118460118461118462118463118464118465118466118467118468118469118470118471118472118473118474118475118476118477118478118479118480118481118482118483118484118485118486118487118488118489118490118491118492118493118494118495118496118497118498118499118500118501118502118503118504118505118506118507118508118509118510118511118512118513118514118515118516118517118518118519118520118521118522118523118524118525118526118527118528118529118530118531118532118533118534118535118536118537118538118539118540118541118542118543118544118545118546118547118548118549118550118551118552118553118554118555118556118557118558118559118560118561118562118563118564118565118566118567118568118569118570118571118572118573118574118575118576118577118578118579118580118581118582118583118584118585118586118587118588118589118590118591118592118593118594118595118596118597118598118599118600118601118602118603118604118605118606118607118608118609118610118611118612118613118614118615118616118617118618118619118620118621118622118623118624118625118626118627118628118629118630118631118632118633118634118635118636118637118638118639118640118641118642118643118644118645118646118647118648118649118650118651118652118653118654118655118656118657118658118659118660118661118662118663118664118665118666118667118668118669118670118671118672118673118674118675118676118677118678118679118680118681118682118683118684118685118686118687118688118689118690118691118692118693118694118695118696118697118698118699118700118701118702118703118704118705118706118707118708118709118710118711118712118713118714118715118716118717118718118719118720118721118722118723118724118725118726118727118728118729118730118731118732118733118734118735118736118737118738118739118740118741118742118743118744118745118746118747118748118749118750118751118752118753118754118755118756118757118758118759118760118761118762118763118764118765118766118767118768118769118770118771118772118773118774118775118776118777118778118779118780118781118782118783118784118785118786118787118788118789118790118791118792118793118794118795118796118797118798118799118800118801118802118803118804118805118806118807118808118809118810118811118812118813118814118815118816118817118818118819118820118821118822118823118824118825118826118827118828118829118830118831118832118833118834118835118836118837118838118839118840118841118842118843118844118845118846118847118848118849118850118851118852118853118854118855118856118857118858118859118860118861118862118863118864118865118866118867118868118869118870118871118872118873118874118875118876118877118878118879118880118881118882118883118884118885118886118887118888118889118890118891118892118893118894118895118896118897118898118899118900118901118902118903118904118905118906118907118908118909118910118911118912118913118914118915118916118917118918118919118920118921118922118923118924118925118926118927118928118929118930118931118932118933118934118935118936118937118938118939118940118941118942118943118944118945118946118947118948118949118950118951118952118953118954118955118956118957118958118959118960118961118962118963118964118965118966118967118968118969118970118971118972118973118974118975118976118977118978118979118980118981118982118983118984118985118986118987118988118989118990118991118992118993118994118995118996118997118998118999119000119001119002119003119004119005119006119007119008119009119010119011119012119013119014119015119016119017119018119019119020119021119022119023119024119025119026119027119028119029119030119031119032119033119034119035119036119037119038119039119040119041119042119043119044119045119046119047119048119049119050119051119052119053119054119055119056119057119058119059119060119061119062119063119064119065119066119067119068119069119070119071119072119073119074119075119076119077119078119079119080119081119082119083119084119085119086119087119088119089119090119091119092119093119094119095119096119097119098119099119100119101119102119103119104119105119106119107119108119109119110119111119112119113119114119115119116119117119118119119119120119121119122119123119124119125119126119127119128119129119130119131119132119133119134119135119136119137119138119139119140119141119142119143119144119145119146119147119148119149119150119151119152119153119154119155119156119157119158119159119160119161119162119163119164119165119166119167119168119169119170119171119172119173119174119175119176119177119178119179119180119181119182119183119184119185119186119187119188119189119190119191119192119193119194119195119196119197119198119199119200119201119202119203119204119205119206119207119208119209119210119211119212119213119214119215119216119217119218119219119220119221119222119223119224119225119226119227119228119229119230119231119232119233119234119235119236119237119238119239119240119241119242119243119244119245119246119247119248119249119250119251119252119253119254119255119256119257119258119259119260119261119262119263119264119265119266119267119268119269119270119271119272119273119274119275119276119277119278119279119280119281119282119283119284119285119286119287119288119289119290119291119292119293119294119295119296119297119298119299119300119301119302119303119304119305119306119307119308119309119310119311119312119313119314119315119316119317119318119319119320119321119322119323119324119325119326119327119328119329119330119331119332119333119334119335119336119337119338119339119340119341119342119343119344119345119346119347119348119349119350119351119352119353119354119355119356119357119358119359119360119361119362119363119364119365119366119367119368119369119370119371119372119373119374119375119376119377119378119379119380119381119382119383119384119385119386119387119388119389119390119391119392119393119394119395119396119397119398119399119400119401119402119403119404119405119406119407119408119409119410119411119412119413119414119415119416119417119418119419119420119421119422119423119424119425119426119427119428119429119430119431119432119433119434119435119436119437119438119439119440119441119442119443119444119445119446119447119448119449119450119451119452119453119454119455119456119457119458119459119460119461119462119463119464119465119466119467119468119469119470119471119472119473119474119475119476119477119478119479119480119481119482119483119484119485119486119487119488119489119490119491119492119493119494119495119496119497119498119499119500119501119502119503119504119505119506119507119508119509119510119511119512119513119514119515119516119517119518119519119520119521119522119523119524119525119526119527119528119529119530119531119532119533119534119535119536119537119538119539119540119541119542119543119544119545119546119547119548119549119550119551119552119553119554119555119556119557119558119559119560119561119562119563119564119565119566119567119568119569119570119571119572119573119574119575119576119577119578119579119580119581119582119583119584119585119586119587119588119589119590119591119592119593119594119595119596119597119598119599119600119601119602119603119604119605119606119607119608119609119610119611119612119613119614119615119616119617119618119619119620119621119622119623119624119625119626119627119628119629119630119631119632119633119634119635119636119637119638119639119640119641119642119643119644119645119646119647119648119649119650119651119652119653119654119655119656119657119658119659119660119661119662119663119664119665119666119667119668119669119670119671119672119673119674119675119676119677119678119679119680119681119682119683119684119685119686119687119688119689119690119691119692119693119694119695119696119697119698119699119700119701119702119703119704119705119706119707119708119709119710119711119712119713119714119715119716119717119718119719119720119721119722119723119724119725119726119727119728119729119730119731119732119733119734119735119736119737119738119739119740119741119742119743119744119745119746119747119748119749119750119751119752119753119754119755119756119757119758119759119760119761119762119763119764119765119766119767119768119769119770119771119772119773119774119775119776119777119778119779119780119781119782119783119784119785119786119787119788119789119790119791119792119793119794119795119796119797119798119799119800119801119802119803119804119805119806119807119808119809119810119811119812119813119814119815119816119817119818119819119820119821119822119823119824119825119826119827119828119829119830119831119832119833119834119835119836119837119838119839119840119841119842119843119844119845119846119847119848119849119850119851119852119853119854119855119856119857119858119859119860119861119862119863119864119865119866119867119868119869119870119871119872119873119874119875119876119877119878119879119880119881119882119883119884119885119886119887119888119889119890119891119892119893119894119895119896119897119898119899119900119901119902119903119904119905119906119907119908119909119910119911119912119913119914119915119916119917119918119919119920119921119922119923119924119925119926119927119928119929119930119931119932119933119934119935119936119937119938119939119940119941119942119943119944119945119946119947119948119949119950119951119952119953119954119955119956119957119958119959119960119961119962119963119964119965119966119967119968119969119970119971119972119973119974119975119976119977119978119979119980119981119982119983119984119985119986119987119988119989119990119991119992119993119994119995119996119997119998119999120000120001120002120003120004120005120006120007120008120009120010120011120012120013120014120015120016120017120018120019120020120021120022120023120024120025120026120027120028120029120030120031120032120033120034120035120036120037120038120039120040120041120042120043120044120045120046120047120048120049120050120051120052120053120054120055120056120057120058120059120060120061120062120063120064120065120066120067120068120069120070120071120072120073120074120075120076120077120078120079120080120081120082120083120084120085120086120087120088120089120090120091120092120093120094120095120096120097120098120099120100120101120102120103120104120105120106120107120108120109120110120111120112120113120114120115120116120117120118120119120120120121120122120123120124120125120126120127120128120129120130120131120132120133120134120135120136120137120138120139120140120141120142120143120144120145120146120147120148120149120150120151120152120153120154120155120156120157120158120159120160120161120162120163120164120165120166120167120168120169120170120171120172120173120174120175120176120177120178120179120180120181120182120183120184120185120186120187120188120189120190120191120192120193120194120195120196120197120198120199120200120201120202120203120204120205120206120207120208120209120210120211120212120213120214120215120216120217120218120219120220120221120222120223120224120225120226120227120228120229120230120231120232120233120234120235120236120237120238120239120240120241120242120243120244120245120246120247120248120249120250120251120252120253120254120255120256120257120258120259120260120261120262120263120264120265120266120267120268120269120270120271120272120273120274120275120276120277120278120279120280120281120282120283120284120285120286120287120288120289120290120291120292120293120294120295120296120297120298120299120300120301120302120303120304120305120306120307120308120309120310120311120312120313120314120315120316120317120318120319120320120321120322120323120324120325120326120327120328120329120330120331120332120333120334120335120336120337120338120339120340120341120342120343120344120345120346120347120348120349120350120351120352120353120354120355120356120357120358120359120360120361120362120363120364120365120366120367120368120369120370120371120372120373120374120375120376120377120378120379120380120381120382120383120384120385120386120387120388120389120390120391120392120393120394120395120396120397120398120399120400120401120402120403120404120405120406120407120408120409120410120411120412120413120414120415120416120417120418120419120420120421120422120423120424120425120426120427120428120429120430120431120432120433120434120435120436120437120438120439120440120441120442120443120444120445120446120447120448120449120450120451120452120453120454120455120456120457120458120459120460120461120462120463120464120465120466120467120468120469120470120471120472120473120474120475120476120477120478120479120480120481120482120483120484120485120486120487120488120489120490120491120492120493120494120495120496120497120498120499120500120501120502120503120504120505120506120507120508120509120510120511120512120513120514120515120516120517120518120519120520120521120522120523120524120525120526120527120528120529120530120531120532120533120534120535120536120537120538120539120540120541120542120543120544120545120546120547120548120549120550120551120552120553120554120555120556120557120558120559120560120561120562120563120564120565120566120567120568120569120570120571120572120573120574120575120576120577120578120579120580120581120582120583120584120585120586120587120588120589120590120591120592120593120594120595120596120597120598120599120600120601120602120603120604120605120606120607120608120609120610120611120612120613120614120615120616120617120618120619120620120621120622120623120624120625120626120627120628120629120630120631120632120633120634120635120636120637120638120639120640120641120642120643120644120645120646120647120648120649120650120651120652120653120654120655120656120657120658120659120660120661120662120663120664120665120666120667120668120669120670120671120672120673120674120675120676120677120678120679120680120681120682120683120684120685120686120687120688120689120690120691120692120693120694120695120696120697120698120699120700120701120702120703120704120705120706120707120708120709120710120711120712120713120714120715120716120717120718120719120720120721120722120723120724120725120726120727120728120729120730120731120732120733120734120735120736120737120738120739120740120741120742120743120744120745120746120747120748120749120750120751120752120753120754120755120756120757120758120759120760120761120762120763120764120765120766120767120768120769120770120771120772120773120774120775120776120777120778120779120780120781
  1. (function universalModuleDefinition(root, factory) {
  2. var amdDependencies = [];
  3. var CANNON = root.CANNON || this.CANNON;
  4. var OIMO = root.OIMO || this.OIMO;
  5. var earcut = root.earcut || this.earcut;
  6. if(typeof exports === 'object' && typeof module === 'object') {
  7. try { CANNON = CANNON || require("cannon"); } catch(e) {}
  8. try { OIMO = OIMO || require("oimo"); } catch(e) {}
  9. try { earcut = earcut || require("earcut"); } catch(e) {}
  10. module.exports = factory(CANNON,OIMO,earcut);
  11. } else if(typeof define === 'function' && define.amd) {
  12. if(require.specified && require.specified("cannon")) amdDependencies.push("cannon");
  13. if(require.specified && require.specified("oimo")) amdDependencies.push("oimo");
  14. if(require.specified && require.specified("earcut")) amdDependencies.push("earcut");
  15. define("babylonjs", amdDependencies, factory);
  16. } else if(typeof exports === 'object') {
  17. try { CANNON = CANNON || require("cannon"); } catch(e) {}
  18. try { OIMO = OIMO || require("oimo"); } catch(e) {}
  19. try { earcut = earcut || require("earcut"); } catch(e) {}
  20. exports["babylonjs"] = factory(CANNON,OIMO,earcut);
  21. } else {
  22. root["BABYLON"] = factory(CANNON,OIMO,earcut);
  23. }
  24. })(this, function(CANNON,OIMO,earcut) {
  25. CANNON = CANNON || this.CANNON;
  26. OIMO = OIMO || this.OIMO;
  27. earcut = earcut || this.earcut;
  28. var __decorate=this&&this.__decorate||function(e,t,r,c){var o,f=arguments.length,n=f<3?t:null===c?c=Object.getOwnPropertyDescriptor(t,r):c;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(e,t,r,c);else for(var l=e.length-1;l>=0;l--)(o=e[l])&&(n=(f<3?o(n):f>3?o(t,r,n):o(t,r))||n);return f>3&&n&&Object.defineProperty(t,r,n),n};
  29. var __extends=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,o){t.__proto__=o}||function(t,o){for(var n in o)o.hasOwnProperty(n)&&(t[n]=o[n])};return function(o,n){function r(){this.constructor=o}t(o,n),o.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();
  30. var BABYLON;
  31. (function (BABYLON) {
  32. /**
  33. * EffectFallbacks can be used to add fallbacks (properties to disable) to certain properties when desired to improve performance.
  34. * (Eg. Start at high quality with reflection and fog, if fps is low, remove reflection, if still low remove fog)
  35. */
  36. var EffectFallbacks = /** @class */ (function () {
  37. function EffectFallbacks() {
  38. this._defines = {};
  39. this._currentRank = 32;
  40. this._maxRank = -1;
  41. }
  42. /**
  43. * Removes the fallback from the bound mesh.
  44. */
  45. EffectFallbacks.prototype.unBindMesh = function () {
  46. this._mesh = null;
  47. };
  48. /**
  49. * Adds a fallback on the specified property.
  50. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  51. * @param define The name of the define in the shader
  52. */
  53. EffectFallbacks.prototype.addFallback = function (rank, define) {
  54. if (!this._defines[rank]) {
  55. if (rank < this._currentRank) {
  56. this._currentRank = rank;
  57. }
  58. if (rank > this._maxRank) {
  59. this._maxRank = rank;
  60. }
  61. this._defines[rank] = new Array();
  62. }
  63. this._defines[rank].push(define);
  64. };
  65. /**
  66. * Sets the mesh to use CPU skinning when needing to fallback.
  67. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  68. * @param mesh The mesh to use the fallbacks.
  69. */
  70. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  71. this._mesh = mesh;
  72. if (rank < this._currentRank) {
  73. this._currentRank = rank;
  74. }
  75. if (rank > this._maxRank) {
  76. this._maxRank = rank;
  77. }
  78. };
  79. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  80. /**
  81. * Checks to see if more fallbacks are still availible.
  82. */
  83. get: function () {
  84. return this._currentRank <= this._maxRank;
  85. },
  86. enumerable: true,
  87. configurable: true
  88. });
  89. /**
  90. * Removes the defines that shoould be removed when falling back.
  91. * @param currentDefines defines the current define statements for the shader.
  92. * @param effect defines the current effect we try to compile
  93. * @returns The resulting defines with defines of the current rank removed.
  94. */
  95. EffectFallbacks.prototype.reduce = function (currentDefines, effect) {
  96. // First we try to switch to CPU skinning
  97. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0 && this._mesh.material) {
  98. this._mesh.computeBonesUsingShaders = false;
  99. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  100. effect._bonesComputationForcedToCPU = true;
  101. var scene = this._mesh.getScene();
  102. for (var index = 0; index < scene.meshes.length; index++) {
  103. var otherMesh = scene.meshes[index];
  104. if (!otherMesh.material) {
  105. continue;
  106. }
  107. if (!otherMesh.computeBonesUsingShaders || otherMesh.numBoneInfluencers === 0) {
  108. continue;
  109. }
  110. if (otherMesh.material.getEffect() === effect) {
  111. otherMesh.computeBonesUsingShaders = false;
  112. }
  113. else if (otherMesh.subMeshes) {
  114. for (var _i = 0, _a = otherMesh.subMeshes; _i < _a.length; _i++) {
  115. var subMesh = _a[_i];
  116. var subMeshEffect = subMesh.effect;
  117. if (subMeshEffect === effect) {
  118. otherMesh.computeBonesUsingShaders = false;
  119. break;
  120. }
  121. }
  122. }
  123. }
  124. }
  125. else {
  126. var currentFallbacks = this._defines[this._currentRank];
  127. if (currentFallbacks) {
  128. for (var index = 0; index < currentFallbacks.length; index++) {
  129. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  130. }
  131. }
  132. this._currentRank++;
  133. }
  134. return currentDefines;
  135. };
  136. return EffectFallbacks;
  137. }());
  138. BABYLON.EffectFallbacks = EffectFallbacks;
  139. /**
  140. * Options to be used when creating an effect.
  141. */
  142. var EffectCreationOptions = /** @class */ (function () {
  143. function EffectCreationOptions() {
  144. }
  145. return EffectCreationOptions;
  146. }());
  147. BABYLON.EffectCreationOptions = EffectCreationOptions;
  148. /**
  149. * Effect containing vertex and fragment shader that can be executed on an object.
  150. */
  151. var Effect = /** @class */ (function () {
  152. /**
  153. * Instantiates an effect.
  154. * An effect can be used to create/manage/execute vertex and fragment shaders.
  155. * @param baseName Name of the effect.
  156. * @param attributesNamesOrOptions List of attribute names that will be passed to the shader or set of all options to create the effect.
  157. * @param uniformsNamesOrEngine List of uniform variable names that will be passed to the shader or the engine that will be used to render effect.
  158. * @param samplers List of sampler variables that will be passed to the shader.
  159. * @param engine Engine to be used to render the effect
  160. * @param defines Define statements to be added to the shader.
  161. * @param fallbacks Possible fallbacks for this effect to improve performance when needed.
  162. * @param onCompiled Callback that will be called when the shader is compiled.
  163. * @param onError Callback that will be called if an error occurs during shader compilation.
  164. * @param indexParameters Parameters to be used with Babylons include syntax to iterate over an array (eg. {lights: 10})
  165. */
  166. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  167. if (samplers === void 0) { samplers = null; }
  168. if (defines === void 0) { defines = null; }
  169. if (fallbacks === void 0) { fallbacks = null; }
  170. if (onCompiled === void 0) { onCompiled = null; }
  171. if (onError === void 0) { onError = null; }
  172. var _this = this;
  173. /**
  174. * Unique ID of the effect.
  175. */
  176. this.uniqueId = 0;
  177. /**
  178. * Observable that will be called when the shader is compiled.
  179. * It is recommended to use executeWhenCompile() or to make sure that scene.isReady() is called to get this observable raised.
  180. */
  181. this.onCompileObservable = new BABYLON.Observable();
  182. /**
  183. * Observable that will be called if an error occurs during shader compilation.
  184. */
  185. this.onErrorObservable = new BABYLON.Observable();
  186. /** @hidden */
  187. this._bonesComputationForcedToCPU = false;
  188. this._uniformBuffersNames = {};
  189. this._isReady = false;
  190. this._compilationError = "";
  191. this.name = baseName;
  192. if (attributesNamesOrOptions.attributes) {
  193. var options = attributesNamesOrOptions;
  194. this._engine = uniformsNamesOrEngine;
  195. this._attributesNames = options.attributes;
  196. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  197. this._samplers = options.samplers.slice();
  198. this.defines = options.defines;
  199. this.onError = options.onError;
  200. this.onCompiled = options.onCompiled;
  201. this._fallbacks = options.fallbacks;
  202. this._indexParameters = options.indexParameters;
  203. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  204. if (options.uniformBuffersNames) {
  205. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  206. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  207. }
  208. }
  209. }
  210. else {
  211. this._engine = engine;
  212. this.defines = defines;
  213. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  214. this._samplers = samplers ? samplers.slice() : [];
  215. this._attributesNames = attributesNamesOrOptions;
  216. this.onError = onError;
  217. this.onCompiled = onCompiled;
  218. this._indexParameters = indexParameters;
  219. this._fallbacks = fallbacks;
  220. }
  221. this.uniqueId = Effect._uniqueIdSeed++;
  222. var vertexSource;
  223. var fragmentSource;
  224. if (baseName.vertexElement) {
  225. vertexSource = document.getElementById(baseName.vertexElement);
  226. if (!vertexSource) {
  227. vertexSource = baseName.vertexElement;
  228. }
  229. }
  230. else {
  231. vertexSource = baseName.vertex || baseName;
  232. }
  233. if (baseName.fragmentElement) {
  234. fragmentSource = document.getElementById(baseName.fragmentElement);
  235. if (!fragmentSource) {
  236. fragmentSource = baseName.fragmentElement;
  237. }
  238. }
  239. else {
  240. fragmentSource = baseName.fragment || baseName;
  241. }
  242. this._loadVertexShader(vertexSource, function (vertexCode) {
  243. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  244. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  245. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  246. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  247. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  248. if (baseName) {
  249. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  250. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  251. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  252. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  253. }
  254. else {
  255. _this._vertexSourceCode = migratedVertexCode;
  256. _this._fragmentSourceCode = migratedFragmentCode;
  257. }
  258. _this._prepareEffect();
  259. });
  260. });
  261. });
  262. });
  263. });
  264. });
  265. }
  266. Object.defineProperty(Effect.prototype, "onBindObservable", {
  267. /**
  268. * Observable that will be called when effect is bound.
  269. */
  270. get: function () {
  271. if (!this._onBindObservable) {
  272. this._onBindObservable = new BABYLON.Observable();
  273. }
  274. return this._onBindObservable;
  275. },
  276. enumerable: true,
  277. configurable: true
  278. });
  279. Object.defineProperty(Effect.prototype, "key", {
  280. /**
  281. * Unique key for this effect
  282. */
  283. get: function () {
  284. return this._key;
  285. },
  286. enumerable: true,
  287. configurable: true
  288. });
  289. /**
  290. * If the effect has been compiled and prepared.
  291. * @returns if the effect is compiled and prepared.
  292. */
  293. Effect.prototype.isReady = function () {
  294. if (!this._isReady && this._program && this._program.isParallelCompiled) {
  295. return this._engine._isProgramCompiled(this._program);
  296. }
  297. return this._isReady;
  298. };
  299. /**
  300. * The engine the effect was initialized with.
  301. * @returns the engine.
  302. */
  303. Effect.prototype.getEngine = function () {
  304. return this._engine;
  305. };
  306. /**
  307. * The compiled webGL program for the effect
  308. * @returns the webGL program.
  309. */
  310. Effect.prototype.getProgram = function () {
  311. return this._program;
  312. };
  313. /**
  314. * The set of names of attribute variables for the shader.
  315. * @returns An array of attribute names.
  316. */
  317. Effect.prototype.getAttributesNames = function () {
  318. return this._attributesNames;
  319. };
  320. /**
  321. * Returns the attribute at the given index.
  322. * @param index The index of the attribute.
  323. * @returns The location of the attribute.
  324. */
  325. Effect.prototype.getAttributeLocation = function (index) {
  326. return this._attributes[index];
  327. };
  328. /**
  329. * Returns the attribute based on the name of the variable.
  330. * @param name of the attribute to look up.
  331. * @returns the attribute location.
  332. */
  333. Effect.prototype.getAttributeLocationByName = function (name) {
  334. var index = this._attributesNames.indexOf(name);
  335. return this._attributes[index];
  336. };
  337. /**
  338. * The number of attributes.
  339. * @returns the numnber of attributes.
  340. */
  341. Effect.prototype.getAttributesCount = function () {
  342. return this._attributes.length;
  343. };
  344. /**
  345. * Gets the index of a uniform variable.
  346. * @param uniformName of the uniform to look up.
  347. * @returns the index.
  348. */
  349. Effect.prototype.getUniformIndex = function (uniformName) {
  350. return this._uniformsNames.indexOf(uniformName);
  351. };
  352. /**
  353. * Returns the attribute based on the name of the variable.
  354. * @param uniformName of the uniform to look up.
  355. * @returns the location of the uniform.
  356. */
  357. Effect.prototype.getUniform = function (uniformName) {
  358. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  359. };
  360. /**
  361. * Returns an array of sampler variable names
  362. * @returns The array of sampler variable neames.
  363. */
  364. Effect.prototype.getSamplers = function () {
  365. return this._samplers;
  366. };
  367. /**
  368. * The error from the last compilation.
  369. * @returns the error string.
  370. */
  371. Effect.prototype.getCompilationError = function () {
  372. return this._compilationError;
  373. };
  374. /**
  375. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  376. * @param func The callback to be used.
  377. */
  378. Effect.prototype.executeWhenCompiled = function (func) {
  379. var _this = this;
  380. if (this.isReady()) {
  381. func(this);
  382. return;
  383. }
  384. this.onCompileObservable.add(function (effect) {
  385. func(effect);
  386. });
  387. if (!this._program || this._program.isParallelCompiled) {
  388. setTimeout(function () {
  389. _this._checkIsReady();
  390. }, 16);
  391. }
  392. };
  393. Effect.prototype._checkIsReady = function () {
  394. var _this = this;
  395. if (this.isReady()) {
  396. return;
  397. }
  398. setTimeout(function () {
  399. _this._checkIsReady();
  400. }, 16);
  401. };
  402. /** @hidden */
  403. Effect.prototype._loadVertexShader = function (vertex, callback) {
  404. if (BABYLON.Tools.IsWindowObjectExist()) {
  405. // DOM element ?
  406. if (vertex instanceof HTMLElement) {
  407. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  408. callback(vertexCode);
  409. return;
  410. }
  411. }
  412. // Base64 encoded ?
  413. if (vertex.substr(0, 7) === "base64:") {
  414. var vertexBinary = window.atob(vertex.substr(7));
  415. callback(vertexBinary);
  416. return;
  417. }
  418. // Is in local store ?
  419. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  420. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  421. return;
  422. }
  423. var vertexShaderUrl;
  424. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  425. vertexShaderUrl = vertex;
  426. }
  427. else {
  428. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  429. }
  430. // Vertex shader
  431. this._engine._loadFile(vertexShaderUrl + ".vertex.fx", callback);
  432. };
  433. /** @hidden */
  434. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  435. if (BABYLON.Tools.IsWindowObjectExist()) {
  436. // DOM element ?
  437. if (fragment instanceof HTMLElement) {
  438. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  439. callback(fragmentCode);
  440. return;
  441. }
  442. }
  443. // Base64 encoded ?
  444. if (fragment.substr(0, 7) === "base64:") {
  445. var fragmentBinary = window.atob(fragment.substr(7));
  446. callback(fragmentBinary);
  447. return;
  448. }
  449. // Is in local store ?
  450. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  451. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  452. return;
  453. }
  454. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  455. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  456. return;
  457. }
  458. var fragmentShaderUrl;
  459. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  460. fragmentShaderUrl = fragment;
  461. }
  462. else {
  463. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  464. }
  465. // Fragment shader
  466. this._engine._loadFile(fragmentShaderUrl + ".fragment.fx", callback);
  467. };
  468. /** @hidden */
  469. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  470. // Rebuild shaders source code
  471. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  472. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  473. vertexCode = prefix + vertexCode;
  474. fragmentCode = prefix + fragmentCode;
  475. // Number lines of shaders source code
  476. var i = 2;
  477. var regex = /\n/gm;
  478. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  479. i = 2;
  480. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  481. // Dump shaders name and formatted source code
  482. if (this.name.vertexElement) {
  483. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  484. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  485. }
  486. else if (this.name.vertex) {
  487. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  488. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  489. }
  490. else {
  491. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  492. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  493. }
  494. };
  495. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  496. var preparedSourceCode = this._processPrecision(sourceCode);
  497. if (this._engine.webGLVersion == 1) {
  498. callback(preparedSourceCode);
  499. return;
  500. }
  501. // Already converted
  502. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  503. callback(preparedSourceCode.replace("#version 300 es", ""));
  504. return;
  505. }
  506. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  507. // Remove extensions
  508. // #extension GL_OES_standard_derivatives : enable
  509. // #extension GL_EXT_shader_texture_lod : enable
  510. // #extension GL_EXT_frag_depth : enable
  511. // #extension GL_EXT_draw_buffers : require
  512. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  513. var result = preparedSourceCode.replace(regex, "");
  514. // Migrate to GLSL v300
  515. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  516. result = result.replace(/attribute[ \t]/g, "in ");
  517. result = result.replace(/[ \t]attribute/g, " in");
  518. result = result.replace(/texture2D\s*\(/g, "texture(");
  519. if (isFragment) {
  520. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  521. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  522. result = result.replace(/textureCube\s*\(/g, "texture(");
  523. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  524. result = result.replace(/gl_FragColor/g, "glFragColor");
  525. result = result.replace(/gl_FragData/g, "glFragData");
  526. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  527. }
  528. callback(result);
  529. };
  530. Effect.prototype._processIncludes = function (sourceCode, callback) {
  531. var _this = this;
  532. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  533. var match = regex.exec(sourceCode);
  534. var returnValue = new String(sourceCode);
  535. while (match != null) {
  536. var includeFile = match[1];
  537. // Uniform declaration
  538. if (includeFile.indexOf("__decl__") !== -1) {
  539. includeFile = includeFile.replace(/__decl__/, "");
  540. if (this._engine.supportsUniformBuffers) {
  541. includeFile = includeFile.replace(/Vertex/, "Ubo");
  542. includeFile = includeFile.replace(/Fragment/, "Ubo");
  543. }
  544. includeFile = includeFile + "Declaration";
  545. }
  546. if (Effect.IncludesShadersStore[includeFile]) {
  547. // Substitution
  548. var includeContent = Effect.IncludesShadersStore[includeFile];
  549. if (match[2]) {
  550. var splits = match[3].split(",");
  551. for (var index = 0; index < splits.length; index += 2) {
  552. var source = new RegExp(splits[index], "g");
  553. var dest = splits[index + 1];
  554. includeContent = includeContent.replace(source, dest);
  555. }
  556. }
  557. if (match[4]) {
  558. var indexString = match[5];
  559. if (indexString.indexOf("..") !== -1) {
  560. var indexSplits = indexString.split("..");
  561. var minIndex = parseInt(indexSplits[0]);
  562. var maxIndex = parseInt(indexSplits[1]);
  563. var sourceIncludeContent = includeContent.slice(0);
  564. includeContent = "";
  565. if (isNaN(maxIndex)) {
  566. maxIndex = this._indexParameters[indexSplits[1]];
  567. }
  568. for (var i = minIndex; i < maxIndex; i++) {
  569. if (!this._engine.supportsUniformBuffers) {
  570. // Ubo replacement
  571. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  572. return p1 + "{X}";
  573. });
  574. }
  575. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  576. }
  577. }
  578. else {
  579. if (!this._engine.supportsUniformBuffers) {
  580. // Ubo replacement
  581. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  582. return p1 + "{X}";
  583. });
  584. }
  585. includeContent = includeContent.replace(/\{X\}/g, indexString);
  586. }
  587. }
  588. // Replace
  589. returnValue = returnValue.replace(match[0], includeContent);
  590. }
  591. else {
  592. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  593. this._engine._loadFile(includeShaderUrl, function (fileContent) {
  594. Effect.IncludesShadersStore[includeFile] = fileContent;
  595. _this._processIncludes(returnValue, callback);
  596. });
  597. return;
  598. }
  599. match = regex.exec(sourceCode);
  600. }
  601. callback(returnValue);
  602. };
  603. Effect.prototype._processPrecision = function (source) {
  604. if (source.indexOf("precision highp float") === -1) {
  605. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  606. source = "precision mediump float;\n" + source;
  607. }
  608. else {
  609. source = "precision highp float;\n" + source;
  610. }
  611. }
  612. else {
  613. if (!this._engine.getCaps().highPrecisionShaderSupported) { // Moving highp to mediump
  614. source = source.replace("precision highp float", "precision mediump float");
  615. }
  616. }
  617. return source;
  618. };
  619. /**
  620. * Recompiles the webGL program
  621. * @param vertexSourceCode The source code for the vertex shader.
  622. * @param fragmentSourceCode The source code for the fragment shader.
  623. * @param onCompiled Callback called when completed.
  624. * @param onError Callback called on error.
  625. * @hidden
  626. */
  627. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  628. var _this = this;
  629. this._isReady = false;
  630. this._vertexSourceCodeOverride = vertexSourceCode;
  631. this._fragmentSourceCodeOverride = fragmentSourceCode;
  632. this.onError = function (effect, error) {
  633. if (onError) {
  634. onError(error);
  635. }
  636. };
  637. this.onCompiled = function () {
  638. var scenes = _this.getEngine().scenes;
  639. for (var i = 0; i < scenes.length; i++) {
  640. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  641. }
  642. if (onCompiled) {
  643. onCompiled(_this._program);
  644. }
  645. };
  646. this._fallbacks = null;
  647. this._prepareEffect();
  648. };
  649. /**
  650. * Gets the uniform locations of the the specified variable names
  651. * @param names THe names of the variables to lookup.
  652. * @returns Array of locations in the same order as variable names.
  653. */
  654. Effect.prototype.getSpecificUniformLocations = function (names) {
  655. var engine = this._engine;
  656. return engine.getUniforms(this._program, names);
  657. };
  658. /**
  659. * Prepares the effect
  660. * @hidden
  661. */
  662. Effect.prototype._prepareEffect = function () {
  663. var _this = this;
  664. var attributesNames = this._attributesNames;
  665. var defines = this.defines;
  666. var fallbacks = this._fallbacks;
  667. this._valueCache = {};
  668. var previousProgram = this._program;
  669. try {
  670. var engine_1 = this._engine;
  671. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  672. this._program = engine_1.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  673. }
  674. else {
  675. this._program = engine_1.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  676. }
  677. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  678. engine_1._executeWhenProgramIsCompiled(this._program, function () {
  679. if (engine_1.supportsUniformBuffers) {
  680. for (var name in _this._uniformBuffersNames) {
  681. _this.bindUniformBlock(name, _this._uniformBuffersNames[name]);
  682. }
  683. }
  684. _this._uniforms = engine_1.getUniforms(_this._program, _this._uniformsNames);
  685. _this._attributes = engine_1.getAttributes(_this._program, attributesNames);
  686. var index;
  687. for (index = 0; index < _this._samplers.length; index++) {
  688. var sampler = _this.getUniform(_this._samplers[index]);
  689. if (sampler == null) {
  690. _this._samplers.splice(index, 1);
  691. index--;
  692. }
  693. }
  694. engine_1.bindSamplers(_this);
  695. _this._compilationError = "";
  696. _this._isReady = true;
  697. if (_this.onCompiled) {
  698. _this.onCompiled(_this);
  699. }
  700. _this.onCompileObservable.notifyObservers(_this);
  701. _this.onCompileObservable.clear();
  702. // Unbind mesh reference in fallbacks
  703. if (_this._fallbacks) {
  704. _this._fallbacks.unBindMesh();
  705. }
  706. if (previousProgram) {
  707. _this.getEngine()._deleteProgram(previousProgram);
  708. }
  709. });
  710. if (this._program.isParallelCompiled) {
  711. this._checkIsReady();
  712. }
  713. }
  714. catch (e) {
  715. this._compilationError = e.message;
  716. // Let's go through fallbacks then
  717. BABYLON.Tools.Error("Unable to compile effect:");
  718. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  719. return " " + uniform;
  720. }));
  721. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  722. return " " + attribute;
  723. }));
  724. BABYLON.Tools.Error("Error: " + this._compilationError);
  725. if (previousProgram) {
  726. this._program = previousProgram;
  727. this._isReady = true;
  728. if (this.onError) {
  729. this.onError(this, this._compilationError);
  730. }
  731. this.onErrorObservable.notifyObservers(this);
  732. }
  733. if (fallbacks && fallbacks.isMoreFallbacks) {
  734. BABYLON.Tools.Error("Trying next fallback.");
  735. this.defines = fallbacks.reduce(this.defines, this);
  736. this._prepareEffect();
  737. }
  738. else { // Sorry we did everything we can
  739. if (this.onError) {
  740. this.onError(this, this._compilationError);
  741. }
  742. this.onErrorObservable.notifyObservers(this);
  743. this.onErrorObservable.clear();
  744. // Unbind mesh reference in fallbacks
  745. if (this._fallbacks) {
  746. this._fallbacks.unBindMesh();
  747. }
  748. }
  749. }
  750. };
  751. Object.defineProperty(Effect.prototype, "isSupported", {
  752. /**
  753. * Checks if the effect is supported. (Must be called after compilation)
  754. */
  755. get: function () {
  756. return this._compilationError === "";
  757. },
  758. enumerable: true,
  759. configurable: true
  760. });
  761. /**
  762. * Binds a texture to the engine to be used as output of the shader.
  763. * @param channel Name of the output variable.
  764. * @param texture Texture to bind.
  765. * @hidden
  766. */
  767. Effect.prototype._bindTexture = function (channel, texture) {
  768. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  769. };
  770. /**
  771. * Sets a texture on the engine to be used in the shader.
  772. * @param channel Name of the sampler variable.
  773. * @param texture Texture to set.
  774. */
  775. Effect.prototype.setTexture = function (channel, texture) {
  776. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  777. };
  778. /**
  779. * Sets a depth stencil texture from a render target on the engine to be used in the shader.
  780. * @param channel Name of the sampler variable.
  781. * @param texture Texture to set.
  782. */
  783. Effect.prototype.setDepthStencilTexture = function (channel, texture) {
  784. this._engine.setDepthStencilTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  785. };
  786. /**
  787. * Sets an array of textures on the engine to be used in the shader.
  788. * @param channel Name of the variable.
  789. * @param textures Textures to set.
  790. */
  791. Effect.prototype.setTextureArray = function (channel, textures) {
  792. if (this._samplers.indexOf(channel + "Ex") === -1) {
  793. var initialPos = this._samplers.indexOf(channel);
  794. for (var index = 1; index < textures.length; index++) {
  795. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  796. }
  797. }
  798. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  799. };
  800. /**
  801. * Sets a texture to be the input of the specified post process. (To use the output, pass in the next post process in the pipeline)
  802. * @param channel Name of the sampler variable.
  803. * @param postProcess Post process to get the input texture from.
  804. */
  805. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  806. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  807. };
  808. /**
  809. * (Warning! setTextureFromPostProcessOutput may be desired instead)
  810. * Sets the input texture of the passed in post process to be input of this effect. (To use the output of the passed in post process use setTextureFromPostProcessOutput)
  811. * @param channel Name of the sampler variable.
  812. * @param postProcess Post process to get the output texture from.
  813. */
  814. Effect.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  815. this._engine.setTextureFromPostProcessOutput(this._samplers.indexOf(channel), postProcess);
  816. };
  817. /** @hidden */
  818. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  819. var cache = this._valueCache[uniformName];
  820. var flag = matrix.updateFlag;
  821. if (cache !== undefined && cache === flag) {
  822. return false;
  823. }
  824. this._valueCache[uniformName] = flag;
  825. return true;
  826. };
  827. /** @hidden */
  828. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  829. var cache = this._valueCache[uniformName];
  830. if (!cache) {
  831. cache = [x, y];
  832. this._valueCache[uniformName] = cache;
  833. return true;
  834. }
  835. var changed = false;
  836. if (cache[0] !== x) {
  837. cache[0] = x;
  838. changed = true;
  839. }
  840. if (cache[1] !== y) {
  841. cache[1] = y;
  842. changed = true;
  843. }
  844. return changed;
  845. };
  846. /** @hidden */
  847. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  848. var cache = this._valueCache[uniformName];
  849. if (!cache) {
  850. cache = [x, y, z];
  851. this._valueCache[uniformName] = cache;
  852. return true;
  853. }
  854. var changed = false;
  855. if (cache[0] !== x) {
  856. cache[0] = x;
  857. changed = true;
  858. }
  859. if (cache[1] !== y) {
  860. cache[1] = y;
  861. changed = true;
  862. }
  863. if (cache[2] !== z) {
  864. cache[2] = z;
  865. changed = true;
  866. }
  867. return changed;
  868. };
  869. /** @hidden */
  870. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  871. var cache = this._valueCache[uniformName];
  872. if (!cache) {
  873. cache = [x, y, z, w];
  874. this._valueCache[uniformName] = cache;
  875. return true;
  876. }
  877. var changed = false;
  878. if (cache[0] !== x) {
  879. cache[0] = x;
  880. changed = true;
  881. }
  882. if (cache[1] !== y) {
  883. cache[1] = y;
  884. changed = true;
  885. }
  886. if (cache[2] !== z) {
  887. cache[2] = z;
  888. changed = true;
  889. }
  890. if (cache[3] !== w) {
  891. cache[3] = w;
  892. changed = true;
  893. }
  894. return changed;
  895. };
  896. /**
  897. * Binds a buffer to a uniform.
  898. * @param buffer Buffer to bind.
  899. * @param name Name of the uniform variable to bind to.
  900. */
  901. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  902. var bufferName = this._uniformBuffersNames[name];
  903. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  904. return;
  905. }
  906. Effect._baseCache[bufferName] = buffer;
  907. this._engine.bindUniformBufferBase(buffer, bufferName);
  908. };
  909. /**
  910. * Binds block to a uniform.
  911. * @param blockName Name of the block to bind.
  912. * @param index Index to bind.
  913. */
  914. Effect.prototype.bindUniformBlock = function (blockName, index) {
  915. this._engine.bindUniformBlock(this._program, blockName, index);
  916. };
  917. /**
  918. * Sets an interger value on a uniform variable.
  919. * @param uniformName Name of the variable.
  920. * @param value Value to be set.
  921. * @returns this effect.
  922. */
  923. Effect.prototype.setInt = function (uniformName, value) {
  924. var cache = this._valueCache[uniformName];
  925. if (cache !== undefined && cache === value) {
  926. return this;
  927. }
  928. this._valueCache[uniformName] = value;
  929. this._engine.setInt(this.getUniform(uniformName), value);
  930. return this;
  931. };
  932. /**
  933. * Sets an int array on a uniform variable.
  934. * @param uniformName Name of the variable.
  935. * @param array array to be set.
  936. * @returns this effect.
  937. */
  938. Effect.prototype.setIntArray = function (uniformName, array) {
  939. this._valueCache[uniformName] = null;
  940. this._engine.setIntArray(this.getUniform(uniformName), array);
  941. return this;
  942. };
  943. /**
  944. * Sets an int array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  945. * @param uniformName Name of the variable.
  946. * @param array array to be set.
  947. * @returns this effect.
  948. */
  949. Effect.prototype.setIntArray2 = function (uniformName, array) {
  950. this._valueCache[uniformName] = null;
  951. this._engine.setIntArray2(this.getUniform(uniformName), array);
  952. return this;
  953. };
  954. /**
  955. * Sets an int array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  956. * @param uniformName Name of the variable.
  957. * @param array array to be set.
  958. * @returns this effect.
  959. */
  960. Effect.prototype.setIntArray3 = function (uniformName, array) {
  961. this._valueCache[uniformName] = null;
  962. this._engine.setIntArray3(this.getUniform(uniformName), array);
  963. return this;
  964. };
  965. /**
  966. * Sets an int array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  967. * @param uniformName Name of the variable.
  968. * @param array array to be set.
  969. * @returns this effect.
  970. */
  971. Effect.prototype.setIntArray4 = function (uniformName, array) {
  972. this._valueCache[uniformName] = null;
  973. this._engine.setIntArray4(this.getUniform(uniformName), array);
  974. return this;
  975. };
  976. /**
  977. * Sets an float array on a uniform variable.
  978. * @param uniformName Name of the variable.
  979. * @param array array to be set.
  980. * @returns this effect.
  981. */
  982. Effect.prototype.setFloatArray = function (uniformName, array) {
  983. this._valueCache[uniformName] = null;
  984. this._engine.setFloatArray(this.getUniform(uniformName), array);
  985. return this;
  986. };
  987. /**
  988. * Sets an float array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  989. * @param uniformName Name of the variable.
  990. * @param array array to be set.
  991. * @returns this effect.
  992. */
  993. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  994. this._valueCache[uniformName] = null;
  995. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  996. return this;
  997. };
  998. /**
  999. * Sets an float array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  1000. * @param uniformName Name of the variable.
  1001. * @param array array to be set.
  1002. * @returns this effect.
  1003. */
  1004. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  1005. this._valueCache[uniformName] = null;
  1006. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  1007. return this;
  1008. };
  1009. /**
  1010. * Sets an float array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  1011. * @param uniformName Name of the variable.
  1012. * @param array array to be set.
  1013. * @returns this effect.
  1014. */
  1015. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  1016. this._valueCache[uniformName] = null;
  1017. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  1018. return this;
  1019. };
  1020. /**
  1021. * Sets an array on a uniform variable.
  1022. * @param uniformName Name of the variable.
  1023. * @param array array to be set.
  1024. * @returns this effect.
  1025. */
  1026. Effect.prototype.setArray = function (uniformName, array) {
  1027. this._valueCache[uniformName] = null;
  1028. this._engine.setArray(this.getUniform(uniformName), array);
  1029. return this;
  1030. };
  1031. /**
  1032. * Sets an array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  1033. * @param uniformName Name of the variable.
  1034. * @param array array to be set.
  1035. * @returns this effect.
  1036. */
  1037. Effect.prototype.setArray2 = function (uniformName, array) {
  1038. this._valueCache[uniformName] = null;
  1039. this._engine.setArray2(this.getUniform(uniformName), array);
  1040. return this;
  1041. };
  1042. /**
  1043. * Sets an array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  1044. * @param uniformName Name of the variable.
  1045. * @param array array to be set.
  1046. * @returns this effect.
  1047. */
  1048. Effect.prototype.setArray3 = function (uniformName, array) {
  1049. this._valueCache[uniformName] = null;
  1050. this._engine.setArray3(this.getUniform(uniformName), array);
  1051. return this;
  1052. };
  1053. /**
  1054. * Sets an array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  1055. * @param uniformName Name of the variable.
  1056. * @param array array to be set.
  1057. * @returns this effect.
  1058. */
  1059. Effect.prototype.setArray4 = function (uniformName, array) {
  1060. this._valueCache[uniformName] = null;
  1061. this._engine.setArray4(this.getUniform(uniformName), array);
  1062. return this;
  1063. };
  1064. /**
  1065. * Sets matrices on a uniform variable.
  1066. * @param uniformName Name of the variable.
  1067. * @param matrices matrices to be set.
  1068. * @returns this effect.
  1069. */
  1070. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1071. if (!matrices) {
  1072. return this;
  1073. }
  1074. this._valueCache[uniformName] = null;
  1075. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1076. return this;
  1077. };
  1078. /**
  1079. * Sets matrix on a uniform variable.
  1080. * @param uniformName Name of the variable.
  1081. * @param matrix matrix to be set.
  1082. * @returns this effect.
  1083. */
  1084. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1085. if (this._cacheMatrix(uniformName, matrix)) {
  1086. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1087. }
  1088. return this;
  1089. };
  1090. /**
  1091. * Sets a 3x3 matrix on a uniform variable. (Speicified as [1,2,3,4,5,6,7,8,9] will result in [1,2,3][4,5,6][7,8,9] matrix)
  1092. * @param uniformName Name of the variable.
  1093. * @param matrix matrix to be set.
  1094. * @returns this effect.
  1095. */
  1096. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1097. this._valueCache[uniformName] = null;
  1098. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1099. return this;
  1100. };
  1101. /**
  1102. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1103. * @param uniformName Name of the variable.
  1104. * @param matrix matrix to be set.
  1105. * @returns this effect.
  1106. */
  1107. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1108. this._valueCache[uniformName] = null;
  1109. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1110. return this;
  1111. };
  1112. /**
  1113. * Sets a float on a uniform variable.
  1114. * @param uniformName Name of the variable.
  1115. * @param value value to be set.
  1116. * @returns this effect.
  1117. */
  1118. Effect.prototype.setFloat = function (uniformName, value) {
  1119. var cache = this._valueCache[uniformName];
  1120. if (cache !== undefined && cache === value) {
  1121. return this;
  1122. }
  1123. this._valueCache[uniformName] = value;
  1124. this._engine.setFloat(this.getUniform(uniformName), value);
  1125. return this;
  1126. };
  1127. /**
  1128. * Sets a boolean on a uniform variable.
  1129. * @param uniformName Name of the variable.
  1130. * @param bool value to be set.
  1131. * @returns this effect.
  1132. */
  1133. Effect.prototype.setBool = function (uniformName, bool) {
  1134. var cache = this._valueCache[uniformName];
  1135. if (cache !== undefined && cache === bool) {
  1136. return this;
  1137. }
  1138. this._valueCache[uniformName] = bool;
  1139. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1140. return this;
  1141. };
  1142. /**
  1143. * Sets a Vector2 on a uniform variable.
  1144. * @param uniformName Name of the variable.
  1145. * @param vector2 vector2 to be set.
  1146. * @returns this effect.
  1147. */
  1148. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1149. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1150. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1151. }
  1152. return this;
  1153. };
  1154. /**
  1155. * Sets a float2 on a uniform variable.
  1156. * @param uniformName Name of the variable.
  1157. * @param x First float in float2.
  1158. * @param y Second float in float2.
  1159. * @returns this effect.
  1160. */
  1161. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1162. if (this._cacheFloat2(uniformName, x, y)) {
  1163. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1164. }
  1165. return this;
  1166. };
  1167. /**
  1168. * Sets a Vector3 on a uniform variable.
  1169. * @param uniformName Name of the variable.
  1170. * @param vector3 Value to be set.
  1171. * @returns this effect.
  1172. */
  1173. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1174. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1175. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1176. }
  1177. return this;
  1178. };
  1179. /**
  1180. * Sets a float3 on a uniform variable.
  1181. * @param uniformName Name of the variable.
  1182. * @param x First float in float3.
  1183. * @param y Second float in float3.
  1184. * @param z Third float in float3.
  1185. * @returns this effect.
  1186. */
  1187. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1188. if (this._cacheFloat3(uniformName, x, y, z)) {
  1189. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1190. }
  1191. return this;
  1192. };
  1193. /**
  1194. * Sets a Vector4 on a uniform variable.
  1195. * @param uniformName Name of the variable.
  1196. * @param vector4 Value to be set.
  1197. * @returns this effect.
  1198. */
  1199. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1200. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1201. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1202. }
  1203. return this;
  1204. };
  1205. /**
  1206. * Sets a float4 on a uniform variable.
  1207. * @param uniformName Name of the variable.
  1208. * @param x First float in float4.
  1209. * @param y Second float in float4.
  1210. * @param z Third float in float4.
  1211. * @param w Fourth float in float4.
  1212. * @returns this effect.
  1213. */
  1214. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1215. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1216. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1217. }
  1218. return this;
  1219. };
  1220. /**
  1221. * Sets a Color3 on a uniform variable.
  1222. * @param uniformName Name of the variable.
  1223. * @param color3 Value to be set.
  1224. * @returns this effect.
  1225. */
  1226. Effect.prototype.setColor3 = function (uniformName, color3) {
  1227. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1228. this._engine.setColor3(this.getUniform(uniformName), color3);
  1229. }
  1230. return this;
  1231. };
  1232. /**
  1233. * Sets a Color4 on a uniform variable.
  1234. * @param uniformName Name of the variable.
  1235. * @param color3 Value to be set.
  1236. * @param alpha Alpha value to be set.
  1237. * @returns this effect.
  1238. */
  1239. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1240. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1241. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1242. }
  1243. return this;
  1244. };
  1245. /**
  1246. * Sets a Color4 on a uniform variable
  1247. * @param uniformName defines the name of the variable
  1248. * @param color4 defines the value to be set
  1249. * @returns this effect.
  1250. */
  1251. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1252. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1253. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1254. }
  1255. return this;
  1256. };
  1257. /**
  1258. * This function will add a new shader to the shader store
  1259. * @param name the name of the shader
  1260. * @param pixelShader optional pixel shader content
  1261. * @param vertexShader optional vertex shader content
  1262. */
  1263. Effect.RegisterShader = function (name, pixelShader, vertexShader) {
  1264. if (pixelShader) {
  1265. Effect.ShadersStore[name + "PixelShader"] = pixelShader;
  1266. }
  1267. if (vertexShader) {
  1268. Effect.ShadersStore[name + "VertexShader"] = vertexShader;
  1269. }
  1270. };
  1271. /**
  1272. * Resets the cache of effects.
  1273. */
  1274. Effect.ResetCache = function () {
  1275. Effect._baseCache = {};
  1276. };
  1277. Effect._uniqueIdSeed = 0;
  1278. Effect._baseCache = {};
  1279. /**
  1280. * Store of each shader (The can be looked up using effect.key)
  1281. */
  1282. Effect.ShadersStore = {};
  1283. /**
  1284. * Store of each included file for a shader (The can be looked up using effect.key)
  1285. */
  1286. Effect.IncludesShadersStore = {};
  1287. return Effect;
  1288. }());
  1289. BABYLON.Effect = Effect;
  1290. })(BABYLON || (BABYLON = {}));
  1291. //# sourceMappingURL=babylon.effect.js.map
  1292. //# sourceMappingURL=babylon.types.js.map
  1293. var BABYLON;
  1294. (function (BABYLON) {
  1295. /**
  1296. * Gather the list of keyboard event types as constants.
  1297. */
  1298. var KeyboardEventTypes = /** @class */ (function () {
  1299. function KeyboardEventTypes() {
  1300. }
  1301. /**
  1302. * The keydown event is fired when a key becomes active (pressed).
  1303. */
  1304. KeyboardEventTypes.KEYDOWN = 0x01;
  1305. /**
  1306. * The keyup event is fired when a key has been released.
  1307. */
  1308. KeyboardEventTypes.KEYUP = 0x02;
  1309. return KeyboardEventTypes;
  1310. }());
  1311. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1312. /**
  1313. * This class is used to store keyboard related info for the onKeyboardObservable event.
  1314. */
  1315. var KeyboardInfo = /** @class */ (function () {
  1316. /**
  1317. * Instantiates a new keyboard info.
  1318. * This class is used to store keyboard related info for the onKeyboardObservable event.
  1319. * @param type Defines the type of event (BABYLON.KeyboardEventTypes)
  1320. * @param event Defines the related dom event
  1321. */
  1322. function KeyboardInfo(
  1323. /**
  1324. * Defines the type of event (BABYLON.KeyboardEventTypes)
  1325. */
  1326. type,
  1327. /**
  1328. * Defines the related dom event
  1329. */
  1330. event) {
  1331. this.type = type;
  1332. this.event = event;
  1333. }
  1334. return KeyboardInfo;
  1335. }());
  1336. BABYLON.KeyboardInfo = KeyboardInfo;
  1337. /**
  1338. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1339. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1340. */
  1341. var KeyboardInfoPre = /** @class */ (function (_super) {
  1342. __extends(KeyboardInfoPre, _super);
  1343. /**
  1344. * Instantiates a new keyboard pre info.
  1345. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1346. * @param type Defines the type of event (BABYLON.KeyboardEventTypes)
  1347. * @param event Defines the related dom event
  1348. */
  1349. function KeyboardInfoPre(
  1350. /**
  1351. * Defines the type of event (BABYLON.KeyboardEventTypes)
  1352. */
  1353. type,
  1354. /**
  1355. * Defines the related dom event
  1356. */
  1357. event) {
  1358. var _this = _super.call(this, type, event) || this;
  1359. _this.type = type;
  1360. _this.event = event;
  1361. _this.skipOnPointerObservable = false;
  1362. return _this;
  1363. }
  1364. return KeyboardInfoPre;
  1365. }(KeyboardInfo));
  1366. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1367. })(BABYLON || (BABYLON = {}));
  1368. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1369. var BABYLON;
  1370. (function (BABYLON) {
  1371. /**
  1372. * Gather the list of pointer event types as constants.
  1373. */
  1374. var PointerEventTypes = /** @class */ (function () {
  1375. function PointerEventTypes() {
  1376. }
  1377. /**
  1378. * The pointerdown event is fired when a pointer becomes active. For mouse, it is fired when the device transitions from no buttons depressed to at least one button depressed. For touch, it is fired when physical contact is made with the digitizer. For pen, it is fired when the stylus makes physical contact with the digitizer.
  1379. */
  1380. PointerEventTypes.POINTERDOWN = 0x01;
  1381. /**
  1382. * The pointerup event is fired when a pointer is no longer active.
  1383. */
  1384. PointerEventTypes.POINTERUP = 0x02;
  1385. /**
  1386. * The pointermove event is fired when a pointer changes coordinates.
  1387. */
  1388. PointerEventTypes.POINTERMOVE = 0x04;
  1389. /**
  1390. * The pointerwheel event is fired when a mouse wheel has been rotated.
  1391. */
  1392. PointerEventTypes.POINTERWHEEL = 0x08;
  1393. /**
  1394. * The pointerpick event is fired when a mesh or sprite has been picked by the pointer.
  1395. */
  1396. PointerEventTypes.POINTERPICK = 0x10;
  1397. /**
  1398. * The pointertap event is fired when a the object has been touched and released without drag.
  1399. */
  1400. PointerEventTypes.POINTERTAP = 0x20;
  1401. /**
  1402. * The pointerdoubletap event is fired when a the object has been touched and released twice without drag.
  1403. */
  1404. PointerEventTypes.POINTERDOUBLETAP = 0x40;
  1405. return PointerEventTypes;
  1406. }());
  1407. BABYLON.PointerEventTypes = PointerEventTypes;
  1408. /**
  1409. * Base class of pointer info types.
  1410. */
  1411. var PointerInfoBase = /** @class */ (function () {
  1412. /**
  1413. * Instantiates the base class of pointers info.
  1414. * @param type Defines the type of event (BABYLON.PointerEventTypes)
  1415. * @param event Defines the related dom event
  1416. */
  1417. function PointerInfoBase(
  1418. /**
  1419. * Defines the type of event (BABYLON.PointerEventTypes)
  1420. */
  1421. type,
  1422. /**
  1423. * Defines the related dom event
  1424. */
  1425. event) {
  1426. this.type = type;
  1427. this.event = event;
  1428. }
  1429. return PointerInfoBase;
  1430. }());
  1431. BABYLON.PointerInfoBase = PointerInfoBase;
  1432. /**
  1433. * This class is used to store pointer related info for the onPrePointerObservable event.
  1434. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1435. */
  1436. var PointerInfoPre = /** @class */ (function (_super) {
  1437. __extends(PointerInfoPre, _super);
  1438. /**
  1439. * Instantiates a PointerInfoPre to store pointer related info to the onPrePointerObservable event.
  1440. * @param type Defines the type of event (BABYLON.PointerEventTypes)
  1441. * @param event Defines the related dom event
  1442. * @param localX Defines the local x coordinates of the pointer when the event occured
  1443. * @param localY Defines the local y coordinates of the pointer when the event occured
  1444. */
  1445. function PointerInfoPre(type, event, localX, localY) {
  1446. var _this = _super.call(this, type, event) || this;
  1447. /**
  1448. * Ray from a pointer if availible (eg. 6dof controller)
  1449. */
  1450. _this.ray = null;
  1451. _this.skipOnPointerObservable = false;
  1452. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1453. return _this;
  1454. }
  1455. return PointerInfoPre;
  1456. }(PointerInfoBase));
  1457. BABYLON.PointerInfoPre = PointerInfoPre;
  1458. /**
  1459. * This type contains all the data related to a pointer event in Babylon.js.
  1460. * The event member is an instance of PointerEvent for all types except PointerWheel and is of type MouseWheelEvent when type equals PointerWheel. The different event types can be found in the PointerEventTypes class.
  1461. */
  1462. var PointerInfo = /** @class */ (function (_super) {
  1463. __extends(PointerInfo, _super);
  1464. /**
  1465. * Instantiates a PointerInfo to store pointer related info to the onPointerObservable event.
  1466. * @param type Defines the type of event (BABYLON.PointerEventTypes)
  1467. * @param event Defines the related dom event
  1468. * @param pickInfo Defines the picking info associated to the info (if any)\
  1469. */
  1470. function PointerInfo(type, event,
  1471. /**
  1472. * Defines the picking info associated to the info (if any)\
  1473. */
  1474. pickInfo) {
  1475. var _this = _super.call(this, type, event) || this;
  1476. _this.pickInfo = pickInfo;
  1477. return _this;
  1478. }
  1479. return PointerInfo;
  1480. }(PointerInfoBase));
  1481. BABYLON.PointerInfo = PointerInfo;
  1482. })(BABYLON || (BABYLON = {}));
  1483. //# sourceMappingURL=babylon.pointerEvents.js.map
  1484. var BABYLON;
  1485. (function (BABYLON) {
  1486. /**
  1487. * Gather the list of clipboard event types as constants.
  1488. */
  1489. var ClipboardEventTypes = /** @class */ (function () {
  1490. function ClipboardEventTypes() {
  1491. }
  1492. /**
  1493. * The clipboard event is fired when a copy command is active (pressed).
  1494. */
  1495. ClipboardEventTypes.COPY = 0x01; //
  1496. /**
  1497. * The clipboard event is fired when a cut command is active (pressed).
  1498. */
  1499. ClipboardEventTypes.CUT = 0x02;
  1500. /**
  1501. * The clipboard event is fired when a paste command is active (pressed).
  1502. */
  1503. ClipboardEventTypes.PASTE = 0x03;
  1504. return ClipboardEventTypes;
  1505. }());
  1506. BABYLON.ClipboardEventTypes = ClipboardEventTypes;
  1507. /**
  1508. * This class is used to store clipboard related info for the onClipboardObservable event.
  1509. */
  1510. var ClipboardInfo = /** @class */ (function () {
  1511. /**
  1512. *Creates an instance of ClipboardInfo.
  1513. * @param {number} type
  1514. * @param {ClipboardEvent} event
  1515. */
  1516. function ClipboardInfo(
  1517. /**
  1518. * Defines the type of event (BABYLON.ClipboardEventTypes)
  1519. */
  1520. type,
  1521. /**
  1522. * Defines the related dom event
  1523. */
  1524. event) {
  1525. this.type = type;
  1526. this.event = event;
  1527. }
  1528. /**
  1529. * Get the clipboard event's type from the keycode.
  1530. * @param keyCode Defines the keyCode for the current keyboard event.
  1531. * @return {number}
  1532. */
  1533. ClipboardInfo.GetTypeFromCharacter = function (keyCode) {
  1534. var charCode = keyCode;
  1535. //TODO: add codes for extended ASCII
  1536. switch (charCode) {
  1537. case 67: return ClipboardEventTypes.COPY;
  1538. case 86: return ClipboardEventTypes.PASTE;
  1539. case 88: return ClipboardEventTypes.CUT;
  1540. default: return -1;
  1541. }
  1542. };
  1543. return ClipboardInfo;
  1544. }());
  1545. BABYLON.ClipboardInfo = ClipboardInfo;
  1546. })(BABYLON || (BABYLON = {}));
  1547. //# sourceMappingURL=babylon.clipboardEvents.js.map
  1548. var BABYLON;
  1549. (function (BABYLON) {
  1550. /** Class used to store color4 gradient */
  1551. var ColorGradient = /** @class */ (function () {
  1552. function ColorGradient() {
  1553. }
  1554. /**
  1555. * Will get a color picked randomly between color1 and color2.
  1556. * If color2 is undefined then color1 will be used
  1557. * @param result defines the target Color4 to store the result in
  1558. */
  1559. ColorGradient.prototype.getColorToRef = function (result) {
  1560. if (!this.color2) {
  1561. result.copyFrom(this.color1);
  1562. return;
  1563. }
  1564. BABYLON.Color4.LerpToRef(this.color1, this.color2, Math.random(), result);
  1565. };
  1566. return ColorGradient;
  1567. }());
  1568. BABYLON.ColorGradient = ColorGradient;
  1569. /** Class used to store color 3 gradient */
  1570. var Color3Gradient = /** @class */ (function () {
  1571. function Color3Gradient() {
  1572. }
  1573. return Color3Gradient;
  1574. }());
  1575. BABYLON.Color3Gradient = Color3Gradient;
  1576. /** Class used to store factor gradient */
  1577. var FactorGradient = /** @class */ (function () {
  1578. function FactorGradient() {
  1579. }
  1580. /**
  1581. * Will get a number picked randomly between factor1 and factor2.
  1582. * If factor2 is undefined then factor1 will be used
  1583. * @returns the picked number
  1584. */
  1585. FactorGradient.prototype.getFactor = function () {
  1586. if (this.factor2 === undefined) {
  1587. return this.factor1;
  1588. }
  1589. return BABYLON.Scalar.Lerp(this.factor1, this.factor2, Math.random());
  1590. };
  1591. return FactorGradient;
  1592. }());
  1593. BABYLON.FactorGradient = FactorGradient;
  1594. /**
  1595. * @ignore
  1596. * Application error to support additional information when loading a file
  1597. */
  1598. var LoadFileError = /** @class */ (function (_super) {
  1599. __extends(LoadFileError, _super);
  1600. /**
  1601. * Creates a new LoadFileError
  1602. * @param message defines the message of the error
  1603. * @param request defines the optional XHR request
  1604. */
  1605. function LoadFileError(message,
  1606. /** defines the optional XHR request */
  1607. request) {
  1608. var _this = _super.call(this, message) || this;
  1609. _this.request = request;
  1610. _this.name = "LoadFileError";
  1611. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  1612. return _this;
  1613. }
  1614. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  1615. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  1616. // Polyfill for Object.setPrototypeOf if necessary.
  1617. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  1618. return LoadFileError;
  1619. }(Error));
  1620. BABYLON.LoadFileError = LoadFileError;
  1621. /**
  1622. * Class used to define a retry strategy when error happens while loading assets
  1623. */
  1624. var RetryStrategy = /** @class */ (function () {
  1625. function RetryStrategy() {
  1626. }
  1627. /**
  1628. * Function used to defines an exponential back off strategy
  1629. * @param maxRetries defines the maximum number of retries (3 by default)
  1630. * @param baseInterval defines the interval between retries
  1631. * @returns the strategy function to use
  1632. */
  1633. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  1634. if (maxRetries === void 0) { maxRetries = 3; }
  1635. if (baseInterval === void 0) { baseInterval = 500; }
  1636. return function (url, request, retryIndex) {
  1637. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  1638. return -1;
  1639. }
  1640. return Math.pow(2, retryIndex) * baseInterval;
  1641. };
  1642. };
  1643. return RetryStrategy;
  1644. }());
  1645. BABYLON.RetryStrategy = RetryStrategy;
  1646. // Screenshots
  1647. var screenshotCanvas;
  1648. var cloneValue = function (source, destinationObject) {
  1649. if (!source) {
  1650. return null;
  1651. }
  1652. if (source instanceof BABYLON.Mesh) {
  1653. return null;
  1654. }
  1655. if (source instanceof BABYLON.SubMesh) {
  1656. return source.clone(destinationObject);
  1657. }
  1658. else if (source.clone) {
  1659. return source.clone();
  1660. }
  1661. return null;
  1662. };
  1663. /**
  1664. * Class containing a set of static utilities functions
  1665. */
  1666. var Tools = /** @class */ (function () {
  1667. function Tools() {
  1668. }
  1669. /**
  1670. * Read the content of a byte array at a specified coordinates (taking in account wrapping)
  1671. * @param u defines the coordinate on X axis
  1672. * @param v defines the coordinate on Y axis
  1673. * @param width defines the width of the source data
  1674. * @param height defines the height of the source data
  1675. * @param pixels defines the source byte array
  1676. * @param color defines the output color
  1677. */
  1678. Tools.FetchToRef = function (u, v, width, height, pixels, color) {
  1679. var wrappedU = ((Math.abs(u) * width) % width) | 0;
  1680. var wrappedV = ((Math.abs(v) * height) % height) | 0;
  1681. var position = (wrappedU + wrappedV * width) * 4;
  1682. color.r = pixels[position] / 255;
  1683. color.g = pixels[position + 1] / 255;
  1684. color.b = pixels[position + 2] / 255;
  1685. color.a = pixels[position + 3] / 255;
  1686. };
  1687. /**
  1688. * Interpolates between a and b via alpha
  1689. * @param a The lower value (returned when alpha = 0)
  1690. * @param b The upper value (returned when alpha = 1)
  1691. * @param alpha The interpolation-factor
  1692. * @return The mixed value
  1693. */
  1694. Tools.Mix = function (a, b, alpha) {
  1695. return a * (1 - alpha) + b * alpha;
  1696. };
  1697. /**
  1698. * Tries to instantiate a new object from a given class name
  1699. * @param className defines the class name to instantiate
  1700. * @returns the new object or null if the system was not able to do the instantiation
  1701. */
  1702. Tools.Instantiate = function (className) {
  1703. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  1704. return Tools.RegisteredExternalClasses[className];
  1705. }
  1706. var arr = className.split(".");
  1707. var fn = (window || this);
  1708. for (var i = 0, len = arr.length; i < len; i++) {
  1709. fn = fn[arr[i]];
  1710. }
  1711. if (typeof fn !== "function") {
  1712. return null;
  1713. }
  1714. return fn;
  1715. };
  1716. /**
  1717. * Provides a slice function that will work even on IE
  1718. * @param data defines the array to slice
  1719. * @param start defines the start of the data (optional)
  1720. * @param end defines the end of the data (optional)
  1721. * @returns the new sliced array
  1722. */
  1723. Tools.Slice = function (data, start, end) {
  1724. if (data.slice) {
  1725. return data.slice(start, end);
  1726. }
  1727. return Array.prototype.slice.call(data, start, end);
  1728. };
  1729. /**
  1730. * Polyfill for setImmediate
  1731. * @param action defines the action to execute after the current execution block
  1732. */
  1733. Tools.SetImmediate = function (action) {
  1734. if (Tools.IsWindowObjectExist() && window.setImmediate) {
  1735. window.setImmediate(action);
  1736. }
  1737. else {
  1738. setTimeout(action, 1);
  1739. }
  1740. };
  1741. /**
  1742. * Function indicating if a number is an exponent of 2
  1743. * @param value defines the value to test
  1744. * @returns true if the value is an exponent of 2
  1745. */
  1746. Tools.IsExponentOfTwo = function (value) {
  1747. var count = 1;
  1748. do {
  1749. count *= 2;
  1750. } while (count < value);
  1751. return count === value;
  1752. };
  1753. /**
  1754. * Returns the nearest 32-bit single precision float representation of a Number
  1755. * @param value A Number. If the parameter is of a different type, it will get converted
  1756. * to a number or to NaN if it cannot be converted
  1757. * @returns number
  1758. */
  1759. Tools.FloatRound = function (value) {
  1760. if (Math.fround) {
  1761. return Math.fround(value);
  1762. }
  1763. return (Tools._tmpFloatArray[0] = value);
  1764. };
  1765. /**
  1766. * Find the next highest power of two.
  1767. * @param x Number to start search from.
  1768. * @return Next highest power of two.
  1769. */
  1770. Tools.CeilingPOT = function (x) {
  1771. x--;
  1772. x |= x >> 1;
  1773. x |= x >> 2;
  1774. x |= x >> 4;
  1775. x |= x >> 8;
  1776. x |= x >> 16;
  1777. x++;
  1778. return x;
  1779. };
  1780. /**
  1781. * Find the next lowest power of two.
  1782. * @param x Number to start search from.
  1783. * @return Next lowest power of two.
  1784. */
  1785. Tools.FloorPOT = function (x) {
  1786. x = x | (x >> 1);
  1787. x = x | (x >> 2);
  1788. x = x | (x >> 4);
  1789. x = x | (x >> 8);
  1790. x = x | (x >> 16);
  1791. return x - (x >> 1);
  1792. };
  1793. /**
  1794. * Find the nearest power of two.
  1795. * @param x Number to start search from.
  1796. * @return Next nearest power of two.
  1797. */
  1798. Tools.NearestPOT = function (x) {
  1799. var c = Tools.CeilingPOT(x);
  1800. var f = Tools.FloorPOT(x);
  1801. return (c - x) > (x - f) ? f : c;
  1802. };
  1803. /**
  1804. * Get the closest exponent of two
  1805. * @param value defines the value to approximate
  1806. * @param max defines the maximum value to return
  1807. * @param mode defines how to define the closest value
  1808. * @returns closest exponent of two of the given value
  1809. */
  1810. Tools.GetExponentOfTwo = function (value, max, mode) {
  1811. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  1812. var pot;
  1813. switch (mode) {
  1814. case BABYLON.Engine.SCALEMODE_FLOOR:
  1815. pot = Tools.FloorPOT(value);
  1816. break;
  1817. case BABYLON.Engine.SCALEMODE_NEAREST:
  1818. pot = Tools.NearestPOT(value);
  1819. break;
  1820. case BABYLON.Engine.SCALEMODE_CEILING:
  1821. default:
  1822. pot = Tools.CeilingPOT(value);
  1823. break;
  1824. }
  1825. return Math.min(pot, max);
  1826. };
  1827. /**
  1828. * Extracts the filename from a path
  1829. * @param path defines the path to use
  1830. * @returns the filename
  1831. */
  1832. Tools.GetFilename = function (path) {
  1833. var index = path.lastIndexOf("/");
  1834. if (index < 0) {
  1835. return path;
  1836. }
  1837. return path.substring(index + 1);
  1838. };
  1839. /**
  1840. * Extracts the "folder" part of a path (everything before the filename).
  1841. * @param uri The URI to extract the info from
  1842. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  1843. * @returns The "folder" part of the path
  1844. */
  1845. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  1846. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  1847. var index = uri.lastIndexOf("/");
  1848. if (index < 0) {
  1849. if (returnUnchangedIfNoSlash) {
  1850. return uri;
  1851. }
  1852. return "";
  1853. }
  1854. return uri.substring(0, index + 1);
  1855. };
  1856. /**
  1857. * Extracts text content from a DOM element hierarchy
  1858. * @param element defines the root element
  1859. * @returns a string
  1860. */
  1861. Tools.GetDOMTextContent = function (element) {
  1862. var result = "";
  1863. var child = element.firstChild;
  1864. while (child) {
  1865. if (child.nodeType === 3) {
  1866. result += child.textContent;
  1867. }
  1868. child = (child.nextSibling);
  1869. }
  1870. return result;
  1871. };
  1872. /**
  1873. * Convert an angle in radians to degrees
  1874. * @param angle defines the angle to convert
  1875. * @returns the angle in degrees
  1876. */
  1877. Tools.ToDegrees = function (angle) {
  1878. return angle * 180 / Math.PI;
  1879. };
  1880. /**
  1881. * Convert an angle in degrees to radians
  1882. * @param angle defines the angle to convert
  1883. * @returns the angle in radians
  1884. */
  1885. Tools.ToRadians = function (angle) {
  1886. return angle * Math.PI / 180;
  1887. };
  1888. /**
  1889. * Encode a buffer to a base64 string
  1890. * @param buffer defines the buffer to encode
  1891. * @returns the encoded string
  1892. */
  1893. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  1894. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  1895. var output = "";
  1896. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  1897. var i = 0;
  1898. var bytes = new Uint8Array(buffer);
  1899. while (i < bytes.length) {
  1900. chr1 = bytes[i++];
  1901. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  1902. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  1903. enc1 = chr1 >> 2;
  1904. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  1905. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  1906. enc4 = chr3 & 63;
  1907. if (isNaN(chr2)) {
  1908. enc3 = enc4 = 64;
  1909. }
  1910. else if (isNaN(chr3)) {
  1911. enc4 = 64;
  1912. }
  1913. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  1914. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  1915. }
  1916. return "data:image/png;base64," + output;
  1917. };
  1918. /**
  1919. * Extracts minimum and maximum values from a list of indexed positions
  1920. * @param positions defines the positions to use
  1921. * @param indices defines the indices to the positions
  1922. * @param indexStart defines the start index
  1923. * @param indexCount defines the end index
  1924. * @param bias defines bias value to add to the result
  1925. * @return minimum and maximum values
  1926. */
  1927. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  1928. if (bias === void 0) { bias = null; }
  1929. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  1930. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  1931. for (var index = indexStart; index < indexStart + indexCount; index++) {
  1932. var offset = indices[index] * 3;
  1933. var x = positions[offset];
  1934. var y = positions[offset + 1];
  1935. var z = positions[offset + 2];
  1936. minimum.minimizeInPlaceFromFloats(x, y, z);
  1937. maximum.maximizeInPlaceFromFloats(x, y, z);
  1938. }
  1939. if (bias) {
  1940. minimum.x -= minimum.x * bias.x + bias.y;
  1941. minimum.y -= minimum.y * bias.x + bias.y;
  1942. minimum.z -= minimum.z * bias.x + bias.y;
  1943. maximum.x += maximum.x * bias.x + bias.y;
  1944. maximum.y += maximum.y * bias.x + bias.y;
  1945. maximum.z += maximum.z * bias.x + bias.y;
  1946. }
  1947. return {
  1948. minimum: minimum,
  1949. maximum: maximum
  1950. };
  1951. };
  1952. /**
  1953. * Extracts minimum and maximum values from a list of positions
  1954. * @param positions defines the positions to use
  1955. * @param start defines the start index in the positions array
  1956. * @param count defines the number of positions to handle
  1957. * @param bias defines bias value to add to the result
  1958. * @param stride defines the stride size to use (distance between two positions in the positions array)
  1959. * @return minimum and maximum values
  1960. */
  1961. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  1962. if (bias === void 0) { bias = null; }
  1963. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  1964. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  1965. if (!stride) {
  1966. stride = 3;
  1967. }
  1968. for (var index = start, offset = start * stride; index < start + count; index++, offset += stride) {
  1969. var x = positions[offset];
  1970. var y = positions[offset + 1];
  1971. var z = positions[offset + 2];
  1972. minimum.minimizeInPlaceFromFloats(x, y, z);
  1973. maximum.maximizeInPlaceFromFloats(x, y, z);
  1974. }
  1975. if (bias) {
  1976. minimum.x -= minimum.x * bias.x + bias.y;
  1977. minimum.y -= minimum.y * bias.x + bias.y;
  1978. minimum.z -= minimum.z * bias.x + bias.y;
  1979. maximum.x += maximum.x * bias.x + bias.y;
  1980. maximum.y += maximum.y * bias.x + bias.y;
  1981. maximum.z += maximum.z * bias.x + bias.y;
  1982. }
  1983. return {
  1984. minimum: minimum,
  1985. maximum: maximum
  1986. };
  1987. };
  1988. /**
  1989. * Returns an array if obj is not an array
  1990. * @param obj defines the object to evaluate as an array
  1991. * @param allowsNullUndefined defines a boolean indicating if obj is allowed to be null or undefined
  1992. * @returns either obj directly if obj is an array or a new array containing obj
  1993. */
  1994. Tools.MakeArray = function (obj, allowsNullUndefined) {
  1995. if (allowsNullUndefined !== true && (obj === undefined || obj == null)) {
  1996. return null;
  1997. }
  1998. return Array.isArray(obj) ? obj : [obj];
  1999. };
  2000. /**
  2001. * Returns an array of the given size filled with element built from the given constructor and the paramters
  2002. * @param size the number of element to construct and put in the array
  2003. * @param itemBuilder a callback responsible for creating new instance of item. Called once per array entry.
  2004. * @returns a new array filled with new objects
  2005. */
  2006. Tools.BuildArray = function (size, itemBuilder) {
  2007. var a = [];
  2008. for (var i = 0; i < size; ++i) {
  2009. a.push(itemBuilder());
  2010. }
  2011. return a;
  2012. };
  2013. /**
  2014. * Gets the pointer prefix to use
  2015. * @returns "pointer" if touch is enabled. Else returns "mouse"
  2016. */
  2017. Tools.GetPointerPrefix = function () {
  2018. var eventPrefix = "pointer";
  2019. // Check if pointer events are supported
  2020. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  2021. eventPrefix = "mouse";
  2022. }
  2023. return eventPrefix;
  2024. };
  2025. /**
  2026. * Queue a new function into the requested animation frame pool (ie. this function will be executed byt the browser for the next frame)
  2027. * @param func - the function to be called
  2028. * @param requester - the object that will request the next frame. Falls back to window.
  2029. * @returns frame number
  2030. */
  2031. Tools.QueueNewFrame = function (func, requester) {
  2032. if (!Tools.IsWindowObjectExist()) {
  2033. return setTimeout(func, 16);
  2034. }
  2035. if (!requester) {
  2036. requester = window;
  2037. }
  2038. if (requester.requestAnimationFrame) {
  2039. return requester.requestAnimationFrame(func);
  2040. }
  2041. else if (requester.msRequestAnimationFrame) {
  2042. return requester.msRequestAnimationFrame(func);
  2043. }
  2044. else if (requester.webkitRequestAnimationFrame) {
  2045. return requester.webkitRequestAnimationFrame(func);
  2046. }
  2047. else if (requester.mozRequestAnimationFrame) {
  2048. return requester.mozRequestAnimationFrame(func);
  2049. }
  2050. else if (requester.oRequestAnimationFrame) {
  2051. return requester.oRequestAnimationFrame(func);
  2052. }
  2053. else {
  2054. return window.setTimeout(func, 16);
  2055. }
  2056. };
  2057. /**
  2058. * Ask the browser to promote the current element to fullscreen rendering mode
  2059. * @param element defines the DOM element to promote
  2060. */
  2061. Tools.RequestFullscreen = function (element) {
  2062. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  2063. if (!requestFunction) {
  2064. return;
  2065. }
  2066. requestFunction.call(element);
  2067. };
  2068. /**
  2069. * Asks the browser to exit fullscreen mode
  2070. */
  2071. Tools.ExitFullscreen = function () {
  2072. if (document.exitFullscreen) {
  2073. document.exitFullscreen();
  2074. }
  2075. else if (document.mozCancelFullScreen) {
  2076. document.mozCancelFullScreen();
  2077. }
  2078. else if (document.webkitCancelFullScreen) {
  2079. document.webkitCancelFullScreen();
  2080. }
  2081. else if (document.msCancelFullScreen) {
  2082. document.msCancelFullScreen();
  2083. }
  2084. };
  2085. /**
  2086. * Sets the cors behavior on a dom element. This will add the required Tools.CorsBehavior to the element.
  2087. * @param url define the url we are trying
  2088. * @param element define the dom element where to configure the cors policy
  2089. */
  2090. Tools.SetCorsBehavior = function (url, element) {
  2091. if (url && url.indexOf("data:") === 0) {
  2092. return;
  2093. }
  2094. if (Tools.CorsBehavior) {
  2095. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  2096. element.crossOrigin = Tools.CorsBehavior;
  2097. }
  2098. else {
  2099. var result = Tools.CorsBehavior(url);
  2100. if (result) {
  2101. element.crossOrigin = result;
  2102. }
  2103. }
  2104. }
  2105. };
  2106. // External files
  2107. /**
  2108. * Removes unwanted characters from an url
  2109. * @param url defines the url to clean
  2110. * @returns the cleaned url
  2111. */
  2112. Tools.CleanUrl = function (url) {
  2113. url = url.replace(/#/mg, "%23");
  2114. return url;
  2115. };
  2116. /**
  2117. * Loads an image as an HTMLImageElement.
  2118. * @param input url string, ArrayBuffer, or Blob to load
  2119. * @param onLoad callback called when the image successfully loads
  2120. * @param onError callback called when the image fails to load
  2121. * @param offlineProvider offline provider for caching
  2122. * @returns the HTMLImageElement of the loaded image
  2123. */
  2124. Tools.LoadImage = function (input, onLoad, onError, offlineProvider) {
  2125. var url;
  2126. var usingObjectURL = false;
  2127. if (input instanceof ArrayBuffer) {
  2128. url = URL.createObjectURL(new Blob([input]));
  2129. usingObjectURL = true;
  2130. }
  2131. else if (input instanceof Blob) {
  2132. url = URL.createObjectURL(input);
  2133. usingObjectURL = true;
  2134. }
  2135. else {
  2136. url = Tools.CleanUrl(input);
  2137. url = Tools.PreprocessUrl(input);
  2138. }
  2139. var img = new Image();
  2140. Tools.SetCorsBehavior(url, img);
  2141. var loadHandler = function () {
  2142. if (usingObjectURL && img.src) {
  2143. URL.revokeObjectURL(img.src);
  2144. }
  2145. img.removeEventListener("load", loadHandler);
  2146. img.removeEventListener("error", errorHandler);
  2147. onLoad(img);
  2148. };
  2149. var errorHandler = function (err) {
  2150. if (usingObjectURL && img.src) {
  2151. URL.revokeObjectURL(img.src);
  2152. }
  2153. img.removeEventListener("load", loadHandler);
  2154. img.removeEventListener("error", errorHandler);
  2155. Tools.Error("Error while trying to load image: " + input);
  2156. if (onError) {
  2157. onError("Error while trying to load image: " + input, err);
  2158. }
  2159. };
  2160. img.addEventListener("load", loadHandler);
  2161. img.addEventListener("error", errorHandler);
  2162. var noOfflineSupport = function () {
  2163. img.src = url;
  2164. };
  2165. var loadFromOfflineSupport = function () {
  2166. if (offlineProvider) {
  2167. offlineProvider.loadImage(url, img);
  2168. }
  2169. };
  2170. if (url.substr(0, 5) !== "data:" && offlineProvider && offlineProvider.enableTexturesOffline) {
  2171. offlineProvider.open(loadFromOfflineSupport, noOfflineSupport);
  2172. }
  2173. else {
  2174. if (url.indexOf("file:") !== -1) {
  2175. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  2176. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  2177. try {
  2178. var blobURL;
  2179. try {
  2180. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  2181. }
  2182. catch (ex) {
  2183. // Chrome doesn't support oneTimeOnly parameter
  2184. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  2185. }
  2186. img.src = blobURL;
  2187. usingObjectURL = true;
  2188. }
  2189. catch (e) {
  2190. img.src = "";
  2191. }
  2192. return img;
  2193. }
  2194. }
  2195. noOfflineSupport();
  2196. }
  2197. return img;
  2198. };
  2199. /**
  2200. * Loads a file
  2201. * @param url url string, ArrayBuffer, or Blob to load
  2202. * @param onSuccess callback called when the file successfully loads
  2203. * @param onProgress callback called while file is loading (if the server supports this mode)
  2204. * @param offlineProvider defines the offline provider for caching
  2205. * @param useArrayBuffer defines a boolean indicating that date must be returned as ArrayBuffer
  2206. * @param onError callback called when the file fails to load
  2207. * @returns a file request object
  2208. */
  2209. Tools.LoadFile = function (url, onSuccess, onProgress, offlineProvider, useArrayBuffer, onError) {
  2210. url = Tools.CleanUrl(url);
  2211. url = Tools.PreprocessUrl(url);
  2212. // If file and file input are set
  2213. if (url.indexOf("file:") !== -1) {
  2214. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  2215. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  2216. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  2217. }
  2218. }
  2219. var loadUrl = Tools.BaseUrl + url;
  2220. var aborted = false;
  2221. var fileRequest = {
  2222. onCompleteObservable: new BABYLON.Observable(),
  2223. abort: function () { return aborted = true; },
  2224. };
  2225. var requestFile = function () {
  2226. var request = new XMLHttpRequest();
  2227. var retryHandle = null;
  2228. fileRequest.abort = function () {
  2229. aborted = true;
  2230. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  2231. request.abort();
  2232. }
  2233. if (retryHandle !== null) {
  2234. clearTimeout(retryHandle);
  2235. retryHandle = null;
  2236. }
  2237. };
  2238. var retryLoop = function (retryIndex) {
  2239. request.open('GET', loadUrl, true);
  2240. if (useArrayBuffer) {
  2241. request.responseType = "arraybuffer";
  2242. }
  2243. if (onProgress) {
  2244. request.addEventListener("progress", onProgress);
  2245. }
  2246. var onLoadEnd = function () {
  2247. request.removeEventListener("loadend", onLoadEnd);
  2248. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  2249. fileRequest.onCompleteObservable.clear();
  2250. };
  2251. request.addEventListener("loadend", onLoadEnd);
  2252. var onReadyStateChange = function () {
  2253. if (aborted) {
  2254. return;
  2255. }
  2256. // In case of undefined state in some browsers.
  2257. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  2258. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  2259. request.removeEventListener("readystatechange", onReadyStateChange);
  2260. if ((request.status >= 200 && request.status < 300) || (request.status === 0 && (!Tools.IsWindowObjectExist() || Tools.IsFileURL()))) {
  2261. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  2262. return;
  2263. }
  2264. var retryStrategy = Tools.DefaultRetryStrategy;
  2265. if (retryStrategy) {
  2266. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  2267. if (waitTime !== -1) {
  2268. // Prevent the request from completing for retry.
  2269. request.removeEventListener("loadend", onLoadEnd);
  2270. request = new XMLHttpRequest();
  2271. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  2272. return;
  2273. }
  2274. }
  2275. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  2276. if (onError) {
  2277. onError(request, e);
  2278. }
  2279. else {
  2280. throw e;
  2281. }
  2282. }
  2283. };
  2284. request.addEventListener("readystatechange", onReadyStateChange);
  2285. request.send();
  2286. };
  2287. retryLoop(0);
  2288. };
  2289. // Caching all files
  2290. if (offlineProvider && offlineProvider.enableSceneOffline) {
  2291. var noOfflineSupport_1 = function (request) {
  2292. if (request && request.status > 400) {
  2293. if (onError) {
  2294. onError(request);
  2295. }
  2296. }
  2297. else {
  2298. if (!aborted) {
  2299. requestFile();
  2300. }
  2301. }
  2302. };
  2303. var loadFromOfflineSupport = function () {
  2304. // TODO: database needs to support aborting and should return a IFileRequest
  2305. if (aborted) {
  2306. return;
  2307. }
  2308. if (offlineProvider) {
  2309. offlineProvider.loadFile(url, function (data) {
  2310. if (!aborted) {
  2311. onSuccess(data);
  2312. }
  2313. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  2314. }, onProgress ? function (event) {
  2315. if (!aborted) {
  2316. onProgress(event);
  2317. }
  2318. } : undefined, noOfflineSupport_1, useArrayBuffer);
  2319. }
  2320. };
  2321. offlineProvider.open(loadFromOfflineSupport, noOfflineSupport_1);
  2322. }
  2323. else {
  2324. requestFile();
  2325. }
  2326. return fileRequest;
  2327. };
  2328. /**
  2329. * Load a script (identified by an url). When the url returns, the
  2330. * content of this file is added into a new script element, attached to the DOM (body element)
  2331. * @param scriptUrl defines the url of the script to laod
  2332. * @param onSuccess defines the callback called when the script is loaded
  2333. * @param onError defines the callback to call if an error occurs
  2334. */
  2335. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  2336. if (!Tools.IsWindowObjectExist()) {
  2337. return;
  2338. }
  2339. var head = document.getElementsByTagName('head')[0];
  2340. var script = document.createElement('script');
  2341. script.type = 'text/javascript';
  2342. script.src = scriptUrl;
  2343. script.onload = function () {
  2344. if (onSuccess) {
  2345. onSuccess();
  2346. }
  2347. };
  2348. script.onerror = function (e) {
  2349. if (onError) {
  2350. onError("Unable to load script '" + scriptUrl + "'", e);
  2351. }
  2352. };
  2353. head.appendChild(script);
  2354. };
  2355. /**
  2356. * Loads a file from a blob
  2357. * @param fileToLoad defines the blob to use
  2358. * @param callback defines the callback to call when data is loaded
  2359. * @param progressCallback defines the callback to call during loading process
  2360. * @returns a file request object
  2361. */
  2362. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  2363. var reader = new FileReader();
  2364. var request = {
  2365. onCompleteObservable: new BABYLON.Observable(),
  2366. abort: function () { return reader.abort(); },
  2367. };
  2368. reader.onloadend = function (e) {
  2369. request.onCompleteObservable.notifyObservers(request);
  2370. };
  2371. reader.onload = function (e) {
  2372. //target doesn't have result from ts 1.3
  2373. callback(e.target['result']);
  2374. };
  2375. reader.onprogress = progressCallback;
  2376. reader.readAsDataURL(fileToLoad);
  2377. return request;
  2378. };
  2379. /**
  2380. * Loads a file
  2381. * @param fileToLoad defines the file to load
  2382. * @param callback defines the callback to call when data is loaded
  2383. * @param progressCallBack defines the callback to call during loading process
  2384. * @param useArrayBuffer defines a boolean indicating that data must be returned as an ArrayBuffer
  2385. * @returns a file request object
  2386. */
  2387. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  2388. var reader = new FileReader();
  2389. var request = {
  2390. onCompleteObservable: new BABYLON.Observable(),
  2391. abort: function () { return reader.abort(); },
  2392. };
  2393. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  2394. reader.onerror = function (e) {
  2395. Tools.Log("Error while reading file: " + fileToLoad.name);
  2396. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  2397. };
  2398. reader.onload = function (e) {
  2399. //target doesn't have result from ts 1.3
  2400. callback(e.target['result']);
  2401. };
  2402. if (progressCallBack) {
  2403. reader.onprogress = progressCallBack;
  2404. }
  2405. if (!useArrayBuffer) {
  2406. // Asynchronous read
  2407. reader.readAsText(fileToLoad);
  2408. }
  2409. else {
  2410. reader.readAsArrayBuffer(fileToLoad);
  2411. }
  2412. return request;
  2413. };
  2414. /**
  2415. * Creates a data url from a given string content
  2416. * @param content defines the content to convert
  2417. * @returns the new data url link
  2418. */
  2419. Tools.FileAsURL = function (content) {
  2420. var fileBlob = new Blob([content]);
  2421. var url = window.URL || window.webkitURL;
  2422. var link = url.createObjectURL(fileBlob);
  2423. return link;
  2424. };
  2425. /**
  2426. * Format the given number to a specific decimal format
  2427. * @param value defines the number to format
  2428. * @param decimals defines the number of decimals to use
  2429. * @returns the formatted string
  2430. */
  2431. Tools.Format = function (value, decimals) {
  2432. if (decimals === void 0) { decimals = 2; }
  2433. return value.toFixed(decimals);
  2434. };
  2435. /**
  2436. * Checks if a given vector is inside a specific range
  2437. * @param v defines the vector to test
  2438. * @param min defines the minimum range
  2439. * @param max defines the maximum range
  2440. */
  2441. Tools.CheckExtends = function (v, min, max) {
  2442. min.minimizeInPlace(v);
  2443. max.maximizeInPlace(v);
  2444. };
  2445. /**
  2446. * Tries to copy an object by duplicating every property
  2447. * @param source defines the source object
  2448. * @param destination defines the target object
  2449. * @param doNotCopyList defines a list of properties to avoid
  2450. * @param mustCopyList defines a list of properties to copy (even if they start with _)
  2451. */
  2452. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  2453. for (var prop in source) {
  2454. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  2455. continue;
  2456. }
  2457. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  2458. continue;
  2459. }
  2460. var sourceValue = source[prop];
  2461. var typeOfSourceValue = typeof sourceValue;
  2462. if (typeOfSourceValue === "function") {
  2463. continue;
  2464. }
  2465. try {
  2466. if (typeOfSourceValue === "object") {
  2467. if (sourceValue instanceof Array) {
  2468. destination[prop] = [];
  2469. if (sourceValue.length > 0) {
  2470. if (typeof sourceValue[0] == "object") {
  2471. for (var index = 0; index < sourceValue.length; index++) {
  2472. var clonedValue = cloneValue(sourceValue[index], destination);
  2473. if (destination[prop].indexOf(clonedValue) === -1) { // Test if auto inject was not done
  2474. destination[prop].push(clonedValue);
  2475. }
  2476. }
  2477. }
  2478. else {
  2479. destination[prop] = sourceValue.slice(0);
  2480. }
  2481. }
  2482. }
  2483. else {
  2484. destination[prop] = cloneValue(sourceValue, destination);
  2485. }
  2486. }
  2487. else {
  2488. destination[prop] = sourceValue;
  2489. }
  2490. }
  2491. catch (e) {
  2492. // Just ignore error (it could be because of a read-only property)
  2493. }
  2494. }
  2495. };
  2496. /**
  2497. * Gets a boolean indicating if the given object has no own property
  2498. * @param obj defines the object to test
  2499. * @returns true if object has no own property
  2500. */
  2501. Tools.IsEmpty = function (obj) {
  2502. for (var i in obj) {
  2503. if (obj.hasOwnProperty(i)) {
  2504. return false;
  2505. }
  2506. }
  2507. return true;
  2508. };
  2509. /**
  2510. * Function used to register events at window level
  2511. * @param events defines the events to register
  2512. */
  2513. Tools.RegisterTopRootEvents = function (events) {
  2514. for (var index = 0; index < events.length; index++) {
  2515. var event = events[index];
  2516. window.addEventListener(event.name, event.handler, false);
  2517. try {
  2518. if (window.parent) {
  2519. window.parent.addEventListener(event.name, event.handler, false);
  2520. }
  2521. }
  2522. catch (e) {
  2523. // Silently fails...
  2524. }
  2525. }
  2526. };
  2527. /**
  2528. * Function used to unregister events from window level
  2529. * @param events defines the events to unregister
  2530. */
  2531. Tools.UnregisterTopRootEvents = function (events) {
  2532. for (var index = 0; index < events.length; index++) {
  2533. var event = events[index];
  2534. window.removeEventListener(event.name, event.handler);
  2535. try {
  2536. if (window.parent) {
  2537. window.parent.removeEventListener(event.name, event.handler);
  2538. }
  2539. }
  2540. catch (e) {
  2541. // Silently fails...
  2542. }
  2543. }
  2544. };
  2545. /**
  2546. * Dumps the current bound framebuffer
  2547. * @param width defines the rendering width
  2548. * @param height defines the rendering height
  2549. * @param engine defines the hosting engine
  2550. * @param successCallback defines the callback triggered once the data are available
  2551. * @param mimeType defines the mime type of the result
  2552. * @param fileName defines the filename to download. If present, the result will automatically be downloaded
  2553. */
  2554. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  2555. if (mimeType === void 0) { mimeType = "image/png"; }
  2556. // Read the contents of the framebuffer
  2557. var numberOfChannelsByLine = width * 4;
  2558. var halfHeight = height / 2;
  2559. //Reading datas from WebGL
  2560. var data = engine.readPixels(0, 0, width, height);
  2561. //To flip image on Y axis.
  2562. for (var i = 0; i < halfHeight; i++) {
  2563. for (var j = 0; j < numberOfChannelsByLine; j++) {
  2564. var currentCell = j + i * numberOfChannelsByLine;
  2565. var targetLine = height - i - 1;
  2566. var targetCell = j + targetLine * numberOfChannelsByLine;
  2567. var temp = data[currentCell];
  2568. data[currentCell] = data[targetCell];
  2569. data[targetCell] = temp;
  2570. }
  2571. }
  2572. // Create a 2D canvas to store the result
  2573. if (!screenshotCanvas) {
  2574. screenshotCanvas = document.createElement('canvas');
  2575. }
  2576. screenshotCanvas.width = width;
  2577. screenshotCanvas.height = height;
  2578. var context = screenshotCanvas.getContext('2d');
  2579. if (context) {
  2580. // Copy the pixels to a 2D canvas
  2581. var imageData = context.createImageData(width, height);
  2582. var castData = (imageData.data);
  2583. castData.set(data);
  2584. context.putImageData(imageData, 0, 0);
  2585. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  2586. }
  2587. };
  2588. /**
  2589. * Converts the canvas data to blob.
  2590. * This acts as a polyfill for browsers not supporting the to blob function.
  2591. * @param canvas Defines the canvas to extract the data from
  2592. * @param successCallback Defines the callback triggered once the data are available
  2593. * @param mimeType Defines the mime type of the result
  2594. */
  2595. Tools.ToBlob = function (canvas, successCallback, mimeType) {
  2596. if (mimeType === void 0) { mimeType = "image/png"; }
  2597. // We need HTMLCanvasElement.toBlob for HD screenshots
  2598. if (!canvas.toBlob) {
  2599. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  2600. canvas.toBlob = function (callback, type, quality) {
  2601. var _this = this;
  2602. setTimeout(function () {
  2603. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  2604. for (var i = 0; i < len; i++) {
  2605. arr[i] = binStr.charCodeAt(i);
  2606. }
  2607. callback(new Blob([arr]));
  2608. });
  2609. };
  2610. }
  2611. canvas.toBlob(function (blob) {
  2612. successCallback(blob);
  2613. }, mimeType);
  2614. };
  2615. /**
  2616. * Encodes the canvas data to base 64 or automatically download the result if filename is defined
  2617. * @param successCallback defines the callback triggered once the data are available
  2618. * @param mimeType defines the mime type of the result
  2619. * @param fileName defines he filename to download. If present, the result will automatically be downloaded
  2620. */
  2621. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  2622. if (mimeType === void 0) { mimeType = "image/png"; }
  2623. if (successCallback) {
  2624. var base64Image = screenshotCanvas.toDataURL(mimeType);
  2625. successCallback(base64Image);
  2626. }
  2627. else {
  2628. this.ToBlob(screenshotCanvas, function (blob) {
  2629. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  2630. if (("download" in document.createElement("a"))) {
  2631. if (!fileName) {
  2632. var date = new Date();
  2633. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  2634. fileName = "screenshot_" + stringDate + ".png";
  2635. }
  2636. Tools.Download(blob, fileName);
  2637. }
  2638. else {
  2639. var url = URL.createObjectURL(blob);
  2640. var newWindow = window.open("");
  2641. if (!newWindow) {
  2642. return;
  2643. }
  2644. var img = newWindow.document.createElement("img");
  2645. img.onload = function () {
  2646. // no longer need to read the blob so it's revoked
  2647. URL.revokeObjectURL(url);
  2648. };
  2649. img.src = url;
  2650. newWindow.document.body.appendChild(img);
  2651. }
  2652. }, mimeType);
  2653. }
  2654. };
  2655. /**
  2656. * Downloads a blob in the browser
  2657. * @param blob defines the blob to download
  2658. * @param fileName defines the name of the downloaded file
  2659. */
  2660. Tools.Download = function (blob, fileName) {
  2661. if (navigator && navigator.msSaveBlob) {
  2662. navigator.msSaveBlob(blob, fileName);
  2663. return;
  2664. }
  2665. var url = window.URL.createObjectURL(blob);
  2666. var a = document.createElement("a");
  2667. document.body.appendChild(a);
  2668. a.style.display = "none";
  2669. a.href = url;
  2670. a.download = fileName;
  2671. a.addEventListener("click", function () {
  2672. if (a.parentElement) {
  2673. a.parentElement.removeChild(a);
  2674. }
  2675. });
  2676. a.click();
  2677. window.URL.revokeObjectURL(url);
  2678. };
  2679. /**
  2680. * Captures a screenshot of the current rendering
  2681. * @see http://doc.babylonjs.com/how_to/render_scene_on_a_png
  2682. * @param engine defines the rendering engine
  2683. * @param camera defines the source camera
  2684. * @param size This parameter can be set to a single number or to an object with the
  2685. * following (optional) properties: precision, width, height. If a single number is passed,
  2686. * it will be used for both width and height. If an object is passed, the screenshot size
  2687. * will be derived from the parameters. The precision property is a multiplier allowing
  2688. * rendering at a higher or lower resolution
  2689. * @param successCallback defines the callback receives a single parameter which contains the
  2690. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  2691. * src parameter of an <img> to display it
  2692. * @param mimeType defines the MIME type of the screenshot image (default: image/png).
  2693. * Check your browser for supported MIME types
  2694. */
  2695. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  2696. if (mimeType === void 0) { mimeType = "image/png"; }
  2697. var width;
  2698. var height;
  2699. // If a precision value is specified
  2700. if (size.precision) {
  2701. width = Math.round(engine.getRenderWidth() * size.precision);
  2702. height = Math.round(width / engine.getAspectRatio(camera));
  2703. }
  2704. else if (size.width && size.height) {
  2705. width = size.width;
  2706. height = size.height;
  2707. }
  2708. //If passing only width, computing height to keep display canvas ratio.
  2709. else if (size.width && !size.height) {
  2710. width = size.width;
  2711. height = Math.round(width / engine.getAspectRatio(camera));
  2712. }
  2713. //If passing only height, computing width to keep display canvas ratio.
  2714. else if (size.height && !size.width) {
  2715. height = size.height;
  2716. width = Math.round(height * engine.getAspectRatio(camera));
  2717. }
  2718. //Assuming here that "size" parameter is a number
  2719. else if (!isNaN(size)) {
  2720. height = size;
  2721. width = size;
  2722. }
  2723. else {
  2724. Tools.Error("Invalid 'size' parameter !");
  2725. return;
  2726. }
  2727. if (!screenshotCanvas) {
  2728. screenshotCanvas = document.createElement('canvas');
  2729. }
  2730. screenshotCanvas.width = width;
  2731. screenshotCanvas.height = height;
  2732. var renderContext = screenshotCanvas.getContext("2d");
  2733. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  2734. var newWidth = width;
  2735. var newHeight = newWidth / ratio;
  2736. if (newHeight > height) {
  2737. newHeight = height;
  2738. newWidth = newHeight * ratio;
  2739. }
  2740. var offsetX = Math.max(0, width - newWidth) / 2;
  2741. var offsetY = Math.max(0, height - newHeight) / 2;
  2742. var renderingCanvas = engine.getRenderingCanvas();
  2743. if (renderContext && renderingCanvas) {
  2744. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  2745. }
  2746. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  2747. };
  2748. /**
  2749. * Generates an image screenshot from the specified camera.
  2750. * @see http://doc.babylonjs.com/how_to/render_scene_on_a_png
  2751. * @param engine The engine to use for rendering
  2752. * @param camera The camera to use for rendering
  2753. * @param size This parameter can be set to a single number or to an object with the
  2754. * following (optional) properties: precision, width, height. If a single number is passed,
  2755. * it will be used for both width and height. If an object is passed, the screenshot size
  2756. * will be derived from the parameters. The precision property is a multiplier allowing
  2757. * rendering at a higher or lower resolution
  2758. * @param successCallback The callback receives a single parameter which contains the
  2759. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  2760. * src parameter of an <img> to display it
  2761. * @param mimeType The MIME type of the screenshot image (default: image/png).
  2762. * Check your browser for supported MIME types
  2763. * @param samples Texture samples (default: 1)
  2764. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  2765. * @param fileName A name for for the downloaded file.
  2766. */
  2767. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  2768. if (mimeType === void 0) { mimeType = "image/png"; }
  2769. if (samples === void 0) { samples = 1; }
  2770. if (antialiasing === void 0) { antialiasing = false; }
  2771. var width;
  2772. var height;
  2773. //If a precision value is specified
  2774. if (size.precision) {
  2775. width = Math.round(engine.getRenderWidth() * size.precision);
  2776. height = Math.round(width / engine.getAspectRatio(camera));
  2777. size = { width: width, height: height };
  2778. }
  2779. else if (size.width && size.height) {
  2780. width = size.width;
  2781. height = size.height;
  2782. }
  2783. //If passing only width, computing height to keep display canvas ratio.
  2784. else if (size.width && !size.height) {
  2785. width = size.width;
  2786. height = Math.round(width / engine.getAspectRatio(camera));
  2787. size = { width: width, height: height };
  2788. }
  2789. //If passing only height, computing width to keep display canvas ratio.
  2790. else if (size.height && !size.width) {
  2791. height = size.height;
  2792. width = Math.round(height * engine.getAspectRatio(camera));
  2793. size = { width: width, height: height };
  2794. }
  2795. //Assuming here that "size" parameter is a number
  2796. else if (!isNaN(size)) {
  2797. height = size;
  2798. width = size;
  2799. }
  2800. else {
  2801. Tools.Error("Invalid 'size' parameter !");
  2802. return;
  2803. }
  2804. var scene = camera.getScene();
  2805. var previousCamera = null;
  2806. if (scene.activeCamera !== camera) {
  2807. previousCamera = scene.activeCamera;
  2808. scene.activeCamera = camera;
  2809. }
  2810. var renderCanvas = engine.getRenderingCanvas();
  2811. if (!renderCanvas) {
  2812. Tools.Error("No rendering canvas found !");
  2813. return;
  2814. }
  2815. var originalSize = { width: renderCanvas.width, height: renderCanvas.height };
  2816. engine.setSize(width, height);
  2817. scene.render();
  2818. // At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  2819. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  2820. texture.renderList = null;
  2821. texture.samples = samples;
  2822. if (antialiasing) {
  2823. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  2824. }
  2825. texture.onAfterRenderObservable.add(function () {
  2826. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  2827. });
  2828. scene.incrementRenderId();
  2829. scene.resetCachedMaterial();
  2830. texture.render(true);
  2831. texture.dispose();
  2832. if (previousCamera) {
  2833. scene.activeCamera = previousCamera;
  2834. }
  2835. engine.setSize(originalSize.width, originalSize.height);
  2836. camera.getProjectionMatrix(true); // Force cache refresh;
  2837. };
  2838. /**
  2839. * Validates if xhr data is correct
  2840. * @param xhr defines the request to validate
  2841. * @param dataType defines the expected data type
  2842. * @returns true if data is correct
  2843. */
  2844. Tools.ValidateXHRData = function (xhr, dataType) {
  2845. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  2846. if (dataType === void 0) { dataType = 7; }
  2847. try {
  2848. if (dataType & 1) {
  2849. if (xhr.responseText && xhr.responseText.length > 0) {
  2850. return true;
  2851. }
  2852. else if (dataType === 1) {
  2853. return false;
  2854. }
  2855. }
  2856. if (dataType & 2) {
  2857. // Check header width and height since there is no "TGA" magic number
  2858. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  2859. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  2860. return true;
  2861. }
  2862. else if (dataType === 2) {
  2863. return false;
  2864. }
  2865. }
  2866. if (dataType & 4) {
  2867. // Check for the "DDS" magic number
  2868. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  2869. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  2870. return true;
  2871. }
  2872. else {
  2873. return false;
  2874. }
  2875. }
  2876. }
  2877. catch (e) {
  2878. // Global protection
  2879. }
  2880. return false;
  2881. };
  2882. /**
  2883. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  2884. * Be aware Math.random() could cause collisions, but:
  2885. * "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"
  2886. * @returns a pseudo random id
  2887. */
  2888. Tools.RandomId = function () {
  2889. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  2890. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  2891. return v.toString(16);
  2892. });
  2893. };
  2894. /**
  2895. * Test if the given uri is a base64 string
  2896. * @param uri The uri to test
  2897. * @return True if the uri is a base64 string or false otherwise
  2898. */
  2899. Tools.IsBase64 = function (uri) {
  2900. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  2901. };
  2902. /**
  2903. * Decode the given base64 uri.
  2904. * @param uri The uri to decode
  2905. * @return The decoded base64 data.
  2906. */
  2907. Tools.DecodeBase64 = function (uri) {
  2908. var decodedString = atob(uri.split(",")[1]);
  2909. var bufferLength = decodedString.length;
  2910. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  2911. for (var i = 0; i < bufferLength; i++) {
  2912. bufferView[i] = decodedString.charCodeAt(i);
  2913. }
  2914. return bufferView.buffer;
  2915. };
  2916. Tools._AddLogEntry = function (entry) {
  2917. Tools._LogCache = entry + Tools._LogCache;
  2918. if (Tools.OnNewCacheEntry) {
  2919. Tools.OnNewCacheEntry(entry);
  2920. }
  2921. };
  2922. Tools._FormatMessage = function (message) {
  2923. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  2924. var date = new Date();
  2925. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  2926. };
  2927. Tools._LogDisabled = function (message) {
  2928. // nothing to do
  2929. };
  2930. Tools._LogEnabled = function (message) {
  2931. var formattedMessage = Tools._FormatMessage(message);
  2932. console.log("BJS - " + formattedMessage);
  2933. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  2934. Tools._AddLogEntry(entry);
  2935. };
  2936. Tools._WarnDisabled = function (message) {
  2937. // nothing to do
  2938. };
  2939. Tools._WarnEnabled = function (message) {
  2940. var formattedMessage = Tools._FormatMessage(message);
  2941. console.warn("BJS - " + formattedMessage);
  2942. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  2943. Tools._AddLogEntry(entry);
  2944. };
  2945. Tools._ErrorDisabled = function (message) {
  2946. // nothing to do
  2947. };
  2948. Tools._ErrorEnabled = function (message) {
  2949. Tools.errorsCount++;
  2950. var formattedMessage = Tools._FormatMessage(message);
  2951. console.error("BJS - " + formattedMessage);
  2952. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  2953. Tools._AddLogEntry(entry);
  2954. };
  2955. Object.defineProperty(Tools, "LogCache", {
  2956. /**
  2957. * Gets current log cache (list of logs)
  2958. */
  2959. get: function () {
  2960. return Tools._LogCache;
  2961. },
  2962. enumerable: true,
  2963. configurable: true
  2964. });
  2965. /**
  2966. * Clears the log cache
  2967. */
  2968. Tools.ClearLogCache = function () {
  2969. Tools._LogCache = "";
  2970. Tools.errorsCount = 0;
  2971. };
  2972. Object.defineProperty(Tools, "LogLevels", {
  2973. /**
  2974. * Sets the current log level (MessageLogLevel / WarningLogLevel / ErrorLogLevel)
  2975. */
  2976. set: function (level) {
  2977. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  2978. Tools.Log = Tools._LogEnabled;
  2979. }
  2980. else {
  2981. Tools.Log = Tools._LogDisabled;
  2982. }
  2983. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  2984. Tools.Warn = Tools._WarnEnabled;
  2985. }
  2986. else {
  2987. Tools.Warn = Tools._WarnDisabled;
  2988. }
  2989. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  2990. Tools.Error = Tools._ErrorEnabled;
  2991. }
  2992. else {
  2993. Tools.Error = Tools._ErrorDisabled;
  2994. }
  2995. },
  2996. enumerable: true,
  2997. configurable: true
  2998. });
  2999. /**
  3000. * Checks if the loaded document was accessed via `file:`-Protocol.
  3001. * @returns boolean
  3002. */
  3003. Tools.IsFileURL = function () {
  3004. return location.protocol === "file:";
  3005. };
  3006. /**
  3007. * Checks if the window object exists
  3008. * @returns true if the window object exists
  3009. */
  3010. Tools.IsWindowObjectExist = function () {
  3011. return (typeof window) !== "undefined";
  3012. };
  3013. Object.defineProperty(Tools, "PerformanceLogLevel", {
  3014. /**
  3015. * Sets the current performance log level
  3016. */
  3017. set: function (level) {
  3018. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  3019. Tools.StartPerformanceCounter = Tools._StartUserMark;
  3020. Tools.EndPerformanceCounter = Tools._EndUserMark;
  3021. return;
  3022. }
  3023. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  3024. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  3025. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  3026. return;
  3027. }
  3028. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  3029. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  3030. },
  3031. enumerable: true,
  3032. configurable: true
  3033. });
  3034. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  3035. };
  3036. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  3037. };
  3038. Tools._StartUserMark = function (counterName, condition) {
  3039. if (condition === void 0) { condition = true; }
  3040. if (!Tools._performance) {
  3041. if (!Tools.IsWindowObjectExist()) {
  3042. return;
  3043. }
  3044. Tools._performance = window.performance;
  3045. }
  3046. if (!condition || !Tools._performance.mark) {
  3047. return;
  3048. }
  3049. Tools._performance.mark(counterName + "-Begin");
  3050. };
  3051. Tools._EndUserMark = function (counterName, condition) {
  3052. if (condition === void 0) { condition = true; }
  3053. if (!condition || !Tools._performance.mark) {
  3054. return;
  3055. }
  3056. Tools._performance.mark(counterName + "-End");
  3057. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  3058. };
  3059. Tools._StartPerformanceConsole = function (counterName, condition) {
  3060. if (condition === void 0) { condition = true; }
  3061. if (!condition) {
  3062. return;
  3063. }
  3064. Tools._StartUserMark(counterName, condition);
  3065. if (console.time) {
  3066. console.time(counterName);
  3067. }
  3068. };
  3069. Tools._EndPerformanceConsole = function (counterName, condition) {
  3070. if (condition === void 0) { condition = true; }
  3071. if (!condition) {
  3072. return;
  3073. }
  3074. Tools._EndUserMark(counterName, condition);
  3075. if (console.time) {
  3076. console.timeEnd(counterName);
  3077. }
  3078. };
  3079. Object.defineProperty(Tools, "Now", {
  3080. /**
  3081. * Gets either window.performance.now() if supported or Date.now() else
  3082. */
  3083. get: function () {
  3084. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  3085. return window.performance.now();
  3086. }
  3087. return Date.now();
  3088. },
  3089. enumerable: true,
  3090. configurable: true
  3091. });
  3092. /**
  3093. * This method will return the name of the class used to create the instance of the given object.
  3094. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  3095. * @param object the object to get the class name from
  3096. * @param isType defines if the object is actually a type
  3097. * @returns the name of the class, will be "object" for a custom data type not using the @className decorator
  3098. */
  3099. Tools.GetClassName = function (object, isType) {
  3100. if (isType === void 0) { isType = false; }
  3101. var name = null;
  3102. if (!isType && object.getClassName) {
  3103. name = object.getClassName();
  3104. }
  3105. else {
  3106. if (object instanceof Object) {
  3107. var classObj = isType ? object : Object.getPrototypeOf(object);
  3108. name = classObj.constructor["__bjsclassName__"];
  3109. }
  3110. if (!name) {
  3111. name = typeof object;
  3112. }
  3113. }
  3114. return name;
  3115. };
  3116. /**
  3117. * Gets the first element of an array satisfying a given predicate
  3118. * @param array defines the array to browse
  3119. * @param predicate defines the predicate to use
  3120. * @returns null if not found or the element
  3121. */
  3122. Tools.First = function (array, predicate) {
  3123. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  3124. var el = array_1[_i];
  3125. if (predicate(el)) {
  3126. return el;
  3127. }
  3128. }
  3129. return null;
  3130. };
  3131. /**
  3132. * This method will return the name of the full name of the class, including its owning module (if any).
  3133. * 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).
  3134. * @param object the object to get the class name from
  3135. * @param isType defines if the object is actually a type
  3136. * @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.
  3137. * @ignorenaming
  3138. */
  3139. Tools.getFullClassName = function (object, isType) {
  3140. if (isType === void 0) { isType = false; }
  3141. var className = null;
  3142. var moduleName = null;
  3143. if (!isType && object.getClassName) {
  3144. className = object.getClassName();
  3145. }
  3146. else {
  3147. if (object instanceof Object) {
  3148. var classObj = isType ? object : Object.getPrototypeOf(object);
  3149. className = classObj.constructor["__bjsclassName__"];
  3150. moduleName = classObj.constructor["__bjsmoduleName__"];
  3151. }
  3152. if (!className) {
  3153. className = typeof object;
  3154. }
  3155. }
  3156. if (!className) {
  3157. return null;
  3158. }
  3159. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  3160. };
  3161. /**
  3162. * Returns a promise that resolves after the given amount of time.
  3163. * @param delay Number of milliseconds to delay
  3164. * @returns Promise that resolves after the given amount of time
  3165. */
  3166. Tools.DelayAsync = function (delay) {
  3167. return new Promise(function (resolve) {
  3168. setTimeout(function () {
  3169. resolve();
  3170. }, delay);
  3171. });
  3172. };
  3173. /**
  3174. * Gets the current gradient from an array of IValueGradient
  3175. * @param ratio defines the current ratio to get
  3176. * @param gradients defines the array of IValueGradient
  3177. * @param updateFunc defines the callback function used to get the final value from the selected gradients
  3178. */
  3179. Tools.GetCurrentGradient = function (ratio, gradients, updateFunc) {
  3180. for (var gradientIndex = 0; gradientIndex < gradients.length - 1; gradientIndex++) {
  3181. var currentGradient = gradients[gradientIndex];
  3182. var nextGradient = gradients[gradientIndex + 1];
  3183. if (ratio >= currentGradient.gradient && ratio <= nextGradient.gradient) {
  3184. var scale = (ratio - currentGradient.gradient) / (nextGradient.gradient - currentGradient.gradient);
  3185. updateFunc(currentGradient, nextGradient, scale);
  3186. return;
  3187. }
  3188. }
  3189. // Use last index if over
  3190. var lastIndex = gradients.length - 1;
  3191. updateFunc(gradients[lastIndex], gradients[lastIndex], 1.0);
  3192. };
  3193. /**
  3194. * Gets or sets the base URL to use to load assets
  3195. */
  3196. Tools.BaseUrl = "";
  3197. /**
  3198. * Gets or sets the retry strategy to apply when an error happens while loading an asset
  3199. */
  3200. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  3201. /**
  3202. * Default behaviour for cors in the application.
  3203. * It can be a string if the expected behavior is identical in the entire app.
  3204. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  3205. */
  3206. Tools.CorsBehavior = "anonymous";
  3207. /**
  3208. * Gets or sets a global variable indicating if fallback texture must be used when a texture cannot be loaded
  3209. * @ignorenaming
  3210. */
  3211. Tools.UseFallbackTexture = true;
  3212. /**
  3213. * Use this object to register external classes like custom textures or material
  3214. * to allow the laoders to instantiate them
  3215. */
  3216. Tools.RegisteredExternalClasses = {};
  3217. /**
  3218. * Texture content used if a texture cannot loaded
  3219. * @ignorenaming
  3220. */
  3221. 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";
  3222. Tools._tmpFloatArray = new Float32Array(1);
  3223. /**
  3224. * Gets or sets a function used to pre-process url before using them to load assets
  3225. */
  3226. Tools.PreprocessUrl = function (url) {
  3227. return url;
  3228. };
  3229. // Logs
  3230. /**
  3231. * No log
  3232. */
  3233. Tools.NoneLogLevel = 0;
  3234. /**
  3235. * Only message logs
  3236. */
  3237. Tools.MessageLogLevel = 1;
  3238. /**
  3239. * Only warning logs
  3240. */
  3241. Tools.WarningLogLevel = 2;
  3242. /**
  3243. * Only error logs
  3244. */
  3245. Tools.ErrorLogLevel = 4;
  3246. /**
  3247. * All logs
  3248. */
  3249. Tools.AllLogLevel = 7;
  3250. Tools._LogCache = "";
  3251. /**
  3252. * Gets a value indicating the number of loading errors
  3253. * @ignorenaming
  3254. */
  3255. Tools.errorsCount = 0;
  3256. /**
  3257. * Log a message to the console
  3258. */
  3259. Tools.Log = Tools._LogEnabled;
  3260. /**
  3261. * Write a warning message to the console
  3262. */
  3263. Tools.Warn = Tools._WarnEnabled;
  3264. /**
  3265. * Write an error message to the console
  3266. */
  3267. Tools.Error = Tools._ErrorEnabled;
  3268. // Performances
  3269. /**
  3270. * No performance log
  3271. */
  3272. Tools.PerformanceNoneLogLevel = 0;
  3273. /**
  3274. * Use user marks to log performance
  3275. */
  3276. Tools.PerformanceUserMarkLogLevel = 1;
  3277. /**
  3278. * Log performance to the console
  3279. */
  3280. Tools.PerformanceConsoleLogLevel = 2;
  3281. /**
  3282. * Starts a performance counter
  3283. */
  3284. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  3285. /**
  3286. * Ends a specific performance coutner
  3287. */
  3288. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  3289. return Tools;
  3290. }());
  3291. BABYLON.Tools = Tools;
  3292. /**
  3293. * This class is used to track a performance counter which is number based.
  3294. * The user has access to many properties which give statistics of different nature.
  3295. *
  3296. * The implementer can track two kinds of Performance Counter: time and count.
  3297. * 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.
  3298. * 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.
  3299. */
  3300. var PerfCounter = /** @class */ (function () {
  3301. /**
  3302. * Creates a new counter
  3303. */
  3304. function PerfCounter() {
  3305. this._startMonitoringTime = 0;
  3306. this._min = 0;
  3307. this._max = 0;
  3308. this._average = 0;
  3309. this._lastSecAverage = 0;
  3310. this._current = 0;
  3311. this._totalValueCount = 0;
  3312. this._totalAccumulated = 0;
  3313. this._lastSecAccumulated = 0;
  3314. this._lastSecTime = 0;
  3315. this._lastSecValueCount = 0;
  3316. }
  3317. Object.defineProperty(PerfCounter.prototype, "min", {
  3318. /**
  3319. * Returns the smallest value ever
  3320. */
  3321. get: function () {
  3322. return this._min;
  3323. },
  3324. enumerable: true,
  3325. configurable: true
  3326. });
  3327. Object.defineProperty(PerfCounter.prototype, "max", {
  3328. /**
  3329. * Returns the biggest value ever
  3330. */
  3331. get: function () {
  3332. return this._max;
  3333. },
  3334. enumerable: true,
  3335. configurable: true
  3336. });
  3337. Object.defineProperty(PerfCounter.prototype, "average", {
  3338. /**
  3339. * Returns the average value since the performance counter is running
  3340. */
  3341. get: function () {
  3342. return this._average;
  3343. },
  3344. enumerable: true,
  3345. configurable: true
  3346. });
  3347. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  3348. /**
  3349. * Returns the average value of the last second the counter was monitored
  3350. */
  3351. get: function () {
  3352. return this._lastSecAverage;
  3353. },
  3354. enumerable: true,
  3355. configurable: true
  3356. });
  3357. Object.defineProperty(PerfCounter.prototype, "current", {
  3358. /**
  3359. * Returns the current value
  3360. */
  3361. get: function () {
  3362. return this._current;
  3363. },
  3364. enumerable: true,
  3365. configurable: true
  3366. });
  3367. Object.defineProperty(PerfCounter.prototype, "total", {
  3368. /**
  3369. * Gets the accumulated total
  3370. */
  3371. get: function () {
  3372. return this._totalAccumulated;
  3373. },
  3374. enumerable: true,
  3375. configurable: true
  3376. });
  3377. Object.defineProperty(PerfCounter.prototype, "count", {
  3378. /**
  3379. * Gets the total value count
  3380. */
  3381. get: function () {
  3382. return this._totalValueCount;
  3383. },
  3384. enumerable: true,
  3385. configurable: true
  3386. });
  3387. /**
  3388. * Call this method to start monitoring a new frame.
  3389. * 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.
  3390. */
  3391. PerfCounter.prototype.fetchNewFrame = function () {
  3392. this._totalValueCount++;
  3393. this._current = 0;
  3394. this._lastSecValueCount++;
  3395. };
  3396. /**
  3397. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  3398. * @param newCount the count value to add to the monitored count
  3399. * @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.
  3400. */
  3401. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  3402. if (!PerfCounter.Enabled) {
  3403. return;
  3404. }
  3405. this._current += newCount;
  3406. if (fetchResult) {
  3407. this._fetchResult();
  3408. }
  3409. };
  3410. /**
  3411. * Start monitoring this performance counter
  3412. */
  3413. PerfCounter.prototype.beginMonitoring = function () {
  3414. if (!PerfCounter.Enabled) {
  3415. return;
  3416. }
  3417. this._startMonitoringTime = Tools.Now;
  3418. };
  3419. /**
  3420. * Compute the time lapsed since the previous beginMonitoring() call.
  3421. * @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
  3422. */
  3423. PerfCounter.prototype.endMonitoring = function (newFrame) {
  3424. if (newFrame === void 0) { newFrame = true; }
  3425. if (!PerfCounter.Enabled) {
  3426. return;
  3427. }
  3428. if (newFrame) {
  3429. this.fetchNewFrame();
  3430. }
  3431. var currentTime = Tools.Now;
  3432. this._current = currentTime - this._startMonitoringTime;
  3433. if (newFrame) {
  3434. this._fetchResult();
  3435. }
  3436. };
  3437. PerfCounter.prototype._fetchResult = function () {
  3438. this._totalAccumulated += this._current;
  3439. this._lastSecAccumulated += this._current;
  3440. // Min/Max update
  3441. this._min = Math.min(this._min, this._current);
  3442. this._max = Math.max(this._max, this._current);
  3443. this._average = this._totalAccumulated / this._totalValueCount;
  3444. // Reset last sec?
  3445. var now = Tools.Now;
  3446. if ((now - this._lastSecTime) > 1000) {
  3447. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  3448. this._lastSecTime = now;
  3449. this._lastSecAccumulated = 0;
  3450. this._lastSecValueCount = 0;
  3451. }
  3452. };
  3453. /**
  3454. * Gets or sets a global boolean to turn on and off all the counters
  3455. */
  3456. PerfCounter.Enabled = true;
  3457. return PerfCounter;
  3458. }());
  3459. BABYLON.PerfCounter = PerfCounter;
  3460. /**
  3461. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  3462. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  3463. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  3464. * @param name The name of the class, case should be preserved
  3465. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  3466. */
  3467. function className(name, module) {
  3468. return function (target) {
  3469. target["__bjsclassName__"] = name;
  3470. target["__bjsmoduleName__"] = (module != null) ? module : null;
  3471. };
  3472. }
  3473. BABYLON.className = className;
  3474. /**
  3475. * An implementation of a loop for asynchronous functions.
  3476. */
  3477. var AsyncLoop = /** @class */ (function () {
  3478. /**
  3479. * Constructor.
  3480. * @param iterations the number of iterations.
  3481. * @param func the function to run each iteration
  3482. * @param successCallback the callback that will be called upon succesful execution
  3483. * @param offset starting offset.
  3484. */
  3485. function AsyncLoop(
  3486. /**
  3487. * Defines the number of iterations for the loop
  3488. */
  3489. iterations, func, successCallback, offset) {
  3490. if (offset === void 0) { offset = 0; }
  3491. this.iterations = iterations;
  3492. this.index = offset - 1;
  3493. this._done = false;
  3494. this._fn = func;
  3495. this._successCallback = successCallback;
  3496. }
  3497. /**
  3498. * Execute the next iteration. Must be called after the last iteration was finished.
  3499. */
  3500. AsyncLoop.prototype.executeNext = function () {
  3501. if (!this._done) {
  3502. if (this.index + 1 < this.iterations) {
  3503. ++this.index;
  3504. this._fn(this);
  3505. }
  3506. else {
  3507. this.breakLoop();
  3508. }
  3509. }
  3510. };
  3511. /**
  3512. * Break the loop and run the success callback.
  3513. */
  3514. AsyncLoop.prototype.breakLoop = function () {
  3515. this._done = true;
  3516. this._successCallback();
  3517. };
  3518. /**
  3519. * Create and run an async loop.
  3520. * @param iterations the number of iterations.
  3521. * @param fn the function to run each iteration
  3522. * @param successCallback the callback that will be called upon succesful execution
  3523. * @param offset starting offset.
  3524. * @returns the created async loop object
  3525. */
  3526. AsyncLoop.Run = function (iterations, fn, successCallback, offset) {
  3527. if (offset === void 0) { offset = 0; }
  3528. var loop = new AsyncLoop(iterations, fn, successCallback, offset);
  3529. loop.executeNext();
  3530. return loop;
  3531. };
  3532. /**
  3533. * A for-loop that will run a given number of iterations synchronous and the rest async.
  3534. * @param iterations total number of iterations
  3535. * @param syncedIterations number of synchronous iterations in each async iteration.
  3536. * @param fn the function to call each iteration.
  3537. * @param callback a success call back that will be called when iterating stops.
  3538. * @param breakFunction a break condition (optional)
  3539. * @param timeout timeout settings for the setTimeout function. default - 0.
  3540. * @returns the created async loop object
  3541. */
  3542. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  3543. if (timeout === void 0) { timeout = 0; }
  3544. return AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  3545. if (breakFunction && breakFunction()) {
  3546. loop.breakLoop();
  3547. }
  3548. else {
  3549. setTimeout(function () {
  3550. for (var i = 0; i < syncedIterations; ++i) {
  3551. var iteration = (loop.index * syncedIterations) + i;
  3552. if (iteration >= iterations) {
  3553. break;
  3554. }
  3555. fn(iteration);
  3556. if (breakFunction && breakFunction()) {
  3557. loop.breakLoop();
  3558. break;
  3559. }
  3560. }
  3561. loop.executeNext();
  3562. }, timeout);
  3563. }
  3564. }, callback);
  3565. };
  3566. return AsyncLoop;
  3567. }());
  3568. BABYLON.AsyncLoop = AsyncLoop;
  3569. })(BABYLON || (BABYLON = {}));
  3570. //# sourceMappingURL=babylon.tools.js.map
  3571. var BABYLON;
  3572. (function (BABYLON) {
  3573. /**
  3574. * Constant used to convert a value to gamma space
  3575. * @ignorenaming
  3576. */
  3577. BABYLON.ToGammaSpace = 1 / 2.2;
  3578. /**
  3579. * Constant used to convert a value to linear space
  3580. * @ignorenaming
  3581. */
  3582. BABYLON.ToLinearSpace = 2.2;
  3583. /**
  3584. * Constant used to define the minimal number value in Babylon.js
  3585. * @ignorenaming
  3586. */
  3587. BABYLON.Epsilon = 0.001;
  3588. /**
  3589. * Class used to hold a RBG color
  3590. */
  3591. var Color3 = /** @class */ (function () {
  3592. /**
  3593. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  3594. * @param r defines the red component (between 0 and 1, default is 0)
  3595. * @param g defines the green component (between 0 and 1, default is 0)
  3596. * @param b defines the blue component (between 0 and 1, default is 0)
  3597. */
  3598. function Color3(
  3599. /**
  3600. * Defines the red component (between 0 and 1, default is 0)
  3601. */
  3602. r,
  3603. /**
  3604. * Defines the green component (between 0 and 1, default is 0)
  3605. */
  3606. g,
  3607. /**
  3608. * Defines the blue component (between 0 and 1, default is 0)
  3609. */
  3610. b) {
  3611. if (r === void 0) { r = 0; }
  3612. if (g === void 0) { g = 0; }
  3613. if (b === void 0) { b = 0; }
  3614. this.r = r;
  3615. this.g = g;
  3616. this.b = b;
  3617. }
  3618. /**
  3619. * Creates a string with the Color3 current values
  3620. * @returns the string representation of the Color3 object
  3621. */
  3622. Color3.prototype.toString = function () {
  3623. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  3624. };
  3625. /**
  3626. * Returns the string "Color3"
  3627. * @returns "Color3"
  3628. */
  3629. Color3.prototype.getClassName = function () {
  3630. return "Color3";
  3631. };
  3632. /**
  3633. * Compute the Color3 hash code
  3634. * @returns an unique number that can be used to hash Color3 objects
  3635. */
  3636. Color3.prototype.getHashCode = function () {
  3637. var hash = this.r || 0;
  3638. hash = (hash * 397) ^ (this.g || 0);
  3639. hash = (hash * 397) ^ (this.b || 0);
  3640. return hash;
  3641. };
  3642. // Operators
  3643. /**
  3644. * Stores in the given array from the given starting index the red, green, blue values as successive elements
  3645. * @param array defines the array where to store the r,g,b components
  3646. * @param index defines an optional index in the target array to define where to start storing values
  3647. * @returns the current Color3 object
  3648. */
  3649. Color3.prototype.toArray = function (array, index) {
  3650. if (index === void 0) { index = 0; }
  3651. array[index] = this.r;
  3652. array[index + 1] = this.g;
  3653. array[index + 2] = this.b;
  3654. return this;
  3655. };
  3656. /**
  3657. * Returns a new Color4 object from the current Color3 and the given alpha
  3658. * @param alpha defines the alpha component on the new Color4 object (default is 1)
  3659. * @returns a new Color4 object
  3660. */
  3661. Color3.prototype.toColor4 = function (alpha) {
  3662. if (alpha === void 0) { alpha = 1; }
  3663. return new Color4(this.r, this.g, this.b, alpha);
  3664. };
  3665. /**
  3666. * Returns a new array populated with 3 numeric elements : red, green and blue values
  3667. * @returns the new array
  3668. */
  3669. Color3.prototype.asArray = function () {
  3670. var result = new Array();
  3671. this.toArray(result, 0);
  3672. return result;
  3673. };
  3674. /**
  3675. * Returns the luminance value
  3676. * @returns a float value
  3677. */
  3678. Color3.prototype.toLuminance = function () {
  3679. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  3680. };
  3681. /**
  3682. * Multiply each Color3 rgb values by the given Color3 rgb values in a new Color3 object
  3683. * @param otherColor defines the second operand
  3684. * @returns the new Color3 object
  3685. */
  3686. Color3.prototype.multiply = function (otherColor) {
  3687. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  3688. };
  3689. /**
  3690. * Multiply the rgb values of the Color3 and the given Color3 and stores the result in the object "result"
  3691. * @param otherColor defines the second operand
  3692. * @param result defines the Color3 object where to store the result
  3693. * @returns the current Color3
  3694. */
  3695. Color3.prototype.multiplyToRef = function (otherColor, result) {
  3696. result.r = this.r * otherColor.r;
  3697. result.g = this.g * otherColor.g;
  3698. result.b = this.b * otherColor.b;
  3699. return this;
  3700. };
  3701. /**
  3702. * Determines equality between Color3 objects
  3703. * @param otherColor defines the second operand
  3704. * @returns true if the rgb values are equal to the given ones
  3705. */
  3706. Color3.prototype.equals = function (otherColor) {
  3707. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  3708. };
  3709. /**
  3710. * Determines equality between the current Color3 object and a set of r,b,g values
  3711. * @param r defines the red component to check
  3712. * @param g defines the green component to check
  3713. * @param b defines the blue component to check
  3714. * @returns true if the rgb values are equal to the given ones
  3715. */
  3716. Color3.prototype.equalsFloats = function (r, g, b) {
  3717. return this.r === r && this.g === g && this.b === b;
  3718. };
  3719. /**
  3720. * Multiplies in place each rgb value by scale
  3721. * @param scale defines the scaling factor
  3722. * @returns the updated Color3
  3723. */
  3724. Color3.prototype.scale = function (scale) {
  3725. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  3726. };
  3727. /**
  3728. * Multiplies the rgb values by scale and stores the result into "result"
  3729. * @param scale defines the scaling factor
  3730. * @param result defines the Color3 object where to store the result
  3731. * @returns the unmodified current Color3
  3732. */
  3733. Color3.prototype.scaleToRef = function (scale, result) {
  3734. result.r = this.r * scale;
  3735. result.g = this.g * scale;
  3736. result.b = this.b * scale;
  3737. return this;
  3738. };
  3739. /**
  3740. * Scale the current Color3 values by a factor and add the result to a given Color3
  3741. * @param scale defines the scale factor
  3742. * @param result defines color to store the result into
  3743. * @returns the unmodified current Color3
  3744. */
  3745. Color3.prototype.scaleAndAddToRef = function (scale, result) {
  3746. result.r += this.r * scale;
  3747. result.g += this.g * scale;
  3748. result.b += this.b * scale;
  3749. return this;
  3750. };
  3751. /**
  3752. * Clamps the rgb values by the min and max values and stores the result into "result"
  3753. * @param min defines minimum clamping value (default is 0)
  3754. * @param max defines maximum clamping value (default is 1)
  3755. * @param result defines color to store the result into
  3756. * @returns the original Color3
  3757. */
  3758. Color3.prototype.clampToRef = function (min, max, result) {
  3759. if (min === void 0) { min = 0; }
  3760. if (max === void 0) { max = 1; }
  3761. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  3762. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  3763. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  3764. return this;
  3765. };
  3766. /**
  3767. * Creates a new Color3 set with the added values of the current Color3 and of the given one
  3768. * @param otherColor defines the second operand
  3769. * @returns the new Color3
  3770. */
  3771. Color3.prototype.add = function (otherColor) {
  3772. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  3773. };
  3774. /**
  3775. * Stores the result of the addition of the current Color3 and given one rgb values into "result"
  3776. * @param otherColor defines the second operand
  3777. * @param result defines Color3 object to store the result into
  3778. * @returns the unmodified current Color3
  3779. */
  3780. Color3.prototype.addToRef = function (otherColor, result) {
  3781. result.r = this.r + otherColor.r;
  3782. result.g = this.g + otherColor.g;
  3783. result.b = this.b + otherColor.b;
  3784. return this;
  3785. };
  3786. /**
  3787. * Returns a new Color3 set with the subtracted values of the given one from the current Color3
  3788. * @param otherColor defines the second operand
  3789. * @returns the new Color3
  3790. */
  3791. Color3.prototype.subtract = function (otherColor) {
  3792. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  3793. };
  3794. /**
  3795. * Stores the result of the subtraction of given one from the current Color3 rgb values into "result"
  3796. * @param otherColor defines the second operand
  3797. * @param result defines Color3 object to store the result into
  3798. * @returns the unmodified current Color3
  3799. */
  3800. Color3.prototype.subtractToRef = function (otherColor, result) {
  3801. result.r = this.r - otherColor.r;
  3802. result.g = this.g - otherColor.g;
  3803. result.b = this.b - otherColor.b;
  3804. return this;
  3805. };
  3806. /**
  3807. * Copy the current object
  3808. * @returns a new Color3 copied the current one
  3809. */
  3810. Color3.prototype.clone = function () {
  3811. return new Color3(this.r, this.g, this.b);
  3812. };
  3813. /**
  3814. * Copies the rgb values from the source in the current Color3
  3815. * @param source defines the source Color3 object
  3816. * @returns the updated Color3 object
  3817. */
  3818. Color3.prototype.copyFrom = function (source) {
  3819. this.r = source.r;
  3820. this.g = source.g;
  3821. this.b = source.b;
  3822. return this;
  3823. };
  3824. /**
  3825. * Updates the Color3 rgb values from the given floats
  3826. * @param r defines the red component to read from
  3827. * @param g defines the green component to read from
  3828. * @param b defines the blue component to read from
  3829. * @returns the current Color3 object
  3830. */
  3831. Color3.prototype.copyFromFloats = function (r, g, b) {
  3832. this.r = r;
  3833. this.g = g;
  3834. this.b = b;
  3835. return this;
  3836. };
  3837. /**
  3838. * Updates the Color3 rgb values from the given floats
  3839. * @param r defines the red component to read from
  3840. * @param g defines the green component to read from
  3841. * @param b defines the blue component to read from
  3842. * @returns the current Color3 object
  3843. */
  3844. Color3.prototype.set = function (r, g, b) {
  3845. return this.copyFromFloats(r, g, b);
  3846. };
  3847. /**
  3848. * Compute the Color3 hexadecimal code as a string
  3849. * @returns a string containing the hexadecimal representation of the Color3 object
  3850. */
  3851. Color3.prototype.toHexString = function () {
  3852. var intR = (this.r * 255) | 0;
  3853. var intG = (this.g * 255) | 0;
  3854. var intB = (this.b * 255) | 0;
  3855. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  3856. };
  3857. /**
  3858. * Computes a new Color3 converted from the current one to linear space
  3859. * @returns a new Color3 object
  3860. */
  3861. Color3.prototype.toLinearSpace = function () {
  3862. var convertedColor = new Color3();
  3863. this.toLinearSpaceToRef(convertedColor);
  3864. return convertedColor;
  3865. };
  3866. /**
  3867. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  3868. * @param convertedColor defines the Color3 object where to store the linear space version
  3869. * @returns the unmodified Color3
  3870. */
  3871. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  3872. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  3873. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  3874. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  3875. return this;
  3876. };
  3877. /**
  3878. * Computes a new Color3 converted from the current one to gamma space
  3879. * @returns a new Color3 object
  3880. */
  3881. Color3.prototype.toGammaSpace = function () {
  3882. var convertedColor = new Color3();
  3883. this.toGammaSpaceToRef(convertedColor);
  3884. return convertedColor;
  3885. };
  3886. /**
  3887. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  3888. * @param convertedColor defines the Color3 object where to store the gamma space version
  3889. * @returns the unmodified Color3
  3890. */
  3891. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  3892. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  3893. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  3894. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  3895. return this;
  3896. };
  3897. // Statics
  3898. /**
  3899. * Creates a new Color3 from the string containing valid hexadecimal values
  3900. * @param hex defines a string containing valid hexadecimal values
  3901. * @returns a new Color3 object
  3902. */
  3903. Color3.FromHexString = function (hex) {
  3904. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  3905. return new Color3(0, 0, 0);
  3906. }
  3907. var r = parseInt(hex.substring(1, 3), 16);
  3908. var g = parseInt(hex.substring(3, 5), 16);
  3909. var b = parseInt(hex.substring(5, 7), 16);
  3910. return Color3.FromInts(r, g, b);
  3911. };
  3912. /**
  3913. * Creates a new Vector3 from the starting index of the given array
  3914. * @param array defines the source array
  3915. * @param offset defines an offset in the source array
  3916. * @returns a new Color3 object
  3917. */
  3918. Color3.FromArray = function (array, offset) {
  3919. if (offset === void 0) { offset = 0; }
  3920. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  3921. };
  3922. /**
  3923. * Creates a new Color3 from integer values (< 256)
  3924. * @param r defines the red component to read from (value between 0 and 255)
  3925. * @param g defines the green component to read from (value between 0 and 255)
  3926. * @param b defines the blue component to read from (value between 0 and 255)
  3927. * @returns a new Color3 object
  3928. */
  3929. Color3.FromInts = function (r, g, b) {
  3930. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  3931. };
  3932. /**
  3933. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  3934. * @param start defines the start Color3 value
  3935. * @param end defines the end Color3 value
  3936. * @param amount defines the gradient value between start and end
  3937. * @returns a new Color3 object
  3938. */
  3939. Color3.Lerp = function (start, end, amount) {
  3940. var result = new Color3(0.0, 0.0, 0.0);
  3941. Color3.LerpToRef(start, end, amount, result);
  3942. return result;
  3943. };
  3944. /**
  3945. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  3946. * @param left defines the start value
  3947. * @param right defines the end value
  3948. * @param amount defines the gradient factor
  3949. * @param result defines the Color3 object where to store the result
  3950. */
  3951. Color3.LerpToRef = function (left, right, amount, result) {
  3952. result.r = left.r + ((right.r - left.r) * amount);
  3953. result.g = left.g + ((right.g - left.g) * amount);
  3954. result.b = left.b + ((right.b - left.b) * amount);
  3955. };
  3956. /**
  3957. * Returns a Color3 value containing a red color
  3958. * @returns a new Color3 object
  3959. */
  3960. Color3.Red = function () { return new Color3(1, 0, 0); };
  3961. /**
  3962. * Returns a Color3 value containing a green color
  3963. * @returns a new Color3 object
  3964. */
  3965. Color3.Green = function () { return new Color3(0, 1, 0); };
  3966. /**
  3967. * Returns a Color3 value containing a blue color
  3968. * @returns a new Color3 object
  3969. */
  3970. Color3.Blue = function () { return new Color3(0, 0, 1); };
  3971. /**
  3972. * Returns a Color3 value containing a black color
  3973. * @returns a new Color3 object
  3974. */
  3975. Color3.Black = function () { return new Color3(0, 0, 0); };
  3976. /**
  3977. * Returns a Color3 value containing a white color
  3978. * @returns a new Color3 object
  3979. */
  3980. Color3.White = function () { return new Color3(1, 1, 1); };
  3981. /**
  3982. * Returns a Color3 value containing a purple color
  3983. * @returns a new Color3 object
  3984. */
  3985. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  3986. /**
  3987. * Returns a Color3 value containing a magenta color
  3988. * @returns a new Color3 object
  3989. */
  3990. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  3991. /**
  3992. * Returns a Color3 value containing a yellow color
  3993. * @returns a new Color3 object
  3994. */
  3995. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  3996. /**
  3997. * Returns a Color3 value containing a gray color
  3998. * @returns a new Color3 object
  3999. */
  4000. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  4001. /**
  4002. * Returns a Color3 value containing a teal color
  4003. * @returns a new Color3 object
  4004. */
  4005. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  4006. /**
  4007. * Returns a Color3 value containing a random color
  4008. * @returns a new Color3 object
  4009. */
  4010. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  4011. return Color3;
  4012. }());
  4013. BABYLON.Color3 = Color3;
  4014. /**
  4015. * Class used to hold a RBGA color
  4016. */
  4017. var Color4 = /** @class */ (function () {
  4018. /**
  4019. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  4020. * @param r defines the red component (between 0 and 1, default is 0)
  4021. * @param g defines the green component (between 0 and 1, default is 0)
  4022. * @param b defines the blue component (between 0 and 1, default is 0)
  4023. * @param a defines the alpha component (between 0 and 1, default is 1)
  4024. */
  4025. function Color4(
  4026. /**
  4027. * Defines the red component (between 0 and 1, default is 0)
  4028. */
  4029. r,
  4030. /**
  4031. * Defines the green component (between 0 and 1, default is 0)
  4032. */
  4033. g,
  4034. /**
  4035. * Defines the blue component (between 0 and 1, default is 0)
  4036. */
  4037. b,
  4038. /**
  4039. * Defines the alpha component (between 0 and 1, default is 1)
  4040. */
  4041. a) {
  4042. if (r === void 0) { r = 0; }
  4043. if (g === void 0) { g = 0; }
  4044. if (b === void 0) { b = 0; }
  4045. if (a === void 0) { a = 1; }
  4046. this.r = r;
  4047. this.g = g;
  4048. this.b = b;
  4049. this.a = a;
  4050. }
  4051. // Operators
  4052. /**
  4053. * Adds in place the given Color4 values to the current Color4 object
  4054. * @param right defines the second operand
  4055. * @returns the current updated Color4 object
  4056. */
  4057. Color4.prototype.addInPlace = function (right) {
  4058. this.r += right.r;
  4059. this.g += right.g;
  4060. this.b += right.b;
  4061. this.a += right.a;
  4062. return this;
  4063. };
  4064. /**
  4065. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  4066. * @returns the new array
  4067. */
  4068. Color4.prototype.asArray = function () {
  4069. var result = new Array();
  4070. this.toArray(result, 0);
  4071. return result;
  4072. };
  4073. /**
  4074. * Stores from the starting index in the given array the Color4 successive values
  4075. * @param array defines the array where to store the r,g,b components
  4076. * @param index defines an optional index in the target array to define where to start storing values
  4077. * @returns the current Color4 object
  4078. */
  4079. Color4.prototype.toArray = function (array, index) {
  4080. if (index === void 0) { index = 0; }
  4081. array[index] = this.r;
  4082. array[index + 1] = this.g;
  4083. array[index + 2] = this.b;
  4084. array[index + 3] = this.a;
  4085. return this;
  4086. };
  4087. /**
  4088. * Creates a new Color4 set with the added values of the current Color4 and of the given one
  4089. * @param right defines the second operand
  4090. * @returns a new Color4 object
  4091. */
  4092. Color4.prototype.add = function (right) {
  4093. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  4094. };
  4095. /**
  4096. * Creates a new Color4 set with the subtracted values of the given one from the current Color4
  4097. * @param right defines the second operand
  4098. * @returns a new Color4 object
  4099. */
  4100. Color4.prototype.subtract = function (right) {
  4101. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  4102. };
  4103. /**
  4104. * Subtracts the given ones from the current Color4 values and stores the results in "result"
  4105. * @param right defines the second operand
  4106. * @param result defines the Color4 object where to store the result
  4107. * @returns the current Color4 object
  4108. */
  4109. Color4.prototype.subtractToRef = function (right, result) {
  4110. result.r = this.r - right.r;
  4111. result.g = this.g - right.g;
  4112. result.b = this.b - right.b;
  4113. result.a = this.a - right.a;
  4114. return this;
  4115. };
  4116. /**
  4117. * Creates a new Color4 with the current Color4 values multiplied by scale
  4118. * @param scale defines the scaling factor to apply
  4119. * @returns a new Color4 object
  4120. */
  4121. Color4.prototype.scale = function (scale) {
  4122. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  4123. };
  4124. /**
  4125. * Multiplies the current Color4 values by scale and stores the result in "result"
  4126. * @param scale defines the scaling factor to apply
  4127. * @param result defines the Color4 object where to store the result
  4128. * @returns the current unmodified Color4
  4129. */
  4130. Color4.prototype.scaleToRef = function (scale, result) {
  4131. result.r = this.r * scale;
  4132. result.g = this.g * scale;
  4133. result.b = this.b * scale;
  4134. result.a = this.a * scale;
  4135. return this;
  4136. };
  4137. /**
  4138. * Scale the current Color4 values by a factor and add the result to a given Color4
  4139. * @param scale defines the scale factor
  4140. * @param result defines the Color4 object where to store the result
  4141. * @returns the unmodified current Color4
  4142. */
  4143. Color4.prototype.scaleAndAddToRef = function (scale, result) {
  4144. result.r += this.r * scale;
  4145. result.g += this.g * scale;
  4146. result.b += this.b * scale;
  4147. result.a += this.a * scale;
  4148. return this;
  4149. };
  4150. /**
  4151. * Clamps the rgb values by the min and max values and stores the result into "result"
  4152. * @param min defines minimum clamping value (default is 0)
  4153. * @param max defines maximum clamping value (default is 1)
  4154. * @param result defines color to store the result into.
  4155. * @returns the cuurent Color4
  4156. */
  4157. Color4.prototype.clampToRef = function (min, max, result) {
  4158. if (min === void 0) { min = 0; }
  4159. if (max === void 0) { max = 1; }
  4160. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  4161. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  4162. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  4163. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  4164. return this;
  4165. };
  4166. /**
  4167. * Multipy an Color4 value by another and return a new Color4 object
  4168. * @param color defines the Color4 value to multiply by
  4169. * @returns a new Color4 object
  4170. */
  4171. Color4.prototype.multiply = function (color) {
  4172. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  4173. };
  4174. /**
  4175. * Multipy a Color4 value by another and push the result in a reference value
  4176. * @param color defines the Color4 value to multiply by
  4177. * @param result defines the Color4 to fill the result in
  4178. * @returns the result Color4
  4179. */
  4180. Color4.prototype.multiplyToRef = function (color, result) {
  4181. result.r = this.r * color.r;
  4182. result.g = this.g * color.g;
  4183. result.b = this.b * color.b;
  4184. result.a = this.a * color.a;
  4185. return result;
  4186. };
  4187. /**
  4188. * Creates a string with the Color4 current values
  4189. * @returns the string representation of the Color4 object
  4190. */
  4191. Color4.prototype.toString = function () {
  4192. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  4193. };
  4194. /**
  4195. * Returns the string "Color4"
  4196. * @returns "Color4"
  4197. */
  4198. Color4.prototype.getClassName = function () {
  4199. return "Color4";
  4200. };
  4201. /**
  4202. * Compute the Color4 hash code
  4203. * @returns an unique number that can be used to hash Color4 objects
  4204. */
  4205. Color4.prototype.getHashCode = function () {
  4206. var hash = this.r || 0;
  4207. hash = (hash * 397) ^ (this.g || 0);
  4208. hash = (hash * 397) ^ (this.b || 0);
  4209. hash = (hash * 397) ^ (this.a || 0);
  4210. return hash;
  4211. };
  4212. /**
  4213. * Creates a new Color4 copied from the current one
  4214. * @returns a new Color4 object
  4215. */
  4216. Color4.prototype.clone = function () {
  4217. return new Color4(this.r, this.g, this.b, this.a);
  4218. };
  4219. /**
  4220. * Copies the given Color4 values into the current one
  4221. * @param source defines the source Color4 object
  4222. * @returns the current updated Color4 object
  4223. */
  4224. Color4.prototype.copyFrom = function (source) {
  4225. this.r = source.r;
  4226. this.g = source.g;
  4227. this.b = source.b;
  4228. this.a = source.a;
  4229. return this;
  4230. };
  4231. /**
  4232. * Copies the given float values into the current one
  4233. * @param r defines the red component to read from
  4234. * @param g defines the green component to read from
  4235. * @param b defines the blue component to read from
  4236. * @param a defines the alpha component to read from
  4237. * @returns the current updated Color4 object
  4238. */
  4239. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  4240. this.r = r;
  4241. this.g = g;
  4242. this.b = b;
  4243. this.a = a;
  4244. return this;
  4245. };
  4246. /**
  4247. * Copies the given float values into the current one
  4248. * @param r defines the red component to read from
  4249. * @param g defines the green component to read from
  4250. * @param b defines the blue component to read from
  4251. * @param a defines the alpha component to read from
  4252. * @returns the current updated Color4 object
  4253. */
  4254. Color4.prototype.set = function (r, g, b, a) {
  4255. return this.copyFromFloats(r, g, b, a);
  4256. };
  4257. /**
  4258. * Compute the Color4 hexadecimal code as a string
  4259. * @returns a string containing the hexadecimal representation of the Color4 object
  4260. */
  4261. Color4.prototype.toHexString = function () {
  4262. var intR = (this.r * 255) | 0;
  4263. var intG = (this.g * 255) | 0;
  4264. var intB = (this.b * 255) | 0;
  4265. var intA = (this.a * 255) | 0;
  4266. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  4267. };
  4268. /**
  4269. * Computes a new Color4 converted from the current one to linear space
  4270. * @returns a new Color4 object
  4271. */
  4272. Color4.prototype.toLinearSpace = function () {
  4273. var convertedColor = new Color4();
  4274. this.toLinearSpaceToRef(convertedColor);
  4275. return convertedColor;
  4276. };
  4277. /**
  4278. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  4279. * @param convertedColor defines the Color4 object where to store the linear space version
  4280. * @returns the unmodified Color4
  4281. */
  4282. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  4283. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  4284. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  4285. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  4286. convertedColor.a = this.a;
  4287. return this;
  4288. };
  4289. /**
  4290. * Computes a new Color4 converted from the current one to gamma space
  4291. * @returns a new Color4 object
  4292. */
  4293. Color4.prototype.toGammaSpace = function () {
  4294. var convertedColor = new Color4();
  4295. this.toGammaSpaceToRef(convertedColor);
  4296. return convertedColor;
  4297. };
  4298. /**
  4299. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  4300. * @param convertedColor defines the Color4 object where to store the gamma space version
  4301. * @returns the unmodified Color4
  4302. */
  4303. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  4304. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  4305. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  4306. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  4307. convertedColor.a = this.a;
  4308. return this;
  4309. };
  4310. // Statics
  4311. /**
  4312. * Creates a new Color4 from the string containing valid hexadecimal values
  4313. * @param hex defines a string containing valid hexadecimal values
  4314. * @returns a new Color4 object
  4315. */
  4316. Color4.FromHexString = function (hex) {
  4317. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  4318. return new Color4(0.0, 0.0, 0.0, 0.0);
  4319. }
  4320. var r = parseInt(hex.substring(1, 3), 16);
  4321. var g = parseInt(hex.substring(3, 5), 16);
  4322. var b = parseInt(hex.substring(5, 7), 16);
  4323. var a = parseInt(hex.substring(7, 9), 16);
  4324. return Color4.FromInts(r, g, b, a);
  4325. };
  4326. /**
  4327. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  4328. * @param left defines the start value
  4329. * @param right defines the end value
  4330. * @param amount defines the gradient factor
  4331. * @returns a new Color4 object
  4332. */
  4333. Color4.Lerp = function (left, right, amount) {
  4334. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  4335. Color4.LerpToRef(left, right, amount, result);
  4336. return result;
  4337. };
  4338. /**
  4339. * Set the given "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  4340. * @param left defines the start value
  4341. * @param right defines the end value
  4342. * @param amount defines the gradient factor
  4343. * @param result defines the Color4 object where to store data
  4344. */
  4345. Color4.LerpToRef = function (left, right, amount, result) {
  4346. result.r = left.r + (right.r - left.r) * amount;
  4347. result.g = left.g + (right.g - left.g) * amount;
  4348. result.b = left.b + (right.b - left.b) * amount;
  4349. result.a = left.a + (right.a - left.a) * amount;
  4350. };
  4351. /**
  4352. * Creates a new Color4 from a Color3 and an alpha value
  4353. * @param color3 defines the source Color3 to read from
  4354. * @param alpha defines the alpha component (1.0 by default)
  4355. * @returns a new Color4 object
  4356. */
  4357. Color4.FromColor3 = function (color3, alpha) {
  4358. if (alpha === void 0) { alpha = 1.0; }
  4359. return new Color4(color3.r, color3.g, color3.b, alpha);
  4360. };
  4361. /**
  4362. * Creates a new Color4 from the starting index element of the given array
  4363. * @param array defines the source array to read from
  4364. * @param offset defines the offset in the source array
  4365. * @returns a new Color4 object
  4366. */
  4367. Color4.FromArray = function (array, offset) {
  4368. if (offset === void 0) { offset = 0; }
  4369. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4370. };
  4371. /**
  4372. * Creates a new Color3 from integer values (< 256)
  4373. * @param r defines the red component to read from (value between 0 and 255)
  4374. * @param g defines the green component to read from (value between 0 and 255)
  4375. * @param b defines the blue component to read from (value between 0 and 255)
  4376. * @param a defines the alpha component to read from (value between 0 and 255)
  4377. * @returns a new Color3 object
  4378. */
  4379. Color4.FromInts = function (r, g, b, a) {
  4380. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  4381. };
  4382. /**
  4383. * Check the content of a given array and convert it to an array containing RGBA data
  4384. * If the original array was already containing count * 4 values then it is returned directly
  4385. * @param colors defines the array to check
  4386. * @param count defines the number of RGBA data to expect
  4387. * @returns an array containing count * 4 values (RGBA)
  4388. */
  4389. Color4.CheckColors4 = function (colors, count) {
  4390. // Check if color3 was used
  4391. if (colors.length === count * 3) {
  4392. var colors4 = [];
  4393. for (var index = 0; index < colors.length; index += 3) {
  4394. var newIndex = (index / 3) * 4;
  4395. colors4[newIndex] = colors[index];
  4396. colors4[newIndex + 1] = colors[index + 1];
  4397. colors4[newIndex + 2] = colors[index + 2];
  4398. colors4[newIndex + 3] = 1.0;
  4399. }
  4400. return colors4;
  4401. }
  4402. return colors;
  4403. };
  4404. return Color4;
  4405. }());
  4406. BABYLON.Color4 = Color4;
  4407. /**
  4408. * Class representing a vector containing 2 coordinates
  4409. */
  4410. var Vector2 = /** @class */ (function () {
  4411. /**
  4412. * Creates a new Vector2 from the given x and y coordinates
  4413. * @param x defines the first coordinate
  4414. * @param y defines the second coordinate
  4415. */
  4416. function Vector2(
  4417. /** defines the first coordinate */
  4418. x,
  4419. /** defines the second coordinate */
  4420. y) {
  4421. if (x === void 0) { x = 0; }
  4422. if (y === void 0) { y = 0; }
  4423. this.x = x;
  4424. this.y = y;
  4425. }
  4426. /**
  4427. * Gets a string with the Vector2 coordinates
  4428. * @returns a string with the Vector2 coordinates
  4429. */
  4430. Vector2.prototype.toString = function () {
  4431. return "{X: " + this.x + " Y:" + this.y + "}";
  4432. };
  4433. /**
  4434. * Gets class name
  4435. * @returns the string "Vector2"
  4436. */
  4437. Vector2.prototype.getClassName = function () {
  4438. return "Vector2";
  4439. };
  4440. /**
  4441. * Gets current vector hash code
  4442. * @returns the Vector2 hash code as a number
  4443. */
  4444. Vector2.prototype.getHashCode = function () {
  4445. var hash = this.x || 0;
  4446. hash = (hash * 397) ^ (this.y || 0);
  4447. return hash;
  4448. };
  4449. // Operators
  4450. /**
  4451. * Sets the Vector2 coordinates in the given array or Float32Array from the given index.
  4452. * @param array defines the source array
  4453. * @param index defines the offset in source array
  4454. * @returns the current Vector2
  4455. */
  4456. Vector2.prototype.toArray = function (array, index) {
  4457. if (index === void 0) { index = 0; }
  4458. array[index] = this.x;
  4459. array[index + 1] = this.y;
  4460. return this;
  4461. };
  4462. /**
  4463. * Copy the current vector to an array
  4464. * @returns a new array with 2 elements: the Vector2 coordinates.
  4465. */
  4466. Vector2.prototype.asArray = function () {
  4467. var result = new Array();
  4468. this.toArray(result, 0);
  4469. return result;
  4470. };
  4471. /**
  4472. * Sets the Vector2 coordinates with the given Vector2 coordinates
  4473. * @param source defines the source Vector2
  4474. * @returns the current updated Vector2
  4475. */
  4476. Vector2.prototype.copyFrom = function (source) {
  4477. this.x = source.x;
  4478. this.y = source.y;
  4479. return this;
  4480. };
  4481. /**
  4482. * Sets the Vector2 coordinates with the given floats
  4483. * @param x defines the first coordinate
  4484. * @param y defines the second coordinate
  4485. * @returns the current updated Vector2
  4486. */
  4487. Vector2.prototype.copyFromFloats = function (x, y) {
  4488. this.x = x;
  4489. this.y = y;
  4490. return this;
  4491. };
  4492. /**
  4493. * Sets the Vector2 coordinates with the given floats
  4494. * @param x defines the first coordinate
  4495. * @param y defines the second coordinate
  4496. * @returns the current updated Vector2
  4497. */
  4498. Vector2.prototype.set = function (x, y) {
  4499. return this.copyFromFloats(x, y);
  4500. };
  4501. /**
  4502. * Add another vector with the current one
  4503. * @param otherVector defines the other vector
  4504. * @returns a new Vector2 set with the addition of the current Vector2 and the given one coordinates
  4505. */
  4506. Vector2.prototype.add = function (otherVector) {
  4507. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  4508. };
  4509. /**
  4510. * Sets the "result" coordinates with the addition of the current Vector2 and the given one coordinates
  4511. * @param otherVector defines the other vector
  4512. * @param result defines the target vector
  4513. * @returns the unmodified current Vector2
  4514. */
  4515. Vector2.prototype.addToRef = function (otherVector, result) {
  4516. result.x = this.x + otherVector.x;
  4517. result.y = this.y + otherVector.y;
  4518. return this;
  4519. };
  4520. /**
  4521. * Set the Vector2 coordinates by adding the given Vector2 coordinates
  4522. * @param otherVector defines the other vector
  4523. * @returns the current updated Vector2
  4524. */
  4525. Vector2.prototype.addInPlace = function (otherVector) {
  4526. this.x += otherVector.x;
  4527. this.y += otherVector.y;
  4528. return this;
  4529. };
  4530. /**
  4531. * Gets a new Vector2 by adding the current Vector2 coordinates to the given Vector3 x, y coordinates
  4532. * @param otherVector defines the other vector
  4533. * @returns a new Vector2
  4534. */
  4535. Vector2.prototype.addVector3 = function (otherVector) {
  4536. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  4537. };
  4538. /**
  4539. * Gets a new Vector2 set with the subtracted coordinates of the given one from the current Vector2
  4540. * @param otherVector defines the other vector
  4541. * @returns a new Vector2
  4542. */
  4543. Vector2.prototype.subtract = function (otherVector) {
  4544. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  4545. };
  4546. /**
  4547. * Sets the "result" coordinates with the subtraction of the given one from the current Vector2 coordinates.
  4548. * @param otherVector defines the other vector
  4549. * @param result defines the target vector
  4550. * @returns the unmodified current Vector2
  4551. */
  4552. Vector2.prototype.subtractToRef = function (otherVector, result) {
  4553. result.x = this.x - otherVector.x;
  4554. result.y = this.y - otherVector.y;
  4555. return this;
  4556. };
  4557. /**
  4558. * Sets the current Vector2 coordinates by subtracting from it the given one coordinates
  4559. * @param otherVector defines the other vector
  4560. * @returns the current updated Vector2
  4561. */
  4562. Vector2.prototype.subtractInPlace = function (otherVector) {
  4563. this.x -= otherVector.x;
  4564. this.y -= otherVector.y;
  4565. return this;
  4566. };
  4567. /**
  4568. * Multiplies in place the current Vector2 coordinates by the given ones
  4569. * @param otherVector defines the other vector
  4570. * @returns the current updated Vector2
  4571. */
  4572. Vector2.prototype.multiplyInPlace = function (otherVector) {
  4573. this.x *= otherVector.x;
  4574. this.y *= otherVector.y;
  4575. return this;
  4576. };
  4577. /**
  4578. * Returns a new Vector2 set with the multiplication of the current Vector2 and the given one coordinates
  4579. * @param otherVector defines the other vector
  4580. * @returns a new Vector2
  4581. */
  4582. Vector2.prototype.multiply = function (otherVector) {
  4583. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  4584. };
  4585. /**
  4586. * Sets "result" coordinates with the multiplication of the current Vector2 and the given one coordinates
  4587. * @param otherVector defines the other vector
  4588. * @param result defines the target vector
  4589. * @returns the unmodified current Vector2
  4590. */
  4591. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  4592. result.x = this.x * otherVector.x;
  4593. result.y = this.y * otherVector.y;
  4594. return this;
  4595. };
  4596. /**
  4597. * Gets a new Vector2 set with the Vector2 coordinates multiplied by the given floats
  4598. * @param x defines the first coordinate
  4599. * @param y defines the second coordinate
  4600. * @returns a new Vector2
  4601. */
  4602. Vector2.prototype.multiplyByFloats = function (x, y) {
  4603. return new Vector2(this.x * x, this.y * y);
  4604. };
  4605. /**
  4606. * Returns a new Vector2 set with the Vector2 coordinates divided by the given one coordinates
  4607. * @param otherVector defines the other vector
  4608. * @returns a new Vector2
  4609. */
  4610. Vector2.prototype.divide = function (otherVector) {
  4611. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  4612. };
  4613. /**
  4614. * Sets the "result" coordinates with the Vector2 divided by the given one coordinates
  4615. * @param otherVector defines the other vector
  4616. * @param result defines the target vector
  4617. * @returns the unmodified current Vector2
  4618. */
  4619. Vector2.prototype.divideToRef = function (otherVector, result) {
  4620. result.x = this.x / otherVector.x;
  4621. result.y = this.y / otherVector.y;
  4622. return this;
  4623. };
  4624. /**
  4625. * Divides the current Vector2 coordinates by the given ones
  4626. * @param otherVector defines the other vector
  4627. * @returns the current updated Vector2
  4628. */
  4629. Vector2.prototype.divideInPlace = function (otherVector) {
  4630. return this.divideToRef(otherVector, this);
  4631. };
  4632. /**
  4633. * Gets a new Vector2 with current Vector2 negated coordinates
  4634. * @returns a new Vector2
  4635. */
  4636. Vector2.prototype.negate = function () {
  4637. return new Vector2(-this.x, -this.y);
  4638. };
  4639. /**
  4640. * Multiply the Vector2 coordinates by scale
  4641. * @param scale defines the scaling factor
  4642. * @returns the current updated Vector2
  4643. */
  4644. Vector2.prototype.scaleInPlace = function (scale) {
  4645. this.x *= scale;
  4646. this.y *= scale;
  4647. return this;
  4648. };
  4649. /**
  4650. * Returns a new Vector2 scaled by "scale" from the current Vector2
  4651. * @param scale defines the scaling factor
  4652. * @returns a new Vector2
  4653. */
  4654. Vector2.prototype.scale = function (scale) {
  4655. var result = new Vector2(0, 0);
  4656. this.scaleToRef(scale, result);
  4657. return result;
  4658. };
  4659. /**
  4660. * Scale the current Vector2 values by a factor to a given Vector2
  4661. * @param scale defines the scale factor
  4662. * @param result defines the Vector2 object where to store the result
  4663. * @returns the unmodified current Vector2
  4664. */
  4665. Vector2.prototype.scaleToRef = function (scale, result) {
  4666. result.x = this.x * scale;
  4667. result.y = this.y * scale;
  4668. return this;
  4669. };
  4670. /**
  4671. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  4672. * @param scale defines the scale factor
  4673. * @param result defines the Vector2 object where to store the result
  4674. * @returns the unmodified current Vector2
  4675. */
  4676. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  4677. result.x += this.x * scale;
  4678. result.y += this.y * scale;
  4679. return this;
  4680. };
  4681. /**
  4682. * Gets a boolean if two vectors are equals
  4683. * @param otherVector defines the other vector
  4684. * @returns true if the given vector coordinates strictly equal the current Vector2 ones
  4685. */
  4686. Vector2.prototype.equals = function (otherVector) {
  4687. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  4688. };
  4689. /**
  4690. * Gets a boolean if two vectors are equals (using an epsilon value)
  4691. * @param otherVector defines the other vector
  4692. * @param epsilon defines the minimal distance to consider equality
  4693. * @returns true if the given vector coordinates are close to the current ones by a distance of epsilon.
  4694. */
  4695. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  4696. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  4697. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  4698. };
  4699. /**
  4700. * Gets a new Vector2 from current Vector2 floored values
  4701. * @returns a new Vector2
  4702. */
  4703. Vector2.prototype.floor = function () {
  4704. return new Vector2(Math.floor(this.x), Math.floor(this.y));
  4705. };
  4706. /**
  4707. * Gets a new Vector2 from current Vector2 floored values
  4708. * @returns a new Vector2
  4709. */
  4710. Vector2.prototype.fract = function () {
  4711. return new Vector2(this.x - Math.floor(this.x), this.y - Math.floor(this.y));
  4712. };
  4713. // Properties
  4714. /**
  4715. * Gets the length of the vector
  4716. * @returns the vector length (float)
  4717. */
  4718. Vector2.prototype.length = function () {
  4719. return Math.sqrt(this.x * this.x + this.y * this.y);
  4720. };
  4721. /**
  4722. * Gets the vector squared length
  4723. * @returns the vector squared length (float)
  4724. */
  4725. Vector2.prototype.lengthSquared = function () {
  4726. return (this.x * this.x + this.y * this.y);
  4727. };
  4728. // Methods
  4729. /**
  4730. * Normalize the vector
  4731. * @returns the current updated Vector2
  4732. */
  4733. Vector2.prototype.normalize = function () {
  4734. var len = this.length();
  4735. if (len === 0) {
  4736. return this;
  4737. }
  4738. var num = 1.0 / len;
  4739. this.x *= num;
  4740. this.y *= num;
  4741. return this;
  4742. };
  4743. /**
  4744. * Gets a new Vector2 copied from the Vector2
  4745. * @returns a new Vector2
  4746. */
  4747. Vector2.prototype.clone = function () {
  4748. return new Vector2(this.x, this.y);
  4749. };
  4750. // Statics
  4751. /**
  4752. * Gets a new Vector2(0, 0)
  4753. * @returns a new Vector2
  4754. */
  4755. Vector2.Zero = function () {
  4756. return new Vector2(0, 0);
  4757. };
  4758. /**
  4759. * Gets a new Vector2(1, 1)
  4760. * @returns a new Vector2
  4761. */
  4762. Vector2.One = function () {
  4763. return new Vector2(1, 1);
  4764. };
  4765. /**
  4766. * Gets a new Vector2 set from the given index element of the given array
  4767. * @param array defines the data source
  4768. * @param offset defines the offset in the data source
  4769. * @returns a new Vector2
  4770. */
  4771. Vector2.FromArray = function (array, offset) {
  4772. if (offset === void 0) { offset = 0; }
  4773. return new Vector2(array[offset], array[offset + 1]);
  4774. };
  4775. /**
  4776. * Sets "result" from the given index element of the given array
  4777. * @param array defines the data source
  4778. * @param offset defines the offset in the data source
  4779. * @param result defines the target vector
  4780. */
  4781. Vector2.FromArrayToRef = function (array, offset, result) {
  4782. result.x = array[offset];
  4783. result.y = array[offset + 1];
  4784. };
  4785. /**
  4786. * Gets a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the given four Vector2
  4787. * @param value1 defines 1st point of control
  4788. * @param value2 defines 2nd point of control
  4789. * @param value3 defines 3rd point of control
  4790. * @param value4 defines 4th point of control
  4791. * @param amount defines the interpolation factor
  4792. * @returns a new Vector2
  4793. */
  4794. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  4795. var squared = amount * amount;
  4796. var cubed = amount * squared;
  4797. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  4798. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  4799. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  4800. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  4801. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  4802. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  4803. return new Vector2(x, y);
  4804. };
  4805. /**
  4806. * 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".
  4807. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  4808. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate
  4809. * @param value defines the value to clamp
  4810. * @param min defines the lower limit
  4811. * @param max defines the upper limit
  4812. * @returns a new Vector2
  4813. */
  4814. Vector2.Clamp = function (value, min, max) {
  4815. var x = value.x;
  4816. x = (x > max.x) ? max.x : x;
  4817. x = (x < min.x) ? min.x : x;
  4818. var y = value.y;
  4819. y = (y > max.y) ? max.y : y;
  4820. y = (y < min.y) ? min.y : y;
  4821. return new Vector2(x, y);
  4822. };
  4823. /**
  4824. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2"
  4825. * @param value1 defines the 1st control point
  4826. * @param tangent1 defines the outgoing tangent
  4827. * @param value2 defines the 2nd control point
  4828. * @param tangent2 defines the incoming tangent
  4829. * @param amount defines the interpolation factor
  4830. * @returns a new Vector2
  4831. */
  4832. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  4833. var squared = amount * amount;
  4834. var cubed = amount * squared;
  4835. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  4836. var part2 = (-2.0 * cubed) + (3.0 * squared);
  4837. var part3 = (cubed - (2.0 * squared)) + amount;
  4838. var part4 = cubed - squared;
  4839. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  4840. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  4841. return new Vector2(x, y);
  4842. };
  4843. /**
  4844. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  4845. * @param start defines the start vector
  4846. * @param end defines the end vector
  4847. * @param amount defines the interpolation factor
  4848. * @returns a new Vector2
  4849. */
  4850. Vector2.Lerp = function (start, end, amount) {
  4851. var x = start.x + ((end.x - start.x) * amount);
  4852. var y = start.y + ((end.y - start.y) * amount);
  4853. return new Vector2(x, y);
  4854. };
  4855. /**
  4856. * Gets the dot product of the vector "left" and the vector "right"
  4857. * @param left defines first vector
  4858. * @param right defines second vector
  4859. * @returns the dot product (float)
  4860. */
  4861. Vector2.Dot = function (left, right) {
  4862. return left.x * right.x + left.y * right.y;
  4863. };
  4864. /**
  4865. * Returns a new Vector2 equal to the normalized given vector
  4866. * @param vector defines the vector to normalize
  4867. * @returns a new Vector2
  4868. */
  4869. Vector2.Normalize = function (vector) {
  4870. var newVector = vector.clone();
  4871. newVector.normalize();
  4872. return newVector;
  4873. };
  4874. /**
  4875. * Gets a new Vector2 set with the minimal coordinate values from the "left" and "right" vectors
  4876. * @param left defines 1st vector
  4877. * @param right defines 2nd vector
  4878. * @returns a new Vector2
  4879. */
  4880. Vector2.Minimize = function (left, right) {
  4881. var x = (left.x < right.x) ? left.x : right.x;
  4882. var y = (left.y < right.y) ? left.y : right.y;
  4883. return new Vector2(x, y);
  4884. };
  4885. /**
  4886. * Gets a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors
  4887. * @param left defines 1st vector
  4888. * @param right defines 2nd vector
  4889. * @returns a new Vector2
  4890. */
  4891. Vector2.Maximize = function (left, right) {
  4892. var x = (left.x > right.x) ? left.x : right.x;
  4893. var y = (left.y > right.y) ? left.y : right.y;
  4894. return new Vector2(x, y);
  4895. };
  4896. /**
  4897. * Gets a new Vector2 set with the transformed coordinates of the given vector by the given transformation matrix
  4898. * @param vector defines the vector to transform
  4899. * @param transformation defines the matrix to apply
  4900. * @returns a new Vector2
  4901. */
  4902. Vector2.Transform = function (vector, transformation) {
  4903. var r = Vector2.Zero();
  4904. Vector2.TransformToRef(vector, transformation, r);
  4905. return r;
  4906. };
  4907. /**
  4908. * Transforms the given vector coordinates by the given transformation matrix and stores the result in the vector "result" coordinates
  4909. * @param vector defines the vector to transform
  4910. * @param transformation defines the matrix to apply
  4911. * @param result defines the target vector
  4912. */
  4913. Vector2.TransformToRef = function (vector, transformation, result) {
  4914. var m = transformation.m;
  4915. var x = (vector.x * m[0]) + (vector.y * m[4]) + m[12];
  4916. var y = (vector.x * m[1]) + (vector.y * m[5]) + m[13];
  4917. result.x = x;
  4918. result.y = y;
  4919. };
  4920. /**
  4921. * Determines if a given vector is included in a triangle
  4922. * @param p defines the vector to test
  4923. * @param p0 defines 1st triangle point
  4924. * @param p1 defines 2nd triangle point
  4925. * @param p2 defines 3rd triangle point
  4926. * @returns true if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  4927. */
  4928. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  4929. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  4930. var sign = a < 0 ? -1 : 1;
  4931. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  4932. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  4933. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  4934. };
  4935. /**
  4936. * Gets the distance between the vectors "value1" and "value2"
  4937. * @param value1 defines first vector
  4938. * @param value2 defines second vector
  4939. * @returns the distance between vectors
  4940. */
  4941. Vector2.Distance = function (value1, value2) {
  4942. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  4943. };
  4944. /**
  4945. * Returns the squared distance between the vectors "value1" and "value2"
  4946. * @param value1 defines first vector
  4947. * @param value2 defines second vector
  4948. * @returns the squared distance between vectors
  4949. */
  4950. Vector2.DistanceSquared = function (value1, value2) {
  4951. var x = value1.x - value2.x;
  4952. var y = value1.y - value2.y;
  4953. return (x * x) + (y * y);
  4954. };
  4955. /**
  4956. * Gets a new Vector2 located at the center of the vectors "value1" and "value2"
  4957. * @param value1 defines first vector
  4958. * @param value2 defines second vector
  4959. * @returns a new Vector2
  4960. */
  4961. Vector2.Center = function (value1, value2) {
  4962. var center = value1.add(value2);
  4963. center.scaleInPlace(0.5);
  4964. return center;
  4965. };
  4966. /**
  4967. * Gets the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  4968. * @param p defines the middle point
  4969. * @param segA defines one point of the segment
  4970. * @param segB defines the other point of the segment
  4971. * @returns the shortest distance
  4972. */
  4973. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  4974. var l2 = Vector2.DistanceSquared(segA, segB);
  4975. if (l2 === 0.0) {
  4976. return Vector2.Distance(p, segA);
  4977. }
  4978. var v = segB.subtract(segA);
  4979. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  4980. var proj = segA.add(v.multiplyByFloats(t, t));
  4981. return Vector2.Distance(p, proj);
  4982. };
  4983. return Vector2;
  4984. }());
  4985. BABYLON.Vector2 = Vector2;
  4986. /**
  4987. * Classed used to store (x,y,z) vector representation
  4988. * A Vector3 is the main object used in 3D geometry
  4989. * It can represent etiher the coordinates of a point the space, either a direction
  4990. * Reminder: Babylon.js uses a left handed forward facing system
  4991. */
  4992. var Vector3 = /** @class */ (function () {
  4993. /**
  4994. * Creates a new Vector3 object from the given x, y, z (floats) coordinates.
  4995. * @param x defines the first coordinates (on X axis)
  4996. * @param y defines the second coordinates (on Y axis)
  4997. * @param z defines the third coordinates (on Z axis)
  4998. */
  4999. function Vector3(
  5000. /**
  5001. * Defines the first coordinates (on X axis)
  5002. */
  5003. x,
  5004. /**
  5005. * Defines the second coordinates (on Y axis)
  5006. */
  5007. y,
  5008. /**
  5009. * Defines the third coordinates (on Z axis)
  5010. */
  5011. z) {
  5012. if (x === void 0) { x = 0; }
  5013. if (y === void 0) { y = 0; }
  5014. if (z === void 0) { z = 0; }
  5015. this.x = x;
  5016. this.y = y;
  5017. this.z = z;
  5018. }
  5019. /**
  5020. * Creates a string representation of the Vector3
  5021. * @returns a string with the Vector3 coordinates.
  5022. */
  5023. Vector3.prototype.toString = function () {
  5024. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  5025. };
  5026. /**
  5027. * Gets the class name
  5028. * @returns the string "Vector3"
  5029. */
  5030. Vector3.prototype.getClassName = function () {
  5031. return "Vector3";
  5032. };
  5033. /**
  5034. * Creates the Vector3 hash code
  5035. * @returns a number which tends to be unique between Vector3 instances
  5036. */
  5037. Vector3.prototype.getHashCode = function () {
  5038. var hash = this.x || 0;
  5039. hash = (hash * 397) ^ (this.y || 0);
  5040. hash = (hash * 397) ^ (this.z || 0);
  5041. return hash;
  5042. };
  5043. // Operators
  5044. /**
  5045. * Creates an array containing three elements : the coordinates of the Vector3
  5046. * @returns a new array of numbers
  5047. */
  5048. Vector3.prototype.asArray = function () {
  5049. var result = [];
  5050. this.toArray(result, 0);
  5051. return result;
  5052. };
  5053. /**
  5054. * Populates the given array or Float32Array from the given index with the successive coordinates of the Vector3
  5055. * @param array defines the destination array
  5056. * @param index defines the offset in the destination array
  5057. * @returns the current Vector3
  5058. */
  5059. Vector3.prototype.toArray = function (array, index) {
  5060. if (index === void 0) { index = 0; }
  5061. array[index] = this.x;
  5062. array[index + 1] = this.y;
  5063. array[index + 2] = this.z;
  5064. return this;
  5065. };
  5066. /**
  5067. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  5068. * @returns a new Quaternion object, computed from the Vector3 coordinates
  5069. */
  5070. Vector3.prototype.toQuaternion = function () {
  5071. return BABYLON.Quaternion.RotationYawPitchRoll(this.y, this.x, this.z);
  5072. };
  5073. /**
  5074. * Adds the given vector to the current Vector3
  5075. * @param otherVector defines the second operand
  5076. * @returns the current updated Vector3
  5077. */
  5078. Vector3.prototype.addInPlace = function (otherVector) {
  5079. return this.addInPlaceFromFloats(otherVector.x, otherVector.y, otherVector.z);
  5080. };
  5081. /**
  5082. * Adds the given coordinates to the current Vector3
  5083. * @param x defines the x coordinate of the operand
  5084. * @param y defines the y coordinate of the operand
  5085. * @param z defines the z coordinate of the operand
  5086. * @returns the current updated Vector3
  5087. */
  5088. Vector3.prototype.addInPlaceFromFloats = function (x, y, z) {
  5089. this.x += x;
  5090. this.y += y;
  5091. this.z += z;
  5092. return this;
  5093. };
  5094. /**
  5095. * Gets a new Vector3, result of the addition the current Vector3 and the given vector
  5096. * @param otherVector defines the second operand
  5097. * @returns the resulting Vector3
  5098. */
  5099. Vector3.prototype.add = function (otherVector) {
  5100. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  5101. };
  5102. /**
  5103. * Adds the current Vector3 to the given one and stores the result in the vector "result"
  5104. * @param otherVector defines the second operand
  5105. * @param result defines the Vector3 object where to store the result
  5106. * @returns the current Vector3
  5107. */
  5108. Vector3.prototype.addToRef = function (otherVector, result) {
  5109. return result.copyFromFloats(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  5110. };
  5111. /**
  5112. * Subtract the given vector from the current Vector3
  5113. * @param otherVector defines the second operand
  5114. * @returns the current updated Vector3
  5115. */
  5116. Vector3.prototype.subtractInPlace = function (otherVector) {
  5117. this.x -= otherVector.x;
  5118. this.y -= otherVector.y;
  5119. this.z -= otherVector.z;
  5120. return this;
  5121. };
  5122. /**
  5123. * Returns a new Vector3, result of the subtraction of the given vector from the current Vector3
  5124. * @param otherVector defines the second operand
  5125. * @returns the resulting Vector3
  5126. */
  5127. Vector3.prototype.subtract = function (otherVector) {
  5128. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  5129. };
  5130. /**
  5131. * Subtracts the given vector from the current Vector3 and stores the result in the vector "result".
  5132. * @param otherVector defines the second operand
  5133. * @param result defines the Vector3 object where to store the result
  5134. * @returns the current Vector3
  5135. */
  5136. Vector3.prototype.subtractToRef = function (otherVector, result) {
  5137. return this.subtractFromFloatsToRef(otherVector.x, otherVector.y, otherVector.z, result);
  5138. };
  5139. /**
  5140. * Returns a new Vector3 set with the subtraction of the given floats from the current Vector3 coordinates
  5141. * @param x defines the x coordinate of the operand
  5142. * @param y defines the y coordinate of the operand
  5143. * @param z defines the z coordinate of the operand
  5144. * @returns the resulting Vector3
  5145. */
  5146. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  5147. return new Vector3(this.x - x, this.y - y, this.z - z);
  5148. };
  5149. /**
  5150. * Subtracts the given floats from the current Vector3 coordinates and set the given vector "result" with this result
  5151. * @param x defines the x coordinate of the operand
  5152. * @param y defines the y coordinate of the operand
  5153. * @param z defines the z coordinate of the operand
  5154. * @param result defines the Vector3 object where to store the result
  5155. * @returns the current Vector3
  5156. */
  5157. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  5158. return result.copyFromFloats(this.x - x, this.y - y, this.z - z);
  5159. };
  5160. /**
  5161. * Gets a new Vector3 set with the current Vector3 negated coordinates
  5162. * @returns a new Vector3
  5163. */
  5164. Vector3.prototype.negate = function () {
  5165. return new Vector3(-this.x, -this.y, -this.z);
  5166. };
  5167. /**
  5168. * Multiplies the Vector3 coordinates by the float "scale"
  5169. * @param scale defines the multiplier factor
  5170. * @returns the current updated Vector3
  5171. */
  5172. Vector3.prototype.scaleInPlace = function (scale) {
  5173. this.x *= scale;
  5174. this.y *= scale;
  5175. this.z *= scale;
  5176. return this;
  5177. };
  5178. /**
  5179. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  5180. * @param scale defines the multiplier factor
  5181. * @returns a new Vector3
  5182. */
  5183. Vector3.prototype.scale = function (scale) {
  5184. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  5185. };
  5186. /**
  5187. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the given vector "result" coordinates
  5188. * @param scale defines the multiplier factor
  5189. * @param result defines the Vector3 object where to store the result
  5190. * @returns the current Vector3
  5191. */
  5192. Vector3.prototype.scaleToRef = function (scale, result) {
  5193. return result.copyFromFloats(this.x * scale, this.y * scale, this.z * scale);
  5194. };
  5195. /**
  5196. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  5197. * @param scale defines the scale factor
  5198. * @param result defines the Vector3 object where to store the result
  5199. * @returns the unmodified current Vector3
  5200. */
  5201. Vector3.prototype.scaleAndAddToRef = function (scale, result) {
  5202. return result.addInPlaceFromFloats(this.x * scale, this.y * scale, this.z * scale);
  5203. };
  5204. /**
  5205. * Returns true if the current Vector3 and the given vector coordinates are strictly equal
  5206. * @param otherVector defines the second operand
  5207. * @returns true if both vectors are equals
  5208. */
  5209. Vector3.prototype.equals = function (otherVector) {
  5210. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  5211. };
  5212. /**
  5213. * Returns true if the current Vector3 and the given vector coordinates are distant less than epsilon
  5214. * @param otherVector defines the second operand
  5215. * @param epsilon defines the minimal distance to define values as equals
  5216. * @returns true if both vectors are distant less than epsilon
  5217. */
  5218. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  5219. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  5220. 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);
  5221. };
  5222. /**
  5223. * Returns true if the current Vector3 coordinates equals the given floats
  5224. * @param x defines the x coordinate of the operand
  5225. * @param y defines the y coordinate of the operand
  5226. * @param z defines the z coordinate of the operand
  5227. * @returns true if both vectors are equals
  5228. */
  5229. Vector3.prototype.equalsToFloats = function (x, y, z) {
  5230. return this.x === x && this.y === y && this.z === z;
  5231. };
  5232. /**
  5233. * Multiplies the current Vector3 coordinates by the given ones
  5234. * @param otherVector defines the second operand
  5235. * @returns the current updated Vector3
  5236. */
  5237. Vector3.prototype.multiplyInPlace = function (otherVector) {
  5238. this.x *= otherVector.x;
  5239. this.y *= otherVector.y;
  5240. this.z *= otherVector.z;
  5241. return this;
  5242. };
  5243. /**
  5244. * Returns a new Vector3, result of the multiplication of the current Vector3 by the given vector
  5245. * @param otherVector defines the second operand
  5246. * @returns the new Vector3
  5247. */
  5248. Vector3.prototype.multiply = function (otherVector) {
  5249. return this.multiplyByFloats(otherVector.x, otherVector.y, otherVector.z);
  5250. };
  5251. /**
  5252. * Multiplies the current Vector3 by the given one and stores the result in the given vector "result"
  5253. * @param otherVector defines the second operand
  5254. * @param result defines the Vector3 object where to store the result
  5255. * @returns the current Vector3
  5256. */
  5257. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  5258. return result.copyFromFloats(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  5259. };
  5260. /**
  5261. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the given floats
  5262. * @param x defines the x coordinate of the operand
  5263. * @param y defines the y coordinate of the operand
  5264. * @param z defines the z coordinate of the operand
  5265. * @returns the new Vector3
  5266. */
  5267. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  5268. return new Vector3(this.x * x, this.y * y, this.z * z);
  5269. };
  5270. /**
  5271. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the given ones
  5272. * @param otherVector defines the second operand
  5273. * @returns the new Vector3
  5274. */
  5275. Vector3.prototype.divide = function (otherVector) {
  5276. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  5277. };
  5278. /**
  5279. * Divides the current Vector3 coordinates by the given ones and stores the result in the given vector "result"
  5280. * @param otherVector defines the second operand
  5281. * @param result defines the Vector3 object where to store the result
  5282. * @returns the current Vector3
  5283. */
  5284. Vector3.prototype.divideToRef = function (otherVector, result) {
  5285. return result.copyFromFloats(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  5286. };
  5287. /**
  5288. * Divides the current Vector3 coordinates by the given ones.
  5289. * @param otherVector defines the second operand
  5290. * @returns the current updated Vector3
  5291. */
  5292. Vector3.prototype.divideInPlace = function (otherVector) {
  5293. return this.divideToRef(otherVector, this);
  5294. };
  5295. /**
  5296. * Updates the current Vector3 with the minimal coordinate values between its and the given vector ones
  5297. * @param other defines the second operand
  5298. * @returns the current updated Vector3
  5299. */
  5300. Vector3.prototype.minimizeInPlace = function (other) {
  5301. return this.minimizeInPlaceFromFloats(other.x, other.y, other.z);
  5302. };
  5303. /**
  5304. * Updates the current Vector3 with the maximal coordinate values between its and the given vector ones.
  5305. * @param other defines the second operand
  5306. * @returns the current updated Vector3
  5307. */
  5308. Vector3.prototype.maximizeInPlace = function (other) {
  5309. return this.maximizeInPlaceFromFloats(other.x, other.y, other.z);
  5310. };
  5311. /**
  5312. * Updates the current Vector3 with the minimal coordinate values between its and the given coordinates
  5313. * @param x defines the x coordinate of the operand
  5314. * @param y defines the y coordinate of the operand
  5315. * @param z defines the z coordinate of the operand
  5316. * @returns the current updated Vector3
  5317. */
  5318. Vector3.prototype.minimizeInPlaceFromFloats = function (x, y, z) {
  5319. if (x < this.x) {
  5320. this.x = x;
  5321. }
  5322. if (y < this.y) {
  5323. this.y = y;
  5324. }
  5325. if (z < this.z) {
  5326. this.z = z;
  5327. }
  5328. return this;
  5329. };
  5330. /**
  5331. * Updates the current Vector3 with the maximal coordinate values between its and the given coordinates.
  5332. * @param x defines the x coordinate of the operand
  5333. * @param y defines the y coordinate of the operand
  5334. * @param z defines the z coordinate of the operand
  5335. * @returns the current updated Vector3
  5336. */
  5337. Vector3.prototype.maximizeInPlaceFromFloats = function (x, y, z) {
  5338. if (x > this.x) {
  5339. this.x = x;
  5340. }
  5341. if (y > this.y) {
  5342. this.y = y;
  5343. }
  5344. if (z > this.z) {
  5345. this.z = z;
  5346. }
  5347. return this;
  5348. };
  5349. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  5350. /**
  5351. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  5352. */
  5353. get: function () {
  5354. var absX = Math.abs(this.x);
  5355. var absY = Math.abs(this.y);
  5356. if (absX !== absY) {
  5357. return true;
  5358. }
  5359. var absZ = Math.abs(this.z);
  5360. if (absX !== absZ) {
  5361. return true;
  5362. }
  5363. if (absY !== absZ) {
  5364. return true;
  5365. }
  5366. return false;
  5367. },
  5368. enumerable: true,
  5369. configurable: true
  5370. });
  5371. /**
  5372. * Gets a new Vector3 from current Vector3 floored values
  5373. * @returns a new Vector3
  5374. */
  5375. Vector3.prototype.floor = function () {
  5376. return new Vector3(Math.floor(this.x), Math.floor(this.y), Math.floor(this.z));
  5377. };
  5378. /**
  5379. * Gets a new Vector3 from current Vector3 floored values
  5380. * @returns a new Vector3
  5381. */
  5382. Vector3.prototype.fract = function () {
  5383. return new Vector3(this.x - Math.floor(this.x), this.y - Math.floor(this.y), this.z - Math.floor(this.z));
  5384. };
  5385. // Properties
  5386. /**
  5387. * Gets the length of the Vector3
  5388. * @returns the length of the Vecto3
  5389. */
  5390. Vector3.prototype.length = function () {
  5391. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  5392. };
  5393. /**
  5394. * Gets the squared length of the Vector3
  5395. * @returns squared length of the Vector3
  5396. */
  5397. Vector3.prototype.lengthSquared = function () {
  5398. return (this.x * this.x + this.y * this.y + this.z * this.z);
  5399. };
  5400. /**
  5401. * Normalize the current Vector3.
  5402. * Please note that this is an in place operation.
  5403. * @returns the current updated Vector3
  5404. */
  5405. Vector3.prototype.normalize = function () {
  5406. return this.normalizeFromLength(this.length());
  5407. };
  5408. /**
  5409. * Reorders the x y z properties of the vector in place
  5410. * @param order new ordering of the properties (eg. for vector 1,2,3 with "ZYX" will produce 3,2,1)
  5411. * @returns the current updated vector
  5412. */
  5413. Vector3.prototype.reorderInPlace = function (order) {
  5414. var _this = this;
  5415. order = order.toLowerCase();
  5416. if (order === "xyz") {
  5417. return this;
  5418. }
  5419. MathTmp.Vector3[0].copyFrom(this);
  5420. ["x", "y", "z"].forEach(function (val, i) {
  5421. _this[val] = MathTmp.Vector3[0][order[i]];
  5422. });
  5423. return this;
  5424. };
  5425. /**
  5426. * Rotates the vector around 0,0,0 by a quaternion
  5427. * @param quaternion the rotation quaternion
  5428. * @param result vector to store the result
  5429. * @returns the resulting vector
  5430. */
  5431. Vector3.prototype.rotateByQuaternionToRef = function (quaternion, result) {
  5432. quaternion.toRotationMatrix(MathTmp.Matrix[0]);
  5433. Vector3.TransformCoordinatesToRef(this, MathTmp.Matrix[0], result);
  5434. return result;
  5435. };
  5436. /**
  5437. * Rotates a vector around a given point
  5438. * @param quaternion the rotation quaternion
  5439. * @param point the point to rotate around
  5440. * @param result vector to store the result
  5441. * @returns the resulting vector
  5442. */
  5443. Vector3.prototype.rotateByQuaternionAroundPointToRef = function (quaternion, point, result) {
  5444. this.subtractToRef(point, MathTmp.Vector3[0]);
  5445. MathTmp.Vector3[0].rotateByQuaternionToRef(quaternion, MathTmp.Vector3[0]);
  5446. point.addToRef(MathTmp.Vector3[0], result);
  5447. return result;
  5448. };
  5449. /**
  5450. * Normalize the current Vector3 with the given input length.
  5451. * Please note that this is an in place operation.
  5452. * @param len the length of the vector
  5453. * @returns the current updated Vector3
  5454. */
  5455. Vector3.prototype.normalizeFromLength = function (len) {
  5456. if (len === 0 || len === 1.0) {
  5457. return this;
  5458. }
  5459. return this.scaleInPlace(1.0 / len);
  5460. };
  5461. /**
  5462. * Normalize the current Vector3 to a new vector
  5463. * @returns the new Vector3
  5464. */
  5465. Vector3.prototype.normalizeToNew = function () {
  5466. var normalized = new Vector3(0, 0, 0);
  5467. this.normalizeToRef(normalized);
  5468. return normalized;
  5469. };
  5470. /**
  5471. * Normalize the current Vector3 to the reference
  5472. * @param reference define the Vector3 to update
  5473. * @returns the updated Vector3
  5474. */
  5475. Vector3.prototype.normalizeToRef = function (reference) {
  5476. var len = this.length();
  5477. if (len === 0 || len === 1.0) {
  5478. return reference.copyFromFloats(this.x, this.y, this.z);
  5479. }
  5480. return this.scaleToRef(1.0 / len, reference);
  5481. };
  5482. /**
  5483. * Creates a new Vector3 copied from the current Vector3
  5484. * @returns the new Vector3
  5485. */
  5486. Vector3.prototype.clone = function () {
  5487. return new Vector3(this.x, this.y, this.z);
  5488. };
  5489. /**
  5490. * Copies the given vector coordinates to the current Vector3 ones
  5491. * @param source defines the source Vector3
  5492. * @returns the current updated Vector3
  5493. */
  5494. Vector3.prototype.copyFrom = function (source) {
  5495. return this.copyFromFloats(source.x, source.y, source.z);
  5496. };
  5497. /**
  5498. * Copies the given floats to the current Vector3 coordinates
  5499. * @param x defines the x coordinate of the operand
  5500. * @param y defines the y coordinate of the operand
  5501. * @param z defines the z coordinate of the operand
  5502. * @returns the current updated Vector3
  5503. */
  5504. Vector3.prototype.copyFromFloats = function (x, y, z) {
  5505. this.x = x;
  5506. this.y = y;
  5507. this.z = z;
  5508. return this;
  5509. };
  5510. /**
  5511. * Copies the given floats to the current Vector3 coordinates
  5512. * @param x defines the x coordinate of the operand
  5513. * @param y defines the y coordinate of the operand
  5514. * @param z defines the z coordinate of the operand
  5515. * @returns the current updated Vector3
  5516. */
  5517. Vector3.prototype.set = function (x, y, z) {
  5518. return this.copyFromFloats(x, y, z);
  5519. };
  5520. /**
  5521. * Copies the given float to the current Vector3 coordinates
  5522. * @param v defines the x, y and z coordinates of the operand
  5523. * @returns the current updated Vector3
  5524. */
  5525. Vector3.prototype.setAll = function (v) {
  5526. this.x = this.y = this.z = v;
  5527. return this;
  5528. };
  5529. // Statics
  5530. /**
  5531. * Get the clip factor between two vectors
  5532. * @param vector0 defines the first operand
  5533. * @param vector1 defines the second operand
  5534. * @param axis defines the axis to use
  5535. * @param size defines the size along the axis
  5536. * @returns the clip factor
  5537. */
  5538. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  5539. var d0 = Vector3.Dot(vector0, axis) - size;
  5540. var d1 = Vector3.Dot(vector1, axis) - size;
  5541. var s = d0 / (d0 - d1);
  5542. return s;
  5543. };
  5544. /**
  5545. * Get angle between two vectors
  5546. * @param vector0 angle between vector0 and vector1
  5547. * @param vector1 angle between vector0 and vector1
  5548. * @param normal direction of the normal
  5549. * @return the angle between vector0 and vector1
  5550. */
  5551. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  5552. var v0 = vector0.normalizeToRef(MathTmp.Vector3[1]);
  5553. var v1 = vector1.normalizeToRef(MathTmp.Vector3[2]);
  5554. var dot = Vector3.Dot(v0, v1);
  5555. var n = MathTmp.Vector3[3];
  5556. Vector3.CrossToRef(v0, v1, n);
  5557. if (Vector3.Dot(n, normal) > 0) {
  5558. return Math.acos(dot);
  5559. }
  5560. return -Math.acos(dot);
  5561. };
  5562. /**
  5563. * Returns a new Vector3 set from the index "offset" of the given array
  5564. * @param array defines the source array
  5565. * @param offset defines the offset in the source array
  5566. * @returns the new Vector3
  5567. */
  5568. Vector3.FromArray = function (array, offset) {
  5569. if (offset === void 0) { offset = 0; }
  5570. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  5571. };
  5572. /**
  5573. * Returns a new Vector3 set from the index "offset" of the given Float32Array
  5574. * This function is deprecated. Use FromArray instead
  5575. * @param array defines the source array
  5576. * @param offset defines the offset in the source array
  5577. * @returns the new Vector3
  5578. */
  5579. Vector3.FromFloatArray = function (array, offset) {
  5580. return Vector3.FromArray(array, offset);
  5581. };
  5582. /**
  5583. * Sets the given vector "result" with the element values from the index "offset" of the given array
  5584. * @param array defines the source array
  5585. * @param offset defines the offset in the source array
  5586. * @param result defines the Vector3 where to store the result
  5587. */
  5588. Vector3.FromArrayToRef = function (array, offset, result) {
  5589. result.x = array[offset];
  5590. result.y = array[offset + 1];
  5591. result.z = array[offset + 2];
  5592. };
  5593. /**
  5594. * Sets the given vector "result" with the element values from the index "offset" of the given Float32Array
  5595. * This function is deprecated. Use FromArrayToRef instead.
  5596. * @param array defines the source array
  5597. * @param offset defines the offset in the source array
  5598. * @param result defines the Vector3 where to store the result
  5599. */
  5600. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  5601. return Vector3.FromArrayToRef(array, offset, result);
  5602. };
  5603. /**
  5604. * Sets the given vector "result" with the given floats.
  5605. * @param x defines the x coordinate of the source
  5606. * @param y defines the y coordinate of the source
  5607. * @param z defines the z coordinate of the source
  5608. * @param result defines the Vector3 where to store the result
  5609. */
  5610. Vector3.FromFloatsToRef = function (x, y, z, result) {
  5611. result.copyFromFloats(x, y, z);
  5612. };
  5613. /**
  5614. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  5615. * @returns a new empty Vector3
  5616. */
  5617. Vector3.Zero = function () {
  5618. return new Vector3(0.0, 0.0, 0.0);
  5619. };
  5620. /**
  5621. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  5622. * @returns a new unit Vector3
  5623. */
  5624. Vector3.One = function () {
  5625. return new Vector3(1.0, 1.0, 1.0);
  5626. };
  5627. /**
  5628. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  5629. * @returns a new up Vector3
  5630. */
  5631. Vector3.Up = function () {
  5632. return new Vector3(0.0, 1.0, 0.0);
  5633. };
  5634. /**
  5635. * Returns a new Vector3 set to (0.0, -1.0, 0.0)
  5636. * @returns a new down Vector3
  5637. */
  5638. Vector3.Down = function () {
  5639. return new Vector3(0.0, -1.0, 0.0);
  5640. };
  5641. /**
  5642. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  5643. * @returns a new forward Vector3
  5644. */
  5645. Vector3.Forward = function () {
  5646. return new Vector3(0.0, 0.0, 1.0);
  5647. };
  5648. /**
  5649. * Returns a new Vector3 set to (0.0, 0.0, -1.0)
  5650. * @returns a new forward Vector3
  5651. */
  5652. Vector3.Backward = function () {
  5653. return new Vector3(0.0, 0.0, -1.0);
  5654. };
  5655. /**
  5656. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  5657. * @returns a new right Vector3
  5658. */
  5659. Vector3.Right = function () {
  5660. return new Vector3(1.0, 0.0, 0.0);
  5661. };
  5662. /**
  5663. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  5664. * @returns a new left Vector3
  5665. */
  5666. Vector3.Left = function () {
  5667. return new Vector3(-1.0, 0.0, 0.0);
  5668. };
  5669. /**
  5670. * Returns a new Vector3 set with the result of the transformation by the given matrix of the given vector.
  5671. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  5672. * @param vector defines the Vector3 to transform
  5673. * @param transformation defines the transformation matrix
  5674. * @returns the transformed Vector3
  5675. */
  5676. Vector3.TransformCoordinates = function (vector, transformation) {
  5677. var result = Vector3.Zero();
  5678. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  5679. return result;
  5680. };
  5681. /**
  5682. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given vector
  5683. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  5684. * @param vector defines the Vector3 to transform
  5685. * @param transformation defines the transformation matrix
  5686. * @param result defines the Vector3 where to store the result
  5687. */
  5688. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  5689. Vector3.TransformCoordinatesFromFloatsToRef(vector.x, vector.y, vector.z, transformation, result);
  5690. };
  5691. /**
  5692. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given floats (x, y, z)
  5693. * This method computes tranformed coordinates only, not transformed direction vectors
  5694. * @param x define the x coordinate of the source vector
  5695. * @param y define the y coordinate of the source vector
  5696. * @param z define the z coordinate of the source vector
  5697. * @param transformation defines the transformation matrix
  5698. * @param result defines the Vector3 where to store the result
  5699. */
  5700. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  5701. var m = transformation.m;
  5702. var rx = x * m[0] + y * m[4] + z * m[8] + m[12];
  5703. var ry = x * m[1] + y * m[5] + z * m[9] + m[13];
  5704. var rz = x * m[2] + y * m[6] + z * m[10] + m[14];
  5705. var rw = 1 / (x * m[3] + y * m[7] + z * m[11] + m[15]);
  5706. result.x = rx * rw;
  5707. result.y = ry * rw;
  5708. result.z = rz * rw;
  5709. };
  5710. /**
  5711. * Returns a new Vector3 set with the result of the normal transformation by the given matrix of the given vector
  5712. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  5713. * @param vector defines the Vector3 to transform
  5714. * @param transformation defines the transformation matrix
  5715. * @returns the new Vector3
  5716. */
  5717. Vector3.TransformNormal = function (vector, transformation) {
  5718. var result = Vector3.Zero();
  5719. Vector3.TransformNormalToRef(vector, transformation, result);
  5720. return result;
  5721. };
  5722. /**
  5723. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector
  5724. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  5725. * @param vector defines the Vector3 to transform
  5726. * @param transformation defines the transformation matrix
  5727. * @param result defines the Vector3 where to store the result
  5728. */
  5729. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  5730. this.TransformNormalFromFloatsToRef(vector.x, vector.y, vector.z, transformation, result);
  5731. };
  5732. /**
  5733. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z)
  5734. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  5735. * @param x define the x coordinate of the source vector
  5736. * @param y define the y coordinate of the source vector
  5737. * @param z define the z coordinate of the source vector
  5738. * @param transformation defines the transformation matrix
  5739. * @param result defines the Vector3 where to store the result
  5740. */
  5741. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  5742. var m = transformation.m;
  5743. result.x = x * m[0] + y * m[4] + z * m[8];
  5744. result.y = x * m[1] + y * m[5] + z * m[9];
  5745. result.z = x * m[2] + y * m[6] + z * m[10];
  5746. };
  5747. /**
  5748. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  5749. * @param value1 defines the first control point
  5750. * @param value2 defines the second control point
  5751. * @param value3 defines the third control point
  5752. * @param value4 defines the fourth control point
  5753. * @param amount defines the amount on the spline to use
  5754. * @returns the new Vector3
  5755. */
  5756. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  5757. var squared = amount * amount;
  5758. var cubed = amount * squared;
  5759. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  5760. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  5761. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  5762. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  5763. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  5764. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  5765. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  5766. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  5767. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  5768. return new Vector3(x, y, z);
  5769. };
  5770. /**
  5771. * 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"
  5772. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  5773. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  5774. * @param value defines the current value
  5775. * @param min defines the lower range value
  5776. * @param max defines the upper range value
  5777. * @returns the new Vector3
  5778. */
  5779. Vector3.Clamp = function (value, min, max) {
  5780. var v = new Vector3();
  5781. Vector3.ClampToRef(value, min, max, v);
  5782. return v;
  5783. };
  5784. /**
  5785. * Sets the given vector "result" with the coordinates of "value", if the vector "value" is in the cube defined by the vectors "min" and "max"
  5786. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  5787. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  5788. * @param value defines the current value
  5789. * @param min defines the lower range value
  5790. * @param max defines the upper range value
  5791. * @param result defines the Vector3 where to store the result
  5792. */
  5793. Vector3.ClampToRef = function (value, min, max, result) {
  5794. var x = value.x;
  5795. x = (x > max.x) ? max.x : x;
  5796. x = (x < min.x) ? min.x : x;
  5797. var y = value.y;
  5798. y = (y > max.y) ? max.y : y;
  5799. y = (y < min.y) ? min.y : y;
  5800. var z = value.z;
  5801. z = (z > max.z) ? max.z : z;
  5802. z = (z < min.z) ? min.z : z;
  5803. result.copyFromFloats(x, y, z);
  5804. };
  5805. /**
  5806. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  5807. * @param value1 defines the first control point
  5808. * @param tangent1 defines the first tangent vector
  5809. * @param value2 defines the second control point
  5810. * @param tangent2 defines the second tangent vector
  5811. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  5812. * @returns the new Vector3
  5813. */
  5814. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  5815. var squared = amount * amount;
  5816. var cubed = amount * squared;
  5817. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  5818. var part2 = (-2.0 * cubed) + (3.0 * squared);
  5819. var part3 = (cubed - (2.0 * squared)) + amount;
  5820. var part4 = cubed - squared;
  5821. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  5822. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  5823. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  5824. return new Vector3(x, y, z);
  5825. };
  5826. /**
  5827. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  5828. * @param start defines the start value
  5829. * @param end defines the end value
  5830. * @param amount max defines amount between both (between 0 and 1)
  5831. * @returns the new Vector3
  5832. */
  5833. Vector3.Lerp = function (start, end, amount) {
  5834. var result = new Vector3(0, 0, 0);
  5835. Vector3.LerpToRef(start, end, amount, result);
  5836. return result;
  5837. };
  5838. /**
  5839. * Sets the given vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  5840. * @param start defines the start value
  5841. * @param end defines the end value
  5842. * @param amount max defines amount between both (between 0 and 1)
  5843. * @param result defines the Vector3 where to store the result
  5844. */
  5845. Vector3.LerpToRef = function (start, end, amount, result) {
  5846. result.x = start.x + ((end.x - start.x) * amount);
  5847. result.y = start.y + ((end.y - start.y) * amount);
  5848. result.z = start.z + ((end.z - start.z) * amount);
  5849. };
  5850. /**
  5851. * Returns the dot product (float) between the vectors "left" and "right"
  5852. * @param left defines the left operand
  5853. * @param right defines the right operand
  5854. * @returns the dot product
  5855. */
  5856. Vector3.Dot = function (left, right) {
  5857. return (left.x * right.x + left.y * right.y + left.z * right.z);
  5858. };
  5859. /**
  5860. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  5861. * The cross product is then orthogonal to both "left" and "right"
  5862. * @param left defines the left operand
  5863. * @param right defines the right operand
  5864. * @returns the cross product
  5865. */
  5866. Vector3.Cross = function (left, right) {
  5867. var result = Vector3.Zero();
  5868. Vector3.CrossToRef(left, right, result);
  5869. return result;
  5870. };
  5871. /**
  5872. * Sets the given vector "result" with the cross product of "left" and "right"
  5873. * The cross product is then orthogonal to both "left" and "right"
  5874. * @param left defines the left operand
  5875. * @param right defines the right operand
  5876. * @param result defines the Vector3 where to store the result
  5877. */
  5878. Vector3.CrossToRef = function (left, right, result) {
  5879. var x = left.y * right.z - left.z * right.y;
  5880. var y = left.z * right.x - left.x * right.z;
  5881. var z = left.x * right.y - left.y * right.x;
  5882. result.copyFromFloats(x, y, z);
  5883. };
  5884. /**
  5885. * Returns a new Vector3 as the normalization of the given vector
  5886. * @param vector defines the Vector3 to normalize
  5887. * @returns the new Vector3
  5888. */
  5889. Vector3.Normalize = function (vector) {
  5890. var result = Vector3.Zero();
  5891. Vector3.NormalizeToRef(vector, result);
  5892. return result;
  5893. };
  5894. /**
  5895. * Sets the given vector "result" with the normalization of the given first vector
  5896. * @param vector defines the Vector3 to normalize
  5897. * @param result defines the Vector3 where to store the result
  5898. */
  5899. Vector3.NormalizeToRef = function (vector, result) {
  5900. vector.normalizeToRef(result);
  5901. };
  5902. /**
  5903. * Project a Vector3 onto screen space
  5904. * @param vector defines the Vector3 to project
  5905. * @param world defines the world matrix to use
  5906. * @param transform defines the transform (view x projection) matrix to use
  5907. * @param viewport defines the screen viewport to use
  5908. * @returns the new Vector3
  5909. */
  5910. Vector3.Project = function (vector, world, transform, viewport) {
  5911. var cw = viewport.width;
  5912. var ch = viewport.height;
  5913. var cx = viewport.x;
  5914. var cy = viewport.y;
  5915. var viewportMatrix = MathTmp.Matrix[1];
  5916. 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);
  5917. var matrix = MathTmp.Matrix[0];
  5918. world.multiplyToRef(transform, matrix);
  5919. matrix.multiplyToRef(viewportMatrix, matrix);
  5920. return Vector3.TransformCoordinates(vector, matrix);
  5921. };
  5922. /** @hidden */
  5923. Vector3.UnprojectFromInvertedMatrixToRef = function (source, matrix, result) {
  5924. Vector3.TransformCoordinatesToRef(source, matrix, result);
  5925. var m = matrix.m;
  5926. var num = source.x * m[3] + source.y * m[7] + source.z * m[11] + m[15];
  5927. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  5928. result.scaleInPlace(1.0 / num);
  5929. }
  5930. };
  5931. /**
  5932. * Unproject from screen space to object space
  5933. * @param source defines the screen space Vector3 to use
  5934. * @param viewportWidth defines the current width of the viewport
  5935. * @param viewportHeight defines the current height of the viewport
  5936. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  5937. * @param transform defines the transform (view x projection) matrix to use
  5938. * @returns the new Vector3
  5939. */
  5940. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  5941. var matrix = MathTmp.Matrix[0];
  5942. world.multiplyToRef(transform, matrix);
  5943. matrix.invert();
  5944. source.x = source.x / viewportWidth * 2 - 1;
  5945. source.y = -(source.y / viewportHeight * 2 - 1);
  5946. var vector = new Vector3();
  5947. Vector3.UnprojectFromInvertedMatrixToRef(source, matrix, vector);
  5948. return vector;
  5949. };
  5950. /**
  5951. * Unproject from screen space to object space
  5952. * @param source defines the screen space Vector3 to use
  5953. * @param viewportWidth defines the current width of the viewport
  5954. * @param viewportHeight defines the current height of the viewport
  5955. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  5956. * @param view defines the view matrix to use
  5957. * @param projection defines the projection matrix to use
  5958. * @returns the new Vector3
  5959. */
  5960. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  5961. var result = Vector3.Zero();
  5962. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  5963. return result;
  5964. };
  5965. /**
  5966. * Unproject from screen space to object space
  5967. * @param source defines the screen space Vector3 to use
  5968. * @param viewportWidth defines the current width of the viewport
  5969. * @param viewportHeight defines the current height of the viewport
  5970. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  5971. * @param view defines the view matrix to use
  5972. * @param projection defines the projection matrix to use
  5973. * @param result defines the Vector3 where to store the result
  5974. */
  5975. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  5976. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  5977. };
  5978. /**
  5979. * Unproject from screen space to object space
  5980. * @param sourceX defines the screen space x coordinate to use
  5981. * @param sourceY defines the screen space y coordinate to use
  5982. * @param sourceZ defines the screen space z coordinate to use
  5983. * @param viewportWidth defines the current width of the viewport
  5984. * @param viewportHeight defines the current height of the viewport
  5985. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  5986. * @param view defines the view matrix to use
  5987. * @param projection defines the projection matrix to use
  5988. * @param result defines the Vector3 where to store the result
  5989. */
  5990. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  5991. var matrix = MathTmp.Matrix[0];
  5992. world.multiplyToRef(view, matrix);
  5993. matrix.multiplyToRef(projection, matrix);
  5994. matrix.invert();
  5995. var screenSource = MathTmp.Vector3[0];
  5996. screenSource.x = sourceX / viewportWidth * 2 - 1;
  5997. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  5998. screenSource.z = 2 * sourceZ - 1.0;
  5999. Vector3.UnprojectFromInvertedMatrixToRef(screenSource, matrix, result);
  6000. };
  6001. /**
  6002. * Unproject a ray from screen space to object space
  6003. * @param sourceX defines the screen space x coordinate to use
  6004. * @param sourceY defines the screen space y coordinate to use
  6005. * @param viewportWidth defines the current width of the viewport
  6006. * @param viewportHeight defines the current height of the viewport
  6007. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  6008. * @param view defines the view matrix to use
  6009. * @param projection defines the projection matrix to use
  6010. * @param ray defines the Ray where to store the result
  6011. */
  6012. Vector3.UnprojectRayToRef = function (sourceX, sourceY, viewportWidth, viewportHeight, world, view, projection, ray) {
  6013. var matrix = MathTmp.Matrix[0];
  6014. world.multiplyToRef(view, matrix);
  6015. matrix.multiplyToRef(projection, matrix);
  6016. matrix.invert();
  6017. var nearScreenSource = MathTmp.Vector3[0];
  6018. nearScreenSource.x = sourceX / viewportWidth * 2 - 1;
  6019. nearScreenSource.y = -(sourceY / viewportHeight * 2 - 1);
  6020. nearScreenSource.z = -1.0;
  6021. var farScreenSource = MathTmp.Vector3[1].copyFromFloats(nearScreenSource.x, nearScreenSource.y, 1.0);
  6022. var nearVec3 = MathTmp.Vector3[2];
  6023. var farVec3 = MathTmp.Vector3[3];
  6024. Vector3.UnprojectFromInvertedMatrixToRef(nearScreenSource, matrix, nearVec3);
  6025. Vector3.UnprojectFromInvertedMatrixToRef(farScreenSource, matrix, farVec3);
  6026. ray.origin.copyFrom(nearVec3);
  6027. farVec3.subtractToRef(nearVec3, ray.direction);
  6028. ray.direction.normalize();
  6029. };
  6030. /**
  6031. * Gets the minimal coordinate values between two Vector3
  6032. * @param left defines the first operand
  6033. * @param right defines the second operand
  6034. * @returns the new Vector3
  6035. */
  6036. Vector3.Minimize = function (left, right) {
  6037. var min = left.clone();
  6038. min.minimizeInPlace(right);
  6039. return min;
  6040. };
  6041. /**
  6042. * Gets the maximal coordinate values between two Vector3
  6043. * @param left defines the first operand
  6044. * @param right defines the second operand
  6045. * @returns the new Vector3
  6046. */
  6047. Vector3.Maximize = function (left, right) {
  6048. var max = left.clone();
  6049. max.maximizeInPlace(right);
  6050. return max;
  6051. };
  6052. /**
  6053. * Returns the distance between the vectors "value1" and "value2"
  6054. * @param value1 defines the first operand
  6055. * @param value2 defines the second operand
  6056. * @returns the distance
  6057. */
  6058. Vector3.Distance = function (value1, value2) {
  6059. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  6060. };
  6061. /**
  6062. * Returns the squared distance between the vectors "value1" and "value2"
  6063. * @param value1 defines the first operand
  6064. * @param value2 defines the second operand
  6065. * @returns the squared distance
  6066. */
  6067. Vector3.DistanceSquared = function (value1, value2) {
  6068. var x = value1.x - value2.x;
  6069. var y = value1.y - value2.y;
  6070. var z = value1.z - value2.z;
  6071. return (x * x) + (y * y) + (z * z);
  6072. };
  6073. /**
  6074. * Returns a new Vector3 located at the center between "value1" and "value2"
  6075. * @param value1 defines the first operand
  6076. * @param value2 defines the second operand
  6077. * @returns the new Vector3
  6078. */
  6079. Vector3.Center = function (value1, value2) {
  6080. var center = value1.add(value2);
  6081. center.scaleInPlace(0.5);
  6082. return center;
  6083. };
  6084. /**
  6085. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  6086. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  6087. * to something in order to rotate it from its local system to the given target system
  6088. * Note: axis1, axis2 and axis3 are normalized during this operation
  6089. * @param axis1 defines the first axis
  6090. * @param axis2 defines the second axis
  6091. * @param axis3 defines the third axis
  6092. * @returns a new Vector3
  6093. */
  6094. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  6095. var rotation = Vector3.Zero();
  6096. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  6097. return rotation;
  6098. };
  6099. /**
  6100. * The same than RotationFromAxis but updates the given ref Vector3 parameter instead of returning a new Vector3
  6101. * @param axis1 defines the first axis
  6102. * @param axis2 defines the second axis
  6103. * @param axis3 defines the third axis
  6104. * @param ref defines the Vector3 where to store the result
  6105. */
  6106. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  6107. var quat = MathTmp.Quaternion[0];
  6108. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  6109. quat.toEulerAnglesToRef(ref);
  6110. };
  6111. return Vector3;
  6112. }());
  6113. BABYLON.Vector3 = Vector3;
  6114. /**
  6115. * Vector4 class created for EulerAngle class conversion to Quaternion
  6116. */
  6117. var Vector4 = /** @class */ (function () {
  6118. /**
  6119. * Creates a Vector4 object from the given floats.
  6120. * @param x x value of the vector
  6121. * @param y y value of the vector
  6122. * @param z z value of the vector
  6123. * @param w w value of the vector
  6124. */
  6125. function Vector4(
  6126. /** x value of the vector */
  6127. x,
  6128. /** y value of the vector */
  6129. y,
  6130. /** z value of the vector */
  6131. z,
  6132. /** w value of the vector */
  6133. w) {
  6134. this.x = x;
  6135. this.y = y;
  6136. this.z = z;
  6137. this.w = w;
  6138. }
  6139. /**
  6140. * Returns the string with the Vector4 coordinates.
  6141. * @returns a string containing all the vector values
  6142. */
  6143. Vector4.prototype.toString = function () {
  6144. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  6145. };
  6146. /**
  6147. * Returns the string "Vector4".
  6148. * @returns "Vector4"
  6149. */
  6150. Vector4.prototype.getClassName = function () {
  6151. return "Vector4";
  6152. };
  6153. /**
  6154. * Returns the Vector4 hash code.
  6155. * @returns a unique hash code
  6156. */
  6157. Vector4.prototype.getHashCode = function () {
  6158. var hash = this.x || 0;
  6159. hash = (hash * 397) ^ (this.y || 0);
  6160. hash = (hash * 397) ^ (this.z || 0);
  6161. hash = (hash * 397) ^ (this.w || 0);
  6162. return hash;
  6163. };
  6164. // Operators
  6165. /**
  6166. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  6167. * @returns the resulting array
  6168. */
  6169. Vector4.prototype.asArray = function () {
  6170. var result = new Array();
  6171. this.toArray(result, 0);
  6172. return result;
  6173. };
  6174. /**
  6175. * Populates the given array from the given index with the Vector4 coordinates.
  6176. * @param array array to populate
  6177. * @param index index of the array to start at (default: 0)
  6178. * @returns the Vector4.
  6179. */
  6180. Vector4.prototype.toArray = function (array, index) {
  6181. if (index === undefined) {
  6182. index = 0;
  6183. }
  6184. array[index] = this.x;
  6185. array[index + 1] = this.y;
  6186. array[index + 2] = this.z;
  6187. array[index + 3] = this.w;
  6188. return this;
  6189. };
  6190. /**
  6191. * Adds the given vector to the current Vector4.
  6192. * @param otherVector the vector to add
  6193. * @returns the updated Vector4.
  6194. */
  6195. Vector4.prototype.addInPlace = function (otherVector) {
  6196. this.x += otherVector.x;
  6197. this.y += otherVector.y;
  6198. this.z += otherVector.z;
  6199. this.w += otherVector.w;
  6200. return this;
  6201. };
  6202. /**
  6203. * Returns a new Vector4 as the result of the addition of the current Vector4 and the given one.
  6204. * @param otherVector the vector to add
  6205. * @returns the resulting vector
  6206. */
  6207. Vector4.prototype.add = function (otherVector) {
  6208. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  6209. };
  6210. /**
  6211. * Updates the given vector "result" with the result of the addition of the current Vector4 and the given one.
  6212. * @param otherVector the vector to add
  6213. * @param result the vector to store the result
  6214. * @returns the current Vector4.
  6215. */
  6216. Vector4.prototype.addToRef = function (otherVector, result) {
  6217. result.x = this.x + otherVector.x;
  6218. result.y = this.y + otherVector.y;
  6219. result.z = this.z + otherVector.z;
  6220. result.w = this.w + otherVector.w;
  6221. return this;
  6222. };
  6223. /**
  6224. * Subtract in place the given vector from the current Vector4.
  6225. * @param otherVector the vector to subtract
  6226. * @returns the updated Vector4.
  6227. */
  6228. Vector4.prototype.subtractInPlace = function (otherVector) {
  6229. this.x -= otherVector.x;
  6230. this.y -= otherVector.y;
  6231. this.z -= otherVector.z;
  6232. this.w -= otherVector.w;
  6233. return this;
  6234. };
  6235. /**
  6236. * Returns a new Vector4 with the result of the subtraction of the given vector from the current Vector4.
  6237. * @param otherVector the vector to add
  6238. * @returns the new vector with the result
  6239. */
  6240. Vector4.prototype.subtract = function (otherVector) {
  6241. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  6242. };
  6243. /**
  6244. * Sets the given vector "result" with the result of the subtraction of the given vector from the current Vector4.
  6245. * @param otherVector the vector to subtract
  6246. * @param result the vector to store the result
  6247. * @returns the current Vector4.
  6248. */
  6249. Vector4.prototype.subtractToRef = function (otherVector, result) {
  6250. result.x = this.x - otherVector.x;
  6251. result.y = this.y - otherVector.y;
  6252. result.z = this.z - otherVector.z;
  6253. result.w = this.w - otherVector.w;
  6254. return this;
  6255. };
  6256. /**
  6257. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  6258. */
  6259. /**
  6260. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  6261. * @param x value to subtract
  6262. * @param y value to subtract
  6263. * @param z value to subtract
  6264. * @param w value to subtract
  6265. * @returns new vector containing the result
  6266. */
  6267. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  6268. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  6269. };
  6270. /**
  6271. * Sets the given vector "result" set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  6272. * @param x value to subtract
  6273. * @param y value to subtract
  6274. * @param z value to subtract
  6275. * @param w value to subtract
  6276. * @param result the vector to store the result in
  6277. * @returns the current Vector4.
  6278. */
  6279. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  6280. result.x = this.x - x;
  6281. result.y = this.y - y;
  6282. result.z = this.z - z;
  6283. result.w = this.w - w;
  6284. return this;
  6285. };
  6286. /**
  6287. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  6288. * @returns a new vector with the negated values
  6289. */
  6290. Vector4.prototype.negate = function () {
  6291. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  6292. };
  6293. /**
  6294. * Multiplies the current Vector4 coordinates by scale (float).
  6295. * @param scale the number to scale with
  6296. * @returns the updated Vector4.
  6297. */
  6298. Vector4.prototype.scaleInPlace = function (scale) {
  6299. this.x *= scale;
  6300. this.y *= scale;
  6301. this.z *= scale;
  6302. this.w *= scale;
  6303. return this;
  6304. };
  6305. /**
  6306. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  6307. * @param scale the number to scale with
  6308. * @returns a new vector with the result
  6309. */
  6310. Vector4.prototype.scale = function (scale) {
  6311. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  6312. };
  6313. /**
  6314. * Sets the given vector "result" with the current Vector4 coordinates multiplied by scale (float).
  6315. * @param scale the number to scale with
  6316. * @param result a vector to store the result in
  6317. * @returns the current Vector4.
  6318. */
  6319. Vector4.prototype.scaleToRef = function (scale, result) {
  6320. result.x = this.x * scale;
  6321. result.y = this.y * scale;
  6322. result.z = this.z * scale;
  6323. result.w = this.w * scale;
  6324. return this;
  6325. };
  6326. /**
  6327. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  6328. * @param scale defines the scale factor
  6329. * @param result defines the Vector4 object where to store the result
  6330. * @returns the unmodified current Vector4
  6331. */
  6332. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  6333. result.x += this.x * scale;
  6334. result.y += this.y * scale;
  6335. result.z += this.z * scale;
  6336. result.w += this.w * scale;
  6337. return this;
  6338. };
  6339. /**
  6340. * Boolean : True if the current Vector4 coordinates are stricly equal to the given ones.
  6341. * @param otherVector the vector to compare against
  6342. * @returns true if they are equal
  6343. */
  6344. Vector4.prototype.equals = function (otherVector) {
  6345. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  6346. };
  6347. /**
  6348. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the given vector ones.
  6349. * @param otherVector vector to compare against
  6350. * @param epsilon (Default: very small number)
  6351. * @returns true if they are equal
  6352. */
  6353. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  6354. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  6355. return otherVector
  6356. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  6357. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  6358. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  6359. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  6360. };
  6361. /**
  6362. * Boolean : True if the given floats are strictly equal to the current Vector4 coordinates.
  6363. * @param x x value to compare against
  6364. * @param y y value to compare against
  6365. * @param z z value to compare against
  6366. * @param w w value to compare against
  6367. * @returns true if equal
  6368. */
  6369. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  6370. return this.x === x && this.y === y && this.z === z && this.w === w;
  6371. };
  6372. /**
  6373. * Multiplies in place the current Vector4 by the given one.
  6374. * @param otherVector vector to multiple with
  6375. * @returns the updated Vector4.
  6376. */
  6377. Vector4.prototype.multiplyInPlace = function (otherVector) {
  6378. this.x *= otherVector.x;
  6379. this.y *= otherVector.y;
  6380. this.z *= otherVector.z;
  6381. this.w *= otherVector.w;
  6382. return this;
  6383. };
  6384. /**
  6385. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the given one.
  6386. * @param otherVector vector to multiple with
  6387. * @returns resulting new vector
  6388. */
  6389. Vector4.prototype.multiply = function (otherVector) {
  6390. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  6391. };
  6392. /**
  6393. * Updates the given vector "result" with the multiplication result of the current Vector4 and the given one.
  6394. * @param otherVector vector to multiple with
  6395. * @param result vector to store the result
  6396. * @returns the current Vector4.
  6397. */
  6398. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  6399. result.x = this.x * otherVector.x;
  6400. result.y = this.y * otherVector.y;
  6401. result.z = this.z * otherVector.z;
  6402. result.w = this.w * otherVector.w;
  6403. return this;
  6404. };
  6405. /**
  6406. * Returns a new Vector4 set with the multiplication result of the given floats and the current Vector4 coordinates.
  6407. * @param x x value multiply with
  6408. * @param y y value multiply with
  6409. * @param z z value multiply with
  6410. * @param w w value multiply with
  6411. * @returns resulting new vector
  6412. */
  6413. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  6414. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  6415. };
  6416. /**
  6417. * Returns a new Vector4 set with the division result of the current Vector4 by the given one.
  6418. * @param otherVector vector to devide with
  6419. * @returns resulting new vector
  6420. */
  6421. Vector4.prototype.divide = function (otherVector) {
  6422. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  6423. };
  6424. /**
  6425. * Updates the given vector "result" with the division result of the current Vector4 by the given one.
  6426. * @param otherVector vector to devide with
  6427. * @param result vector to store the result
  6428. * @returns the current Vector4.
  6429. */
  6430. Vector4.prototype.divideToRef = function (otherVector, result) {
  6431. result.x = this.x / otherVector.x;
  6432. result.y = this.y / otherVector.y;
  6433. result.z = this.z / otherVector.z;
  6434. result.w = this.w / otherVector.w;
  6435. return this;
  6436. };
  6437. /**
  6438. * Divides the current Vector3 coordinates by the given ones.
  6439. * @param otherVector vector to devide with
  6440. * @returns the updated Vector3.
  6441. */
  6442. Vector4.prototype.divideInPlace = function (otherVector) {
  6443. return this.divideToRef(otherVector, this);
  6444. };
  6445. /**
  6446. * Updates the Vector4 coordinates with the minimum values between its own and the given vector ones
  6447. * @param other defines the second operand
  6448. * @returns the current updated Vector4
  6449. */
  6450. Vector4.prototype.minimizeInPlace = function (other) {
  6451. if (other.x < this.x) {
  6452. this.x = other.x;
  6453. }
  6454. if (other.y < this.y) {
  6455. this.y = other.y;
  6456. }
  6457. if (other.z < this.z) {
  6458. this.z = other.z;
  6459. }
  6460. if (other.w < this.w) {
  6461. this.w = other.w;
  6462. }
  6463. return this;
  6464. };
  6465. /**
  6466. * Updates the Vector4 coordinates with the maximum values between its own and the given vector ones
  6467. * @param other defines the second operand
  6468. * @returns the current updated Vector4
  6469. */
  6470. Vector4.prototype.maximizeInPlace = function (other) {
  6471. if (other.x > this.x) {
  6472. this.x = other.x;
  6473. }
  6474. if (other.y > this.y) {
  6475. this.y = other.y;
  6476. }
  6477. if (other.z > this.z) {
  6478. this.z = other.z;
  6479. }
  6480. if (other.w > this.w) {
  6481. this.w = other.w;
  6482. }
  6483. return this;
  6484. };
  6485. /**
  6486. * Gets a new Vector4 from current Vector4 floored values
  6487. * @returns a new Vector4
  6488. */
  6489. Vector4.prototype.floor = function () {
  6490. return new Vector4(Math.floor(this.x), Math.floor(this.y), Math.floor(this.z), Math.floor(this.w));
  6491. };
  6492. /**
  6493. * Gets a new Vector4 from current Vector3 floored values
  6494. * @returns a new Vector4
  6495. */
  6496. Vector4.prototype.fract = function () {
  6497. 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));
  6498. };
  6499. // Properties
  6500. /**
  6501. * Returns the Vector4 length (float).
  6502. * @returns the length
  6503. */
  6504. Vector4.prototype.length = function () {
  6505. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  6506. };
  6507. /**
  6508. * Returns the Vector4 squared length (float).
  6509. * @returns the length squared
  6510. */
  6511. Vector4.prototype.lengthSquared = function () {
  6512. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  6513. };
  6514. // Methods
  6515. /**
  6516. * Normalizes in place the Vector4.
  6517. * @returns the updated Vector4.
  6518. */
  6519. Vector4.prototype.normalize = function () {
  6520. var len = this.length();
  6521. if (len === 0) {
  6522. return this;
  6523. }
  6524. return this.scaleInPlace(1.0 / len);
  6525. };
  6526. /**
  6527. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  6528. * @returns this converted to a new vector3
  6529. */
  6530. Vector4.prototype.toVector3 = function () {
  6531. return new Vector3(this.x, this.y, this.z);
  6532. };
  6533. /**
  6534. * Returns a new Vector4 copied from the current one.
  6535. * @returns the new cloned vector
  6536. */
  6537. Vector4.prototype.clone = function () {
  6538. return new Vector4(this.x, this.y, this.z, this.w);
  6539. };
  6540. /**
  6541. * Updates the current Vector4 with the given one coordinates.
  6542. * @param source the source vector to copy from
  6543. * @returns the updated Vector4.
  6544. */
  6545. Vector4.prototype.copyFrom = function (source) {
  6546. this.x = source.x;
  6547. this.y = source.y;
  6548. this.z = source.z;
  6549. this.w = source.w;
  6550. return this;
  6551. };
  6552. /**
  6553. * Updates the current Vector4 coordinates with the given floats.
  6554. * @param x float to copy from
  6555. * @param y float to copy from
  6556. * @param z float to copy from
  6557. * @param w float to copy from
  6558. * @returns the updated Vector4.
  6559. */
  6560. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  6561. this.x = x;
  6562. this.y = y;
  6563. this.z = z;
  6564. this.w = w;
  6565. return this;
  6566. };
  6567. /**
  6568. * Updates the current Vector4 coordinates with the given floats.
  6569. * @param x float to set from
  6570. * @param y float to set from
  6571. * @param z float to set from
  6572. * @param w float to set from
  6573. * @returns the updated Vector4.
  6574. */
  6575. Vector4.prototype.set = function (x, y, z, w) {
  6576. return this.copyFromFloats(x, y, z, w);
  6577. };
  6578. /**
  6579. * Copies the given float to the current Vector3 coordinates
  6580. * @param v defines the x, y, z and w coordinates of the operand
  6581. * @returns the current updated Vector3
  6582. */
  6583. Vector4.prototype.setAll = function (v) {
  6584. this.x = this.y = this.z = this.w = v;
  6585. return this;
  6586. };
  6587. // Statics
  6588. /**
  6589. * Returns a new Vector4 set from the starting index of the given array.
  6590. * @param array the array to pull values from
  6591. * @param offset the offset into the array to start at
  6592. * @returns the new vector
  6593. */
  6594. Vector4.FromArray = function (array, offset) {
  6595. if (!offset) {
  6596. offset = 0;
  6597. }
  6598. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  6599. };
  6600. /**
  6601. * Updates the given vector "result" from the starting index of the given array.
  6602. * @param array the array to pull values from
  6603. * @param offset the offset into the array to start at
  6604. * @param result the vector to store the result in
  6605. */
  6606. Vector4.FromArrayToRef = function (array, offset, result) {
  6607. result.x = array[offset];
  6608. result.y = array[offset + 1];
  6609. result.z = array[offset + 2];
  6610. result.w = array[offset + 3];
  6611. };
  6612. /**
  6613. * Updates the given vector "result" from the starting index of the given Float32Array.
  6614. * @param array the array to pull values from
  6615. * @param offset the offset into the array to start at
  6616. * @param result the vector to store the result in
  6617. */
  6618. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  6619. Vector4.FromArrayToRef(array, offset, result);
  6620. };
  6621. /**
  6622. * Updates the given vector "result" coordinates from the given floats.
  6623. * @param x float to set from
  6624. * @param y float to set from
  6625. * @param z float to set from
  6626. * @param w float to set from
  6627. * @param result the vector to the floats in
  6628. */
  6629. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  6630. result.x = x;
  6631. result.y = y;
  6632. result.z = z;
  6633. result.w = w;
  6634. };
  6635. /**
  6636. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  6637. * @returns the new vector
  6638. */
  6639. Vector4.Zero = function () {
  6640. return new Vector4(0.0, 0.0, 0.0, 0.0);
  6641. };
  6642. /**
  6643. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  6644. * @returns the new vector
  6645. */
  6646. Vector4.One = function () {
  6647. return new Vector4(1.0, 1.0, 1.0, 1.0);
  6648. };
  6649. /**
  6650. * Returns a new normalized Vector4 from the given one.
  6651. * @param vector the vector to normalize
  6652. * @returns the vector
  6653. */
  6654. Vector4.Normalize = function (vector) {
  6655. var result = Vector4.Zero();
  6656. Vector4.NormalizeToRef(vector, result);
  6657. return result;
  6658. };
  6659. /**
  6660. * Updates the given vector "result" from the normalization of the given one.
  6661. * @param vector the vector to normalize
  6662. * @param result the vector to store the result in
  6663. */
  6664. Vector4.NormalizeToRef = function (vector, result) {
  6665. result.copyFrom(vector);
  6666. result.normalize();
  6667. };
  6668. /**
  6669. * Returns a vector with the minimum values from the left and right vectors
  6670. * @param left left vector to minimize
  6671. * @param right right vector to minimize
  6672. * @returns a new vector with the minimum of the left and right vector values
  6673. */
  6674. Vector4.Minimize = function (left, right) {
  6675. var min = left.clone();
  6676. min.minimizeInPlace(right);
  6677. return min;
  6678. };
  6679. /**
  6680. * Returns a vector with the maximum values from the left and right vectors
  6681. * @param left left vector to maximize
  6682. * @param right right vector to maximize
  6683. * @returns a new vector with the maximum of the left and right vector values
  6684. */
  6685. Vector4.Maximize = function (left, right) {
  6686. var max = left.clone();
  6687. max.maximizeInPlace(right);
  6688. return max;
  6689. };
  6690. /**
  6691. * Returns the distance (float) between the vectors "value1" and "value2".
  6692. * @param value1 value to calulate the distance between
  6693. * @param value2 value to calulate the distance between
  6694. * @return the distance between the two vectors
  6695. */
  6696. Vector4.Distance = function (value1, value2) {
  6697. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  6698. };
  6699. /**
  6700. * Returns the squared distance (float) between the vectors "value1" and "value2".
  6701. * @param value1 value to calulate the distance between
  6702. * @param value2 value to calulate the distance between
  6703. * @return the distance between the two vectors squared
  6704. */
  6705. Vector4.DistanceSquared = function (value1, value2) {
  6706. var x = value1.x - value2.x;
  6707. var y = value1.y - value2.y;
  6708. var z = value1.z - value2.z;
  6709. var w = value1.w - value2.w;
  6710. return (x * x) + (y * y) + (z * z) + (w * w);
  6711. };
  6712. /**
  6713. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  6714. * @param value1 value to calulate the center between
  6715. * @param value2 value to calulate the center between
  6716. * @return the center between the two vectors
  6717. */
  6718. Vector4.Center = function (value1, value2) {
  6719. var center = value1.add(value2);
  6720. center.scaleInPlace(0.5);
  6721. return center;
  6722. };
  6723. /**
  6724. * Returns a new Vector4 set with the result of the normal transformation by the given matrix of the given vector.
  6725. * This methods computes transformed normalized direction vectors only.
  6726. * @param vector the vector to transform
  6727. * @param transformation the transformation matrix to apply
  6728. * @returns the new vector
  6729. */
  6730. Vector4.TransformNormal = function (vector, transformation) {
  6731. var result = Vector4.Zero();
  6732. Vector4.TransformNormalToRef(vector, transformation, result);
  6733. return result;
  6734. };
  6735. /**
  6736. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector.
  6737. * This methods computes transformed normalized direction vectors only.
  6738. * @param vector the vector to transform
  6739. * @param transformation the transformation matrix to apply
  6740. * @param result the vector to store the result in
  6741. */
  6742. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  6743. var m = transformation.m;
  6744. var x = (vector.x * m[0]) + (vector.y * m[4]) + (vector.z * m[8]);
  6745. var y = (vector.x * m[1]) + (vector.y * m[5]) + (vector.z * m[9]);
  6746. var z = (vector.x * m[2]) + (vector.y * m[6]) + (vector.z * m[10]);
  6747. result.x = x;
  6748. result.y = y;
  6749. result.z = z;
  6750. result.w = vector.w;
  6751. };
  6752. /**
  6753. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z, w).
  6754. * This methods computes transformed normalized direction vectors only.
  6755. * @param x value to transform
  6756. * @param y value to transform
  6757. * @param z value to transform
  6758. * @param w value to transform
  6759. * @param transformation the transformation matrix to apply
  6760. * @param result the vector to store the results in
  6761. */
  6762. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  6763. var m = transformation.m;
  6764. result.x = (x * m[0]) + (y * m[4]) + (z * m[8]);
  6765. result.y = (x * m[1]) + (y * m[5]) + (z * m[9]);
  6766. result.z = (x * m[2]) + (y * m[6]) + (z * m[10]);
  6767. result.w = w;
  6768. };
  6769. return Vector4;
  6770. }());
  6771. BABYLON.Vector4 = Vector4;
  6772. /**
  6773. * Size containing widht and height
  6774. */
  6775. var Size = /** @class */ (function () {
  6776. /**
  6777. * Creates a Size object from the given width and height (floats).
  6778. * @param width width of the new size
  6779. * @param height height of the new size
  6780. */
  6781. function Size(width, height) {
  6782. this.width = width;
  6783. this.height = height;
  6784. }
  6785. /**
  6786. * Returns a string with the Size width and height
  6787. * @returns a string with the Size width and height
  6788. */
  6789. Size.prototype.toString = function () {
  6790. return "{W: " + this.width + ", H: " + this.height + "}";
  6791. };
  6792. /**
  6793. * "Size"
  6794. * @returns the string "Size"
  6795. */
  6796. Size.prototype.getClassName = function () {
  6797. return "Size";
  6798. };
  6799. /**
  6800. * Returns the Size hash code.
  6801. * @returns a hash code for a unique width and height
  6802. */
  6803. Size.prototype.getHashCode = function () {
  6804. var hash = this.width || 0;
  6805. hash = (hash * 397) ^ (this.height || 0);
  6806. return hash;
  6807. };
  6808. /**
  6809. * Updates the current size from the given one.
  6810. * @param src the given size
  6811. */
  6812. Size.prototype.copyFrom = function (src) {
  6813. this.width = src.width;
  6814. this.height = src.height;
  6815. };
  6816. /**
  6817. * Updates in place the current Size from the given floats.
  6818. * @param width width of the new size
  6819. * @param height height of the new size
  6820. * @returns the updated Size.
  6821. */
  6822. Size.prototype.copyFromFloats = function (width, height) {
  6823. this.width = width;
  6824. this.height = height;
  6825. return this;
  6826. };
  6827. /**
  6828. * Updates in place the current Size from the given floats.
  6829. * @param width width to set
  6830. * @param height height to set
  6831. * @returns the updated Size.
  6832. */
  6833. Size.prototype.set = function (width, height) {
  6834. return this.copyFromFloats(width, height);
  6835. };
  6836. /**
  6837. * Multiplies the width and height by numbers
  6838. * @param w factor to multiple the width by
  6839. * @param h factor to multiple the height by
  6840. * @returns a new Size set with the multiplication result of the current Size and the given floats.
  6841. */
  6842. Size.prototype.multiplyByFloats = function (w, h) {
  6843. return new Size(this.width * w, this.height * h);
  6844. };
  6845. /**
  6846. * Clones the size
  6847. * @returns a new Size copied from the given one.
  6848. */
  6849. Size.prototype.clone = function () {
  6850. return new Size(this.width, this.height);
  6851. };
  6852. /**
  6853. * True if the current Size and the given one width and height are strictly equal.
  6854. * @param other the other size to compare against
  6855. * @returns True if the current Size and the given one width and height are strictly equal.
  6856. */
  6857. Size.prototype.equals = function (other) {
  6858. if (!other) {
  6859. return false;
  6860. }
  6861. return (this.width === other.width) && (this.height === other.height);
  6862. };
  6863. Object.defineProperty(Size.prototype, "surface", {
  6864. /**
  6865. * The surface of the Size : width * height (float).
  6866. */
  6867. get: function () {
  6868. return this.width * this.height;
  6869. },
  6870. enumerable: true,
  6871. configurable: true
  6872. });
  6873. /**
  6874. * Create a new size of zero
  6875. * @returns a new Size set to (0.0, 0.0)
  6876. */
  6877. Size.Zero = function () {
  6878. return new Size(0.0, 0.0);
  6879. };
  6880. /**
  6881. * Sums the width and height of two sizes
  6882. * @param otherSize size to add to this size
  6883. * @returns a new Size set as the addition result of the current Size and the given one.
  6884. */
  6885. Size.prototype.add = function (otherSize) {
  6886. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  6887. return r;
  6888. };
  6889. /**
  6890. * Subtracts the width and height of two
  6891. * @param otherSize size to subtract to this size
  6892. * @returns a new Size set as the subtraction result of the given one from the current Size.
  6893. */
  6894. Size.prototype.subtract = function (otherSize) {
  6895. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  6896. return r;
  6897. };
  6898. /**
  6899. * Creates a new Size set at the linear interpolation "amount" between "start" and "end"
  6900. * @param start starting size to lerp between
  6901. * @param end end size to lerp between
  6902. * @param amount amount to lerp between the start and end values
  6903. * @returns a new Size set at the linear interpolation "amount" between "start" and "end"
  6904. */
  6905. Size.Lerp = function (start, end, amount) {
  6906. var w = start.width + ((end.width - start.width) * amount);
  6907. var h = start.height + ((end.height - start.height) * amount);
  6908. return new Size(w, h);
  6909. };
  6910. return Size;
  6911. }());
  6912. BABYLON.Size = Size;
  6913. /**
  6914. * Class used to store quaternion data
  6915. * @see https://en.wikipedia.org/wiki/Quaternion
  6916. * @see http://doc.babylonjs.com/features/position,_rotation,_scaling
  6917. */
  6918. var Quaternion = /** @class */ (function () {
  6919. /**
  6920. * Creates a new Quaternion from the given floats
  6921. * @param x defines the first component (0 by default)
  6922. * @param y defines the second component (0 by default)
  6923. * @param z defines the third component (0 by default)
  6924. * @param w defines the fourth component (1.0 by default)
  6925. */
  6926. function Quaternion(
  6927. /** defines the first component (0 by default) */
  6928. x,
  6929. /** defines the second component (0 by default) */
  6930. y,
  6931. /** defines the third component (0 by default) */
  6932. z,
  6933. /** defines the fourth component (1.0 by default) */
  6934. w) {
  6935. if (x === void 0) { x = 0.0; }
  6936. if (y === void 0) { y = 0.0; }
  6937. if (z === void 0) { z = 0.0; }
  6938. if (w === void 0) { w = 1.0; }
  6939. this.x = x;
  6940. this.y = y;
  6941. this.z = z;
  6942. this.w = w;
  6943. }
  6944. /**
  6945. * Gets a string representation for the current quaternion
  6946. * @returns a string with the Quaternion coordinates
  6947. */
  6948. Quaternion.prototype.toString = function () {
  6949. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  6950. };
  6951. /**
  6952. * Gets the class name of the quaternion
  6953. * @returns the string "Quaternion"
  6954. */
  6955. Quaternion.prototype.getClassName = function () {
  6956. return "Quaternion";
  6957. };
  6958. /**
  6959. * Gets a hash code for this quaternion
  6960. * @returns the quaternion hash code
  6961. */
  6962. Quaternion.prototype.getHashCode = function () {
  6963. var hash = this.x || 0;
  6964. hash = (hash * 397) ^ (this.y || 0);
  6965. hash = (hash * 397) ^ (this.z || 0);
  6966. hash = (hash * 397) ^ (this.w || 0);
  6967. return hash;
  6968. };
  6969. /**
  6970. * Copy the quaternion to an array
  6971. * @returns a new array populated with 4 elements from the quaternion coordinates
  6972. */
  6973. Quaternion.prototype.asArray = function () {
  6974. return [this.x, this.y, this.z, this.w];
  6975. };
  6976. /**
  6977. * Check if two quaternions are equals
  6978. * @param otherQuaternion defines the second operand
  6979. * @return true if the current quaternion and the given one coordinates are strictly equals
  6980. */
  6981. Quaternion.prototype.equals = function (otherQuaternion) {
  6982. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  6983. };
  6984. /**
  6985. * Clone the current quaternion
  6986. * @returns a new quaternion copied from the current one
  6987. */
  6988. Quaternion.prototype.clone = function () {
  6989. return new Quaternion(this.x, this.y, this.z, this.w);
  6990. };
  6991. /**
  6992. * Copy a quaternion to the current one
  6993. * @param other defines the other quaternion
  6994. * @returns the updated current quaternion
  6995. */
  6996. Quaternion.prototype.copyFrom = function (other) {
  6997. this.x = other.x;
  6998. this.y = other.y;
  6999. this.z = other.z;
  7000. this.w = other.w;
  7001. return this;
  7002. };
  7003. /**
  7004. * Updates the current quaternion with the given float coordinates
  7005. * @param x defines the x coordinate
  7006. * @param y defines the y coordinate
  7007. * @param z defines the z coordinate
  7008. * @param w defines the w coordinate
  7009. * @returns the updated current quaternion
  7010. */
  7011. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  7012. this.x = x;
  7013. this.y = y;
  7014. this.z = z;
  7015. this.w = w;
  7016. return this;
  7017. };
  7018. /**
  7019. * Updates the current quaternion from the given float coordinates
  7020. * @param x defines the x coordinate
  7021. * @param y defines the y coordinate
  7022. * @param z defines the z coordinate
  7023. * @param w defines the w coordinate
  7024. * @returns the updated current quaternion
  7025. */
  7026. Quaternion.prototype.set = function (x, y, z, w) {
  7027. return this.copyFromFloats(x, y, z, w);
  7028. };
  7029. /**
  7030. * Adds two quaternions
  7031. * @param other defines the second operand
  7032. * @returns a new quaternion as the addition result of the given one and the current quaternion
  7033. */
  7034. Quaternion.prototype.add = function (other) {
  7035. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  7036. };
  7037. /**
  7038. * Add a quaternion to the current one
  7039. * @param other defines the quaternion to add
  7040. * @returns the current quaternion
  7041. */
  7042. Quaternion.prototype.addInPlace = function (other) {
  7043. this.x += other.x;
  7044. this.y += other.y;
  7045. this.z += other.z;
  7046. this.w += other.w;
  7047. return this;
  7048. };
  7049. /**
  7050. * Subtract two quaternions
  7051. * @param other defines the second operand
  7052. * @returns a new quaternion as the subtraction result of the given one from the current one
  7053. */
  7054. Quaternion.prototype.subtract = function (other) {
  7055. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  7056. };
  7057. /**
  7058. * Multiplies the current quaternion by a scale factor
  7059. * @param value defines the scale factor
  7060. * @returns a new quaternion set by multiplying the current quaternion coordinates by the float "scale"
  7061. */
  7062. Quaternion.prototype.scale = function (value) {
  7063. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  7064. };
  7065. /**
  7066. * Scale the current quaternion values by a factor and stores the result to a given quaternion
  7067. * @param scale defines the scale factor
  7068. * @param result defines the Quaternion object where to store the result
  7069. * @returns the unmodified current quaternion
  7070. */
  7071. Quaternion.prototype.scaleToRef = function (scale, result) {
  7072. result.x = this.x * scale;
  7073. result.y = this.y * scale;
  7074. result.z = this.z * scale;
  7075. result.w = this.w * scale;
  7076. return this;
  7077. };
  7078. /**
  7079. * Multiplies in place the current quaternion by a scale factor
  7080. * @param value defines the scale factor
  7081. * @returns the current modified quaternion
  7082. */
  7083. Quaternion.prototype.scaleInPlace = function (value) {
  7084. this.x *= value;
  7085. this.y *= value;
  7086. this.z *= value;
  7087. this.w *= value;
  7088. return this;
  7089. };
  7090. /**
  7091. * Scale the current quaternion values by a factor and add the result to a given quaternion
  7092. * @param scale defines the scale factor
  7093. * @param result defines the Quaternion object where to store the result
  7094. * @returns the unmodified current quaternion
  7095. */
  7096. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  7097. result.x += this.x * scale;
  7098. result.y += this.y * scale;
  7099. result.z += this.z * scale;
  7100. result.w += this.w * scale;
  7101. return this;
  7102. };
  7103. /**
  7104. * Multiplies two quaternions
  7105. * @param q1 defines the second operand
  7106. * @returns a new quaternion set as the multiplication result of the current one with the given one "q1"
  7107. */
  7108. Quaternion.prototype.multiply = function (q1) {
  7109. var result = new Quaternion(0, 0, 0, 1.0);
  7110. this.multiplyToRef(q1, result);
  7111. return result;
  7112. };
  7113. /**
  7114. * Sets the given "result" as the the multiplication result of the current one with the given one "q1"
  7115. * @param q1 defines the second operand
  7116. * @param result defines the target quaternion
  7117. * @returns the current quaternion
  7118. */
  7119. Quaternion.prototype.multiplyToRef = function (q1, result) {
  7120. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  7121. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  7122. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  7123. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  7124. result.copyFromFloats(x, y, z, w);
  7125. return this;
  7126. };
  7127. /**
  7128. * Updates the current quaternion with the multiplication of itself with the given one "q1"
  7129. * @param q1 defines the second operand
  7130. * @returns the currentupdated quaternion
  7131. */
  7132. Quaternion.prototype.multiplyInPlace = function (q1) {
  7133. this.multiplyToRef(q1, this);
  7134. return this;
  7135. };
  7136. /**
  7137. * Conjugates (1-q) the current quaternion and stores the result in the given quaternion
  7138. * @param ref defines the target quaternion
  7139. * @returns the current quaternion
  7140. */
  7141. Quaternion.prototype.conjugateToRef = function (ref) {
  7142. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  7143. return this;
  7144. };
  7145. /**
  7146. * Conjugates in place (1-q) the current quaternion
  7147. * @returns the current updated quaternion
  7148. */
  7149. Quaternion.prototype.conjugateInPlace = function () {
  7150. this.x *= -1;
  7151. this.y *= -1;
  7152. this.z *= -1;
  7153. return this;
  7154. };
  7155. /**
  7156. * Conjugates in place (1-q) the current quaternion
  7157. * @returns a new quaternion
  7158. */
  7159. Quaternion.prototype.conjugate = function () {
  7160. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  7161. return result;
  7162. };
  7163. /**
  7164. * Gets length of current quaternion
  7165. * @returns the quaternion length (float)
  7166. */
  7167. Quaternion.prototype.length = function () {
  7168. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  7169. };
  7170. /**
  7171. * Normalize in place the current quaternion
  7172. * @returns the current updated quaternion
  7173. */
  7174. Quaternion.prototype.normalize = function () {
  7175. var length = 1.0 / this.length();
  7176. this.x *= length;
  7177. this.y *= length;
  7178. this.z *= length;
  7179. this.w *= length;
  7180. return this;
  7181. };
  7182. /**
  7183. * Returns a new Vector3 set with the Euler angles translated from the current quaternion
  7184. * @param order is a reserved parameter and is ignore for now
  7185. * @returns a new Vector3 containing the Euler angles
  7186. */
  7187. Quaternion.prototype.toEulerAngles = function (order) {
  7188. if (order === void 0) { order = "YZX"; }
  7189. var result = Vector3.Zero();
  7190. this.toEulerAnglesToRef(result, order);
  7191. return result;
  7192. };
  7193. /**
  7194. * Sets the given vector3 "result" with the Euler angles translated from the current quaternion
  7195. * @param result defines the vector which will be filled with the Euler angles
  7196. * @param order is a reserved parameter and is ignore for now
  7197. * @returns the current unchanged quaternion
  7198. */
  7199. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  7200. if (order === void 0) { order = "YZX"; }
  7201. var qz = this.z;
  7202. var qx = this.x;
  7203. var qy = this.y;
  7204. var qw = this.w;
  7205. var sqw = qw * qw;
  7206. var sqz = qz * qz;
  7207. var sqx = qx * qx;
  7208. var sqy = qy * qy;
  7209. var zAxisY = qy * qz - qx * qw;
  7210. var limit = .4999999;
  7211. if (zAxisY < -limit) {
  7212. result.y = 2 * Math.atan2(qy, qw);
  7213. result.x = Math.PI / 2;
  7214. result.z = 0;
  7215. }
  7216. else if (zAxisY > limit) {
  7217. result.y = 2 * Math.atan2(qy, qw);
  7218. result.x = -Math.PI / 2;
  7219. result.z = 0;
  7220. }
  7221. else {
  7222. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  7223. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  7224. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  7225. }
  7226. return this;
  7227. };
  7228. /**
  7229. * Updates the given rotation matrix with the current quaternion values
  7230. * @param result defines the target matrix
  7231. * @returns the current unchanged quaternion
  7232. */
  7233. Quaternion.prototype.toRotationMatrix = function (result) {
  7234. Matrix.FromQuaternionToRef(this, result);
  7235. return this;
  7236. };
  7237. /**
  7238. * Updates the current quaternion from the given rotation matrix values
  7239. * @param matrix defines the source matrix
  7240. * @returns the current updated quaternion
  7241. */
  7242. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  7243. Quaternion.FromRotationMatrixToRef(matrix, this);
  7244. return this;
  7245. };
  7246. // Statics
  7247. /**
  7248. * Creates a new quaternion from a rotation matrix
  7249. * @param matrix defines the source matrix
  7250. * @returns a new quaternion created from the given rotation matrix values
  7251. */
  7252. Quaternion.FromRotationMatrix = function (matrix) {
  7253. var result = new Quaternion();
  7254. Quaternion.FromRotationMatrixToRef(matrix, result);
  7255. return result;
  7256. };
  7257. /**
  7258. * Updates the given quaternion with the given rotation matrix values
  7259. * @param matrix defines the source matrix
  7260. * @param result defines the target quaternion
  7261. */
  7262. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  7263. var data = matrix.m;
  7264. var m11 = data[0], m12 = data[4], m13 = data[8];
  7265. var m21 = data[1], m22 = data[5], m23 = data[9];
  7266. var m31 = data[2], m32 = data[6], m33 = data[10];
  7267. var trace = m11 + m22 + m33;
  7268. var s;
  7269. if (trace > 0) {
  7270. s = 0.5 / Math.sqrt(trace + 1.0);
  7271. result.w = 0.25 / s;
  7272. result.x = (m32 - m23) * s;
  7273. result.y = (m13 - m31) * s;
  7274. result.z = (m21 - m12) * s;
  7275. }
  7276. else if (m11 > m22 && m11 > m33) {
  7277. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  7278. result.w = (m32 - m23) / s;
  7279. result.x = 0.25 * s;
  7280. result.y = (m12 + m21) / s;
  7281. result.z = (m13 + m31) / s;
  7282. }
  7283. else if (m22 > m33) {
  7284. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  7285. result.w = (m13 - m31) / s;
  7286. result.x = (m12 + m21) / s;
  7287. result.y = 0.25 * s;
  7288. result.z = (m23 + m32) / s;
  7289. }
  7290. else {
  7291. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  7292. result.w = (m21 - m12) / s;
  7293. result.x = (m13 + m31) / s;
  7294. result.y = (m23 + m32) / s;
  7295. result.z = 0.25 * s;
  7296. }
  7297. };
  7298. /**
  7299. * Returns the dot product (float) between the quaternions "left" and "right"
  7300. * @param left defines the left operand
  7301. * @param right defines the right operand
  7302. * @returns the dot product
  7303. */
  7304. Quaternion.Dot = function (left, right) {
  7305. return (left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w);
  7306. };
  7307. /**
  7308. * Checks if the two quaternions are close to each other
  7309. * @param quat0 defines the first quaternion to check
  7310. * @param quat1 defines the second quaternion to check
  7311. * @returns true if the two quaternions are close to each other
  7312. */
  7313. Quaternion.AreClose = function (quat0, quat1) {
  7314. var dot = Quaternion.Dot(quat0, quat1);
  7315. return dot >= 0;
  7316. };
  7317. /**
  7318. * Creates an empty quaternion
  7319. * @returns a new quaternion set to (0.0, 0.0, 0.0)
  7320. */
  7321. Quaternion.Zero = function () {
  7322. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  7323. };
  7324. /**
  7325. * Inverse a given quaternion
  7326. * @param q defines the source quaternion
  7327. * @returns a new quaternion as the inverted current quaternion
  7328. */
  7329. Quaternion.Inverse = function (q) {
  7330. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  7331. };
  7332. /**
  7333. * Inverse a given quaternion
  7334. * @param q defines the source quaternion
  7335. * @param result the quaternion the result will be stored in
  7336. * @returns the result quaternion
  7337. */
  7338. Quaternion.InverseToRef = function (q, result) {
  7339. result.set(-q.x, -q.y, -q.z, q.w);
  7340. return result;
  7341. };
  7342. /**
  7343. * Creates an identity quaternion
  7344. * @returns the identity quaternion
  7345. */
  7346. Quaternion.Identity = function () {
  7347. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  7348. };
  7349. /**
  7350. * Gets a boolean indicating if the given quaternion is identity
  7351. * @param quaternion defines the quaternion to check
  7352. * @returns true if the quaternion is identity
  7353. */
  7354. Quaternion.IsIdentity = function (quaternion) {
  7355. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  7356. };
  7357. /**
  7358. * Creates a quaternion from a rotation around an axis
  7359. * @param axis defines the axis to use
  7360. * @param angle defines the angle to use
  7361. * @returns a new quaternion created from the given axis (Vector3) and angle in radians (float)
  7362. */
  7363. Quaternion.RotationAxis = function (axis, angle) {
  7364. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  7365. };
  7366. /**
  7367. * Creates a rotation around an axis and stores it into the given quaternion
  7368. * @param axis defines the axis to use
  7369. * @param angle defines the angle to use
  7370. * @param result defines the target quaternion
  7371. * @returns the target quaternion
  7372. */
  7373. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  7374. var sin = Math.sin(angle / 2);
  7375. axis.normalize();
  7376. result.w = Math.cos(angle / 2);
  7377. result.x = axis.x * sin;
  7378. result.y = axis.y * sin;
  7379. result.z = axis.z * sin;
  7380. return result;
  7381. };
  7382. /**
  7383. * Creates a new quaternion from data stored into an array
  7384. * @param array defines the data source
  7385. * @param offset defines the offset in the source array where the data starts
  7386. * @returns a new quaternion
  7387. */
  7388. Quaternion.FromArray = function (array, offset) {
  7389. if (!offset) {
  7390. offset = 0;
  7391. }
  7392. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  7393. };
  7394. /**
  7395. * Create a quaternion from Euler rotation angles
  7396. * @param x Pitch
  7397. * @param y Yaw
  7398. * @param z Roll
  7399. * @returns the new Quaternion
  7400. */
  7401. Quaternion.FromEulerAngles = function (x, y, z) {
  7402. var q = new Quaternion();
  7403. Quaternion.RotationYawPitchRollToRef(y, x, z, q);
  7404. return q;
  7405. };
  7406. /**
  7407. * Updates a quaternion from Euler rotation angles
  7408. * @param x Pitch
  7409. * @param y Yaw
  7410. * @param z Roll
  7411. * @param result the quaternion to store the result
  7412. * @returns the updated quaternion
  7413. */
  7414. Quaternion.FromEulerAnglesToRef = function (x, y, z, result) {
  7415. Quaternion.RotationYawPitchRollToRef(y, x, z, result);
  7416. return result;
  7417. };
  7418. /**
  7419. * Create a quaternion from Euler rotation vector
  7420. * @param vec the Euler vector (x Pitch, y Yaw, z Roll)
  7421. * @returns the new Quaternion
  7422. */
  7423. Quaternion.FromEulerVector = function (vec) {
  7424. var q = new Quaternion();
  7425. Quaternion.RotationYawPitchRollToRef(vec.y, vec.x, vec.z, q);
  7426. return q;
  7427. };
  7428. /**
  7429. * Updates a quaternion from Euler rotation vector
  7430. * @param vec the Euler vector (x Pitch, y Yaw, z Roll)
  7431. * @param result the quaternion to store the result
  7432. * @returns the updated quaternion
  7433. */
  7434. Quaternion.FromEulerVectorToRef = function (vec, result) {
  7435. Quaternion.RotationYawPitchRollToRef(vec.y, vec.x, vec.z, result);
  7436. return result;
  7437. };
  7438. /**
  7439. * Creates a new quaternion from the given Euler float angles (y, x, z)
  7440. * @param yaw defines the rotation around Y axis
  7441. * @param pitch defines the rotation around X axis
  7442. * @param roll defines the rotation around Z axis
  7443. * @returns the new quaternion
  7444. */
  7445. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  7446. var q = new Quaternion();
  7447. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  7448. return q;
  7449. };
  7450. /**
  7451. * Creates a new rotation from the given Euler float angles (y, x, z) and stores it in the target quaternion
  7452. * @param yaw defines the rotation around Y axis
  7453. * @param pitch defines the rotation around X axis
  7454. * @param roll defines the rotation around Z axis
  7455. * @param result defines the target quaternion
  7456. */
  7457. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  7458. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  7459. var halfRoll = roll * 0.5;
  7460. var halfPitch = pitch * 0.5;
  7461. var halfYaw = yaw * 0.5;
  7462. var sinRoll = Math.sin(halfRoll);
  7463. var cosRoll = Math.cos(halfRoll);
  7464. var sinPitch = Math.sin(halfPitch);
  7465. var cosPitch = Math.cos(halfPitch);
  7466. var sinYaw = Math.sin(halfYaw);
  7467. var cosYaw = Math.cos(halfYaw);
  7468. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  7469. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  7470. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  7471. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  7472. };
  7473. /**
  7474. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation
  7475. * @param alpha defines the rotation around first axis
  7476. * @param beta defines the rotation around second axis
  7477. * @param gamma defines the rotation around third axis
  7478. * @returns the new quaternion
  7479. */
  7480. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  7481. var result = new Quaternion();
  7482. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  7483. return result;
  7484. };
  7485. /**
  7486. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation and stores it in the target quaternion
  7487. * @param alpha defines the rotation around first axis
  7488. * @param beta defines the rotation around second axis
  7489. * @param gamma defines the rotation around third axis
  7490. * @param result defines the target quaternion
  7491. */
  7492. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  7493. // Produces a quaternion from Euler angles in the z-x-z orientation
  7494. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  7495. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  7496. var halfBeta = beta * 0.5;
  7497. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  7498. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  7499. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  7500. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  7501. };
  7502. /**
  7503. * 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)
  7504. * @param axis1 defines the first axis
  7505. * @param axis2 defines the second axis
  7506. * @param axis3 defines the third axis
  7507. * @returns the new quaternion
  7508. */
  7509. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3) {
  7510. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  7511. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  7512. return quat;
  7513. };
  7514. /**
  7515. * 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
  7516. * @param axis1 defines the first axis
  7517. * @param axis2 defines the second axis
  7518. * @param axis3 defines the third axis
  7519. * @param ref defines the target quaternion
  7520. */
  7521. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  7522. var rotMat = MathTmp.Matrix[0];
  7523. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  7524. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  7525. };
  7526. /**
  7527. * Interpolates between two quaternions
  7528. * @param left defines first quaternion
  7529. * @param right defines second quaternion
  7530. * @param amount defines the gradient to use
  7531. * @returns the new interpolated quaternion
  7532. */
  7533. Quaternion.Slerp = function (left, right, amount) {
  7534. var result = Quaternion.Identity();
  7535. Quaternion.SlerpToRef(left, right, amount, result);
  7536. return result;
  7537. };
  7538. /**
  7539. * Interpolates between two quaternions and stores it into a target quaternion
  7540. * @param left defines first quaternion
  7541. * @param right defines second quaternion
  7542. * @param amount defines the gradient to use
  7543. * @param result defines the target quaternion
  7544. */
  7545. Quaternion.SlerpToRef = function (left, right, amount, result) {
  7546. var num2;
  7547. var num3;
  7548. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  7549. var flag = false;
  7550. if (num4 < 0) {
  7551. flag = true;
  7552. num4 = -num4;
  7553. }
  7554. if (num4 > 0.999999) {
  7555. num3 = 1 - amount;
  7556. num2 = flag ? -amount : amount;
  7557. }
  7558. else {
  7559. var num5 = Math.acos(num4);
  7560. var num6 = (1.0 / Math.sin(num5));
  7561. num3 = (Math.sin((1.0 - amount) * num5)) * num6;
  7562. num2 = flag ? ((-Math.sin(amount * num5)) * num6) : ((Math.sin(amount * num5)) * num6);
  7563. }
  7564. result.x = (num3 * left.x) + (num2 * right.x);
  7565. result.y = (num3 * left.y) + (num2 * right.y);
  7566. result.z = (num3 * left.z) + (num2 * right.z);
  7567. result.w = (num3 * left.w) + (num2 * right.w);
  7568. };
  7569. /**
  7570. * Interpolate between two quaternions using Hermite interpolation
  7571. * @param value1 defines first quaternion
  7572. * @param tangent1 defines the incoming tangent
  7573. * @param value2 defines second quaternion
  7574. * @param tangent2 defines the outgoing tangent
  7575. * @param amount defines the target quaternion
  7576. * @returns the new interpolated quaternion
  7577. */
  7578. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  7579. var squared = amount * amount;
  7580. var cubed = amount * squared;
  7581. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  7582. var part2 = (-2.0 * cubed) + (3.0 * squared);
  7583. var part3 = (cubed - (2.0 * squared)) + amount;
  7584. var part4 = cubed - squared;
  7585. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  7586. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  7587. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  7588. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  7589. return new Quaternion(x, y, z, w);
  7590. };
  7591. return Quaternion;
  7592. }());
  7593. BABYLON.Quaternion = Quaternion;
  7594. /**
  7595. * Class used to store matrix data (4x4)
  7596. */
  7597. var Matrix = /** @class */ (function () {
  7598. /**
  7599. * Creates an empty matrix (filled with zeros)
  7600. */
  7601. function Matrix() {
  7602. this._isIdentity = false;
  7603. this._isIdentityDirty = true;
  7604. this._isIdentity3x2 = true;
  7605. this._isIdentity3x2Dirty = true;
  7606. this._m = new Float32Array(16);
  7607. this._updateIdentityStatus(false);
  7608. }
  7609. Object.defineProperty(Matrix.prototype, "m", {
  7610. /**
  7611. * Gets the internal data of the matrix
  7612. */
  7613. get: function () { return this._m; },
  7614. enumerable: true,
  7615. configurable: true
  7616. });
  7617. /** @hidden */
  7618. Matrix.prototype._markAsUpdated = function () {
  7619. this.updateFlag = Matrix._updateFlagSeed++;
  7620. this._isIdentity = false;
  7621. this._isIdentity3x2 = false;
  7622. this._isIdentityDirty = true;
  7623. this._isIdentity3x2Dirty = true;
  7624. };
  7625. /** @hidden */
  7626. Matrix.prototype._updateIdentityStatus = function (isIdentity, isIdentityDirty, isIdentity3x2, isIdentity3x2Dirty) {
  7627. if (isIdentityDirty === void 0) { isIdentityDirty = false; }
  7628. if (isIdentity3x2 === void 0) { isIdentity3x2 = false; }
  7629. if (isIdentity3x2Dirty === void 0) { isIdentity3x2Dirty = true; }
  7630. this.updateFlag = Matrix._updateFlagSeed++;
  7631. this._isIdentity = isIdentity;
  7632. this._isIdentity3x2 = isIdentity || isIdentity3x2;
  7633. this._isIdentityDirty = this._isIdentity ? false : isIdentityDirty;
  7634. this._isIdentity3x2Dirty = this._isIdentity3x2 ? false : isIdentity3x2Dirty;
  7635. };
  7636. // Properties
  7637. /**
  7638. * Check if the current matrix is identity
  7639. * @returns true is the matrix is the identity matrix
  7640. */
  7641. Matrix.prototype.isIdentity = function () {
  7642. if (this._isIdentityDirty) {
  7643. this._isIdentityDirty = false;
  7644. var m = this._m;
  7645. this._isIdentity = (m[0] === 1.0 && m[1] === 0.0 && m[2] === 0.0 && m[3] === 0.0 &&
  7646. m[4] === 0.0 && m[5] === 1.0 && m[6] === 0.0 && m[7] === 0.0 &&
  7647. m[8] === 0.0 && m[9] === 0.0 && m[10] === 1.0 && m[11] === 0.0 &&
  7648. m[12] === 0.0 && m[13] === 0.0 && m[14] === 0.0 && m[15] === 1.0);
  7649. }
  7650. return this._isIdentity;
  7651. };
  7652. /**
  7653. * Check if the current matrix is identity as a texture matrix (3x2 store in 4x4)
  7654. * @returns true is the matrix is the identity matrix
  7655. */
  7656. Matrix.prototype.isIdentityAs3x2 = function () {
  7657. if (this._isIdentity3x2Dirty) {
  7658. this._isIdentity3x2Dirty = false;
  7659. if (this._m[0] !== 1.0 || this._m[5] !== 1.0 || this._m[15] !== 1.0) {
  7660. this._isIdentity3x2 = false;
  7661. }
  7662. else if (this._m[1] !== 0.0 || this._m[2] !== 0.0 || this._m[3] !== 0.0 ||
  7663. this._m[4] !== 0.0 || this._m[6] !== 0.0 || this._m[7] !== 0.0 ||
  7664. this._m[8] !== 0.0 || this._m[9] !== 0.0 || this._m[10] !== 0.0 || this._m[11] !== 0.0 ||
  7665. this._m[12] !== 0.0 || this._m[13] !== 0.0 || this._m[14] !== 0.0) {
  7666. this._isIdentity3x2 = false;
  7667. }
  7668. else {
  7669. this._isIdentity3x2 = true;
  7670. }
  7671. }
  7672. return this._isIdentity3x2;
  7673. };
  7674. /**
  7675. * Gets the determinant of the matrix
  7676. * @returns the matrix determinant
  7677. */
  7678. Matrix.prototype.determinant = function () {
  7679. if (this._isIdentity === true) {
  7680. return 1;
  7681. }
  7682. var m = this._m;
  7683. var m00 = m[0], m01 = m[1], m02 = m[2], m03 = m[3];
  7684. var m10 = m[4], m11 = m[5], m12 = m[6], m13 = m[7];
  7685. var m20 = m[8], m21 = m[9], m22 = m[10], m23 = m[11];
  7686. var m30 = m[12], m31 = m[13], m32 = m[14], m33 = m[15];
  7687. // https://en.wikipedia.org/wiki/Laplace_expansion
  7688. // to compute the deterrminant of a 4x4 Matrix we compute the cofactors of any row or column,
  7689. // then we multiply each Cofactor by its corresponding matrix value and sum them all to get the determinant
  7690. // Cofactor(i, j) = sign(i,j) * det(Minor(i, j))
  7691. // where
  7692. // - sign(i,j) = (i+j) % 2 === 0 ? 1 : -1
  7693. // - Minor(i, j) is the 3x3 matrix we get by removing row i and column j from current Matrix
  7694. //
  7695. // Here we do that for the 1st row.
  7696. var det_22_33 = m22 * m33 - m32 * m23;
  7697. var det_21_33 = m21 * m33 - m31 * m23;
  7698. var det_21_32 = m21 * m32 - m31 * m22;
  7699. var det_20_33 = m20 * m33 - m30 * m23;
  7700. var det_20_32 = m20 * m32 - m22 * m30;
  7701. var det_20_31 = m20 * m31 - m30 * m21;
  7702. var cofact_00 = +(m11 * det_22_33 - m12 * det_21_33 + m13 * det_21_32);
  7703. var cofact_01 = -(m10 * det_22_33 - m12 * det_20_33 + m13 * det_20_32);
  7704. var cofact_02 = +(m10 * det_21_33 - m11 * det_20_33 + m13 * det_20_31);
  7705. var cofact_03 = -(m10 * det_21_32 - m11 * det_20_32 + m12 * det_20_31);
  7706. return m00 * cofact_00 + m01 * cofact_01 + m02 * cofact_02 + m03 * cofact_03;
  7707. };
  7708. // Methods
  7709. /**
  7710. * Returns the matrix as a Float32Array
  7711. * @returns the matrix underlying array
  7712. */
  7713. Matrix.prototype.toArray = function () {
  7714. return this._m;
  7715. };
  7716. /**
  7717. * Returns the matrix as a Float32Array
  7718. * @returns the matrix underlying array.
  7719. */
  7720. Matrix.prototype.asArray = function () {
  7721. return this._m;
  7722. };
  7723. /**
  7724. * Inverts the current matrix in place
  7725. * @returns the current inverted matrix
  7726. */
  7727. Matrix.prototype.invert = function () {
  7728. this.invertToRef(this);
  7729. return this;
  7730. };
  7731. /**
  7732. * Sets all the matrix elements to zero
  7733. * @returns the current matrix
  7734. */
  7735. Matrix.prototype.reset = function () {
  7736. Matrix.FromValuesToRef(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, this);
  7737. this._updateIdentityStatus(false);
  7738. return this;
  7739. };
  7740. /**
  7741. * Adds the current matrix with a second one
  7742. * @param other defines the matrix to add
  7743. * @returns a new matrix as the addition of the current matrix and the given one
  7744. */
  7745. Matrix.prototype.add = function (other) {
  7746. var result = new Matrix();
  7747. this.addToRef(other, result);
  7748. return result;
  7749. };
  7750. /**
  7751. * Sets the given matrix "result" to the addition of the current matrix and the given one
  7752. * @param other defines the matrix to add
  7753. * @param result defines the target matrix
  7754. * @returns the current matrix
  7755. */
  7756. Matrix.prototype.addToRef = function (other, result) {
  7757. var m = this._m;
  7758. var resultM = result._m;
  7759. var otherM = other.m;
  7760. for (var index = 0; index < 16; index++) {
  7761. resultM[index] = m[index] + otherM[index];
  7762. }
  7763. result._markAsUpdated();
  7764. return this;
  7765. };
  7766. /**
  7767. * Adds in place the given matrix to the current matrix
  7768. * @param other defines the second operand
  7769. * @returns the current updated matrix
  7770. */
  7771. Matrix.prototype.addToSelf = function (other) {
  7772. var m = this._m;
  7773. var otherM = other.m;
  7774. for (var index = 0; index < 16; index++) {
  7775. m[index] += otherM[index];
  7776. }
  7777. this._markAsUpdated();
  7778. return this;
  7779. };
  7780. /**
  7781. * Sets the given matrix to the current inverted Matrix
  7782. * @param other defines the target matrix
  7783. * @returns the unmodified current matrix
  7784. */
  7785. Matrix.prototype.invertToRef = function (other) {
  7786. if (this._isIdentity === true) {
  7787. Matrix.IdentityToRef(other);
  7788. return this;
  7789. }
  7790. // the inverse of a Matrix is the transpose of cofactor matrix divided by the determinant
  7791. var m = this._m;
  7792. var m00 = m[0], m01 = m[1], m02 = m[2], m03 = m[3];
  7793. var m10 = m[4], m11 = m[5], m12 = m[6], m13 = m[7];
  7794. var m20 = m[8], m21 = m[9], m22 = m[10], m23 = m[11];
  7795. var m30 = m[12], m31 = m[13], m32 = m[14], m33 = m[15];
  7796. var det_22_33 = m22 * m33 - m32 * m23;
  7797. var det_21_33 = m21 * m33 - m31 * m23;
  7798. var det_21_32 = m21 * m32 - m31 * m22;
  7799. var det_20_33 = m20 * m33 - m30 * m23;
  7800. var det_20_32 = m20 * m32 - m22 * m30;
  7801. var det_20_31 = m20 * m31 - m30 * m21;
  7802. var cofact_00 = +(m11 * det_22_33 - m12 * det_21_33 + m13 * det_21_32);
  7803. var cofact_01 = -(m10 * det_22_33 - m12 * det_20_33 + m13 * det_20_32);
  7804. var cofact_02 = +(m10 * det_21_33 - m11 * det_20_33 + m13 * det_20_31);
  7805. var cofact_03 = -(m10 * det_21_32 - m11 * det_20_32 + m12 * det_20_31);
  7806. var det = m00 * cofact_00 + m01 * cofact_01 + m02 * cofact_02 + m03 * cofact_03;
  7807. if (det === 0) {
  7808. // not invertible
  7809. other.copyFrom(this);
  7810. return this;
  7811. }
  7812. var detInv = 1 / det;
  7813. var det_12_33 = m12 * m33 - m32 * m13;
  7814. var det_11_33 = m11 * m33 - m31 * m13;
  7815. var det_11_32 = m11 * m32 - m31 * m12;
  7816. var det_10_33 = m10 * m33 - m30 * m13;
  7817. var det_10_32 = m10 * m32 - m30 * m12;
  7818. var det_10_31 = m10 * m31 - m30 * m11;
  7819. var det_12_23 = m12 * m23 - m22 * m13;
  7820. var det_11_23 = m11 * m23 - m21 * m13;
  7821. var det_11_22 = m11 * m22 - m21 * m12;
  7822. var det_10_23 = m10 * m23 - m20 * m13;
  7823. var det_10_22 = m10 * m22 - m20 * m12;
  7824. var det_10_21 = m10 * m21 - m20 * m11;
  7825. var cofact_10 = -(m01 * det_22_33 - m02 * det_21_33 + m03 * det_21_32);
  7826. var cofact_11 = +(m00 * det_22_33 - m02 * det_20_33 + m03 * det_20_32);
  7827. var cofact_12 = -(m00 * det_21_33 - m01 * det_20_33 + m03 * det_20_31);
  7828. var cofact_13 = +(m00 * det_21_32 - m01 * det_20_32 + m02 * det_20_31);
  7829. var cofact_20 = +(m01 * det_12_33 - m02 * det_11_33 + m03 * det_11_32);
  7830. var cofact_21 = -(m00 * det_12_33 - m02 * det_10_33 + m03 * det_10_32);
  7831. var cofact_22 = +(m00 * det_11_33 - m01 * det_10_33 + m03 * det_10_31);
  7832. var cofact_23 = -(m00 * det_11_32 - m01 * det_10_32 + m02 * det_10_31);
  7833. var cofact_30 = -(m01 * det_12_23 - m02 * det_11_23 + m03 * det_11_22);
  7834. var cofact_31 = +(m00 * det_12_23 - m02 * det_10_23 + m03 * det_10_22);
  7835. var cofact_32 = -(m00 * det_11_23 - m01 * det_10_23 + m03 * det_10_21);
  7836. var cofact_33 = +(m00 * det_11_22 - m01 * det_10_22 + m02 * det_10_21);
  7837. Matrix.FromValuesToRef(cofact_00 * detInv, cofact_10 * detInv, cofact_20 * detInv, cofact_30 * detInv, cofact_01 * detInv, cofact_11 * detInv, cofact_21 * detInv, cofact_31 * detInv, cofact_02 * detInv, cofact_12 * detInv, cofact_22 * detInv, cofact_32 * detInv, cofact_03 * detInv, cofact_13 * detInv, cofact_23 * detInv, cofact_33 * detInv, other);
  7838. return this;
  7839. };
  7840. /**
  7841. * add a value at the specified position in the current Matrix
  7842. * @param index the index of the value within the matrix. between 0 and 15.
  7843. * @param value the value to be added
  7844. * @returns the current updated matrix
  7845. */
  7846. Matrix.prototype.addAtIndex = function (index, value) {
  7847. this._m[index] += value;
  7848. this._markAsUpdated();
  7849. return this;
  7850. };
  7851. /**
  7852. * mutiply the specified position in the current Matrix by a value
  7853. * @param index the index of the value within the matrix. between 0 and 15.
  7854. * @param value the value to be added
  7855. * @returns the current updated matrix
  7856. */
  7857. Matrix.prototype.multiplyAtIndex = function (index, value) {
  7858. this._m[index] *= value;
  7859. this._markAsUpdated();
  7860. return this;
  7861. };
  7862. /**
  7863. * Inserts the translation vector (using 3 floats) in the current matrix
  7864. * @param x defines the 1st component of the translation
  7865. * @param y defines the 2nd component of the translation
  7866. * @param z defines the 3rd component of the translation
  7867. * @returns the current updated matrix
  7868. */
  7869. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  7870. this._m[12] = x;
  7871. this._m[13] = y;
  7872. this._m[14] = z;
  7873. this._markAsUpdated();
  7874. return this;
  7875. };
  7876. /**
  7877. * Inserts the translation vector in the current matrix
  7878. * @param vector3 defines the translation to insert
  7879. * @returns the current updated matrix
  7880. */
  7881. Matrix.prototype.setTranslation = function (vector3) {
  7882. return this.setTranslationFromFloats(vector3.x, vector3.y, vector3.z);
  7883. };
  7884. /**
  7885. * Gets the translation value of the current matrix
  7886. * @returns a new Vector3 as the extracted translation from the matrix
  7887. */
  7888. Matrix.prototype.getTranslation = function () {
  7889. return new Vector3(this._m[12], this._m[13], this._m[14]);
  7890. };
  7891. /**
  7892. * Fill a Vector3 with the extracted translation from the matrix
  7893. * @param result defines the Vector3 where to store the translation
  7894. * @returns the current matrix
  7895. */
  7896. Matrix.prototype.getTranslationToRef = function (result) {
  7897. result.x = this._m[12];
  7898. result.y = this._m[13];
  7899. result.z = this._m[14];
  7900. return this;
  7901. };
  7902. /**
  7903. * Remove rotation and scaling part from the matrix
  7904. * @returns the updated matrix
  7905. */
  7906. Matrix.prototype.removeRotationAndScaling = function () {
  7907. var m = this.m;
  7908. 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, m[12], m[13], m[14], m[15], this);
  7909. this._updateIdentityStatus(m[12] === 0 && m[13] === 0 && m[14] === 0 && m[15] === 1);
  7910. return this;
  7911. };
  7912. /**
  7913. * Multiply two matrices
  7914. * @param other defines the second operand
  7915. * @returns a new matrix set with the multiplication result of the current Matrix and the given one
  7916. */
  7917. Matrix.prototype.multiply = function (other) {
  7918. var result = new Matrix();
  7919. this.multiplyToRef(other, result);
  7920. return result;
  7921. };
  7922. /**
  7923. * Copy the current matrix from the given one
  7924. * @param other defines the source matrix
  7925. * @returns the current updated matrix
  7926. */
  7927. Matrix.prototype.copyFrom = function (other) {
  7928. other.copyToArray(this._m);
  7929. var o = other;
  7930. this._updateIdentityStatus(o._isIdentity, o._isIdentityDirty, o._isIdentity3x2, o._isIdentity3x2Dirty);
  7931. return this;
  7932. };
  7933. /**
  7934. * Populates the given array from the starting index with the current matrix values
  7935. * @param array defines the target array
  7936. * @param offset defines the offset in the target array where to start storing values
  7937. * @returns the current matrix
  7938. */
  7939. Matrix.prototype.copyToArray = function (array, offset) {
  7940. if (offset === void 0) { offset = 0; }
  7941. for (var index = 0; index < 16; index++) {
  7942. array[offset + index] = this._m[index];
  7943. }
  7944. return this;
  7945. };
  7946. /**
  7947. * Sets the given matrix "result" with the multiplication result of the current Matrix and the given one
  7948. * @param other defines the second operand
  7949. * @param result defines the matrix where to store the multiplication
  7950. * @returns the current matrix
  7951. */
  7952. Matrix.prototype.multiplyToRef = function (other, result) {
  7953. if (this._isIdentity) {
  7954. result.copyFrom(other);
  7955. return this;
  7956. }
  7957. if (other._isIdentity) {
  7958. result.copyFrom(this);
  7959. return this;
  7960. }
  7961. this.multiplyToArray(other, result._m, 0);
  7962. result._markAsUpdated();
  7963. return this;
  7964. };
  7965. /**
  7966. * Sets the Float32Array "result" from the given index "offset" with the multiplication of the current matrix and the given one
  7967. * @param other defines the second operand
  7968. * @param result defines the array where to store the multiplication
  7969. * @param offset defines the offset in the target array where to start storing values
  7970. * @returns the current matrix
  7971. */
  7972. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  7973. var m = this._m;
  7974. var otherM = other.m;
  7975. var tm0 = m[0], tm1 = m[1], tm2 = m[2], tm3 = m[3];
  7976. var tm4 = m[4], tm5 = m[5], tm6 = m[6], tm7 = m[7];
  7977. var tm8 = m[8], tm9 = m[9], tm10 = m[10], tm11 = m[11];
  7978. var tm12 = m[12], tm13 = m[13], tm14 = m[14], tm15 = m[15];
  7979. var om0 = otherM[0], om1 = otherM[1], om2 = otherM[2], om3 = otherM[3];
  7980. var om4 = otherM[4], om5 = otherM[5], om6 = otherM[6], om7 = otherM[7];
  7981. var om8 = otherM[8], om9 = otherM[9], om10 = otherM[10], om11 = otherM[11];
  7982. var om12 = otherM[12], om13 = otherM[13], om14 = otherM[14], om15 = otherM[15];
  7983. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  7984. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  7985. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  7986. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  7987. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  7988. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  7989. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  7990. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  7991. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  7992. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  7993. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  7994. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  7995. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  7996. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  7997. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  7998. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  7999. return this;
  8000. };
  8001. /**
  8002. * Check equality between this matrix and a second one
  8003. * @param value defines the second matrix to compare
  8004. * @returns true is the current matrix and the given one values are strictly equal
  8005. */
  8006. Matrix.prototype.equals = function (value) {
  8007. var other = value;
  8008. if (!other) {
  8009. return false;
  8010. }
  8011. if (this._isIdentity || other._isIdentity) {
  8012. if (!this._isIdentityDirty && !other._isIdentityDirty) {
  8013. return this._isIdentity && other._isIdentity;
  8014. }
  8015. }
  8016. var m = this.m;
  8017. var om = other.m;
  8018. return (m[0] === om[0] && m[1] === om[1] && m[2] === om[2] && m[3] === om[3] &&
  8019. m[4] === om[4] && m[5] === om[5] && m[6] === om[6] && m[7] === om[7] &&
  8020. m[8] === om[8] && m[9] === om[9] && m[10] === om[10] && m[11] === om[11] &&
  8021. m[12] === om[12] && m[13] === om[13] && m[14] === om[14] && m[15] === om[15]);
  8022. };
  8023. /**
  8024. * Clone the current matrix
  8025. * @returns a new matrix from the current matrix
  8026. */
  8027. Matrix.prototype.clone = function () {
  8028. var matrix = new Matrix();
  8029. matrix.copyFrom(this);
  8030. return matrix;
  8031. };
  8032. /**
  8033. * Returns the name of the current matrix class
  8034. * @returns the string "Matrix"
  8035. */
  8036. Matrix.prototype.getClassName = function () {
  8037. return "Matrix";
  8038. };
  8039. /**
  8040. * Gets the hash code of the current matrix
  8041. * @returns the hash code
  8042. */
  8043. Matrix.prototype.getHashCode = function () {
  8044. var hash = this._m[0] || 0;
  8045. for (var i = 1; i < 16; i++) {
  8046. hash = (hash * 397) ^ (this._m[i] || 0);
  8047. }
  8048. return hash;
  8049. };
  8050. /**
  8051. * Decomposes the current Matrix into a translation, rotation and scaling components
  8052. * @param scale defines the scale vector3 given as a reference to update
  8053. * @param rotation defines the rotation quaternion given as a reference to update
  8054. * @param translation defines the translation vector3 given as a reference to update
  8055. * @returns true if operation was successful
  8056. */
  8057. Matrix.prototype.decompose = function (scale, rotation, translation) {
  8058. if (this._isIdentity) {
  8059. if (translation) {
  8060. translation.setAll(0);
  8061. }
  8062. if (scale) {
  8063. scale.setAll(1);
  8064. }
  8065. if (rotation) {
  8066. rotation.copyFromFloats(0, 0, 0, 1);
  8067. }
  8068. return true;
  8069. }
  8070. var m = this._m;
  8071. if (translation) {
  8072. translation.copyFromFloats(m[12], m[13], m[14]);
  8073. }
  8074. scale = scale || MathTmp.Vector3[0];
  8075. scale.x = Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  8076. scale.y = Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  8077. scale.z = Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  8078. if (this.determinant() <= 0) {
  8079. scale.y *= -1;
  8080. }
  8081. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  8082. if (rotation) {
  8083. rotation.copyFromFloats(0.0, 0.0, 0.0, 1.0);
  8084. }
  8085. return false;
  8086. }
  8087. if (rotation) {
  8088. var sx = 1 / scale.x, sy = 1 / scale.y, sz = 1 / scale.z;
  8089. Matrix.FromValuesToRef(m[0] * sx, m[1] * sx, m[2] * sx, 0.0, m[4] * sy, m[5] * sy, m[6] * sy, 0.0, m[8] * sz, m[9] * sz, m[10] * sz, 0.0, 0.0, 0.0, 0.0, 1.0, MathTmp.Matrix[0]);
  8090. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  8091. }
  8092. return true;
  8093. };
  8094. /**
  8095. * Gets specific row of the matrix
  8096. * @param index defines the number of the row to get
  8097. * @returns the index-th row of the current matrix as a new Vector4
  8098. */
  8099. Matrix.prototype.getRow = function (index) {
  8100. if (index < 0 || index > 3) {
  8101. return null;
  8102. }
  8103. var i = index * 4;
  8104. return new Vector4(this._m[i + 0], this._m[i + 1], this._m[i + 2], this._m[i + 3]);
  8105. };
  8106. /**
  8107. * Sets the index-th row of the current matrix to the vector4 values
  8108. * @param index defines the number of the row to set
  8109. * @param row defines the target vector4
  8110. * @returns the updated current matrix
  8111. */
  8112. Matrix.prototype.setRow = function (index, row) {
  8113. return this.setRowFromFloats(index, row.x, row.y, row.z, row.w);
  8114. };
  8115. /**
  8116. * Compute the transpose of the matrix
  8117. * @returns the new transposed matrix
  8118. */
  8119. Matrix.prototype.transpose = function () {
  8120. return Matrix.Transpose(this);
  8121. };
  8122. /**
  8123. * Compute the transpose of the matrix and store it in a given matrix
  8124. * @param result defines the target matrix
  8125. * @returns the current matrix
  8126. */
  8127. Matrix.prototype.transposeToRef = function (result) {
  8128. Matrix.TransposeToRef(this, result);
  8129. return this;
  8130. };
  8131. /**
  8132. * Sets the index-th row of the current matrix with the given 4 x float values
  8133. * @param index defines the row index
  8134. * @param x defines the x component to set
  8135. * @param y defines the y component to set
  8136. * @param z defines the z component to set
  8137. * @param w defines the w component to set
  8138. * @returns the updated current matrix
  8139. */
  8140. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  8141. if (index < 0 || index > 3) {
  8142. return this;
  8143. }
  8144. var i = index * 4;
  8145. this._m[i + 0] = x;
  8146. this._m[i + 1] = y;
  8147. this._m[i + 2] = z;
  8148. this._m[i + 3] = w;
  8149. this._markAsUpdated();
  8150. return this;
  8151. };
  8152. /**
  8153. * Compute a new matrix set with the current matrix values multiplied by scale (float)
  8154. * @param scale defines the scale factor
  8155. * @returns a new matrix
  8156. */
  8157. Matrix.prototype.scale = function (scale) {
  8158. var result = new Matrix();
  8159. this.scaleToRef(scale, result);
  8160. return result;
  8161. };
  8162. /**
  8163. * Scale the current matrix values by a factor to a given result matrix
  8164. * @param scale defines the scale factor
  8165. * @param result defines the matrix to store the result
  8166. * @returns the current matrix
  8167. */
  8168. Matrix.prototype.scaleToRef = function (scale, result) {
  8169. for (var index = 0; index < 16; index++) {
  8170. result._m[index] = this._m[index] * scale;
  8171. }
  8172. result._markAsUpdated();
  8173. return this;
  8174. };
  8175. /**
  8176. * Scale the current matrix values by a factor and add the result to a given matrix
  8177. * @param scale defines the scale factor
  8178. * @param result defines the Matrix to store the result
  8179. * @returns the current matrix
  8180. */
  8181. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  8182. for (var index = 0; index < 16; index++) {
  8183. result._m[index] += this._m[index] * scale;
  8184. }
  8185. result._markAsUpdated();
  8186. return this;
  8187. };
  8188. /**
  8189. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  8190. * @param ref matrix to store the result
  8191. */
  8192. Matrix.prototype.toNormalMatrix = function (ref) {
  8193. var tmp = MathTmp.Matrix[0];
  8194. this.invertToRef(tmp);
  8195. tmp.transposeToRef(ref);
  8196. var m = ref._m;
  8197. Matrix.FromValuesToRef(m[0], m[1], m[2], 0.0, m[4], m[5], m[6], 0.0, m[8], m[9], m[10], 0.0, 0.0, 0.0, 0.0, 1.0, ref);
  8198. };
  8199. /**
  8200. * Gets only rotation part of the current matrix
  8201. * @returns a new matrix sets to the extracted rotation matrix from the current one
  8202. */
  8203. Matrix.prototype.getRotationMatrix = function () {
  8204. var result = new Matrix();
  8205. this.getRotationMatrixToRef(result);
  8206. return result;
  8207. };
  8208. /**
  8209. * Extracts the rotation matrix from the current one and sets it as the given "result"
  8210. * @param result defines the target matrix to store data to
  8211. * @returns the current matrix
  8212. */
  8213. Matrix.prototype.getRotationMatrixToRef = function (result) {
  8214. var scale = MathTmp.Vector3[0];
  8215. if (!this.decompose(scale)) {
  8216. Matrix.IdentityToRef(result);
  8217. return this;
  8218. }
  8219. var m = this._m;
  8220. var sx = 1 / scale.x, sy = 1 / scale.y, sz = 1 / scale.z;
  8221. Matrix.FromValuesToRef(m[0] * sx, m[1] * sx, m[2] * sx, 0.0, m[4] * sy, m[5] * sy, m[6] * sy, 0.0, m[8] * sz, m[9] * sz, m[10] * sz, 0.0, 0.0, 0.0, 0.0, 1.0, result);
  8222. return this;
  8223. };
  8224. /**
  8225. * Toggles model matrix from being right handed to left handed in place and vice versa
  8226. */
  8227. Matrix.prototype.toggleModelMatrixHandInPlace = function () {
  8228. var m = this._m;
  8229. m[2] *= -1;
  8230. m[6] *= -1;
  8231. m[8] *= -1;
  8232. m[9] *= -1;
  8233. m[14] *= -1;
  8234. this._markAsUpdated();
  8235. };
  8236. /**
  8237. * Toggles projection matrix from being right handed to left handed in place and vice versa
  8238. */
  8239. Matrix.prototype.toggleProjectionMatrixHandInPlace = function () {
  8240. var m = this._m;
  8241. m[8] *= -1;
  8242. m[9] *= -1;
  8243. m[10] *= -1;
  8244. m[11] *= -1;
  8245. this._markAsUpdated();
  8246. };
  8247. // Statics
  8248. /**
  8249. * Creates a matrix from an array
  8250. * @param array defines the source array
  8251. * @param offset defines an offset in the source array
  8252. * @returns a new Matrix set from the starting index of the given array
  8253. */
  8254. Matrix.FromArray = function (array, offset) {
  8255. if (offset === void 0) { offset = 0; }
  8256. var result = new Matrix();
  8257. Matrix.FromArrayToRef(array, offset, result);
  8258. return result;
  8259. };
  8260. /**
  8261. * Copy the content of an array into a given matrix
  8262. * @param array defines the source array
  8263. * @param offset defines an offset in the source array
  8264. * @param result defines the target matrix
  8265. */
  8266. Matrix.FromArrayToRef = function (array, offset, result) {
  8267. for (var index = 0; index < 16; index++) {
  8268. result._m[index] = array[index + offset];
  8269. }
  8270. result._markAsUpdated();
  8271. };
  8272. /**
  8273. * Stores an array into a matrix after having multiplied each component by a given factor
  8274. * @param array defines the source array
  8275. * @param offset defines the offset in the source array
  8276. * @param scale defines the scaling factor
  8277. * @param result defines the target matrix
  8278. */
  8279. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  8280. for (var index = 0; index < 16; index++) {
  8281. result._m[index] = array[index + offset] * scale;
  8282. }
  8283. result._markAsUpdated();
  8284. };
  8285. Object.defineProperty(Matrix, "IdentityReadOnly", {
  8286. /**
  8287. * Gets an identity matrix that must not be updated
  8288. */
  8289. get: function () {
  8290. return Matrix._identityReadOnly;
  8291. },
  8292. enumerable: true,
  8293. configurable: true
  8294. });
  8295. /**
  8296. * Stores a list of values (16) inside a given matrix
  8297. * @param initialM11 defines 1st value of 1st row
  8298. * @param initialM12 defines 2nd value of 1st row
  8299. * @param initialM13 defines 3rd value of 1st row
  8300. * @param initialM14 defines 4th value of 1st row
  8301. * @param initialM21 defines 1st value of 2nd row
  8302. * @param initialM22 defines 2nd value of 2nd row
  8303. * @param initialM23 defines 3rd value of 2nd row
  8304. * @param initialM24 defines 4th value of 2nd row
  8305. * @param initialM31 defines 1st value of 3rd row
  8306. * @param initialM32 defines 2nd value of 3rd row
  8307. * @param initialM33 defines 3rd value of 3rd row
  8308. * @param initialM34 defines 4th value of 3rd row
  8309. * @param initialM41 defines 1st value of 4th row
  8310. * @param initialM42 defines 2nd value of 4th row
  8311. * @param initialM43 defines 3rd value of 4th row
  8312. * @param initialM44 defines 4th value of 4th row
  8313. * @param result defines the target matrix
  8314. */
  8315. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  8316. var m = result._m;
  8317. m[0] = initialM11;
  8318. m[1] = initialM12;
  8319. m[2] = initialM13;
  8320. m[3] = initialM14;
  8321. m[4] = initialM21;
  8322. m[5] = initialM22;
  8323. m[6] = initialM23;
  8324. m[7] = initialM24;
  8325. m[8] = initialM31;
  8326. m[9] = initialM32;
  8327. m[10] = initialM33;
  8328. m[11] = initialM34;
  8329. m[12] = initialM41;
  8330. m[13] = initialM42;
  8331. m[14] = initialM43;
  8332. m[15] = initialM44;
  8333. result._markAsUpdated();
  8334. };
  8335. /**
  8336. * Creates new matrix from a list of values (16)
  8337. * @param initialM11 defines 1st value of 1st row
  8338. * @param initialM12 defines 2nd value of 1st row
  8339. * @param initialM13 defines 3rd value of 1st row
  8340. * @param initialM14 defines 4th value of 1st row
  8341. * @param initialM21 defines 1st value of 2nd row
  8342. * @param initialM22 defines 2nd value of 2nd row
  8343. * @param initialM23 defines 3rd value of 2nd row
  8344. * @param initialM24 defines 4th value of 2nd row
  8345. * @param initialM31 defines 1st value of 3rd row
  8346. * @param initialM32 defines 2nd value of 3rd row
  8347. * @param initialM33 defines 3rd value of 3rd row
  8348. * @param initialM34 defines 4th value of 3rd row
  8349. * @param initialM41 defines 1st value of 4th row
  8350. * @param initialM42 defines 2nd value of 4th row
  8351. * @param initialM43 defines 3rd value of 4th row
  8352. * @param initialM44 defines 4th value of 4th row
  8353. * @returns the new matrix
  8354. */
  8355. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  8356. var result = new Matrix();
  8357. var m = result._m;
  8358. m[0] = initialM11;
  8359. m[1] = initialM12;
  8360. m[2] = initialM13;
  8361. m[3] = initialM14;
  8362. m[4] = initialM21;
  8363. m[5] = initialM22;
  8364. m[6] = initialM23;
  8365. m[7] = initialM24;
  8366. m[8] = initialM31;
  8367. m[9] = initialM32;
  8368. m[10] = initialM33;
  8369. m[11] = initialM34;
  8370. m[12] = initialM41;
  8371. m[13] = initialM42;
  8372. m[14] = initialM43;
  8373. m[15] = initialM44;
  8374. result._markAsUpdated();
  8375. return result;
  8376. };
  8377. /**
  8378. * Creates a new matrix composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  8379. * @param scale defines the scale vector3
  8380. * @param rotation defines the rotation quaternion
  8381. * @param translation defines the translation vector3
  8382. * @returns a new matrix
  8383. */
  8384. Matrix.Compose = function (scale, rotation, translation) {
  8385. var result = new Matrix();
  8386. Matrix.ComposeToRef(scale, rotation, translation, result);
  8387. return result;
  8388. };
  8389. /**
  8390. * Sets a matrix to a value composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  8391. * @param scale defines the scale vector3
  8392. * @param rotation defines the rotation quaternion
  8393. * @param translation defines the translation vector3
  8394. * @param result defines the target matrix
  8395. */
  8396. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  8397. Matrix.ScalingToRef(scale.x, scale.y, scale.z, MathTmp.Matrix[1]);
  8398. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  8399. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  8400. result.setTranslation(translation);
  8401. };
  8402. /**
  8403. * Creates a new identity matrix
  8404. * @returns a new identity matrix
  8405. */
  8406. Matrix.Identity = function () {
  8407. var identity = 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);
  8408. identity._updateIdentityStatus(true);
  8409. return identity;
  8410. };
  8411. /**
  8412. * Creates a new identity matrix and stores the result in a given matrix
  8413. * @param result defines the target matrix
  8414. */
  8415. Matrix.IdentityToRef = function (result) {
  8416. 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);
  8417. result._updateIdentityStatus(true);
  8418. };
  8419. /**
  8420. * Creates a new zero matrix
  8421. * @returns a new zero matrix
  8422. */
  8423. Matrix.Zero = function () {
  8424. var zero = 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);
  8425. zero._updateIdentityStatus(false);
  8426. return zero;
  8427. };
  8428. /**
  8429. * Creates a new rotation matrix for "angle" radians around the X axis
  8430. * @param angle defines the angle (in radians) to use
  8431. * @return the new matrix
  8432. */
  8433. Matrix.RotationX = function (angle) {
  8434. var result = new Matrix();
  8435. Matrix.RotationXToRef(angle, result);
  8436. return result;
  8437. };
  8438. /**
  8439. * Creates a new matrix as the invert of a given matrix
  8440. * @param source defines the source matrix
  8441. * @returns the new matrix
  8442. */
  8443. Matrix.Invert = function (source) {
  8444. var result = new Matrix();
  8445. source.invertToRef(result);
  8446. return result;
  8447. };
  8448. /**
  8449. * Creates a new rotation matrix for "angle" radians around the X axis and stores it in a given matrix
  8450. * @param angle defines the angle (in radians) to use
  8451. * @param result defines the target matrix
  8452. */
  8453. Matrix.RotationXToRef = function (angle, result) {
  8454. var s = Math.sin(angle);
  8455. var c = Math.cos(angle);
  8456. Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, c, s, 0.0, 0.0, -s, c, 0.0, 0.0, 0.0, 0.0, 1.0, result);
  8457. result._updateIdentityStatus(c === 1 && s === 0);
  8458. };
  8459. /**
  8460. * Creates a new rotation matrix for "angle" radians around the Y axis
  8461. * @param angle defines the angle (in radians) to use
  8462. * @return the new matrix
  8463. */
  8464. Matrix.RotationY = function (angle) {
  8465. var result = new Matrix();
  8466. Matrix.RotationYToRef(angle, result);
  8467. return result;
  8468. };
  8469. /**
  8470. * Creates a new rotation matrix for "angle" radians around the Y axis and stores it in a given matrix
  8471. * @param angle defines the angle (in radians) to use
  8472. * @param result defines the target matrix
  8473. */
  8474. Matrix.RotationYToRef = function (angle, result) {
  8475. var s = Math.sin(angle);
  8476. var c = Math.cos(angle);
  8477. Matrix.FromValuesToRef(c, 0.0, -s, 0.0, 0.0, 1.0, 0.0, 0.0, s, 0.0, c, 0.0, 0.0, 0.0, 0.0, 1.0, result);
  8478. result._updateIdentityStatus(c === 1 && s === 0);
  8479. };
  8480. /**
  8481. * Creates a new rotation matrix for "angle" radians around the Z axis
  8482. * @param angle defines the angle (in radians) to use
  8483. * @return the new matrix
  8484. */
  8485. Matrix.RotationZ = function (angle) {
  8486. var result = new Matrix();
  8487. Matrix.RotationZToRef(angle, result);
  8488. return result;
  8489. };
  8490. /**
  8491. * Creates a new rotation matrix for "angle" radians around the Z axis and stores it in a given matrix
  8492. * @param angle defines the angle (in radians) to use
  8493. * @param result defines the target matrix
  8494. */
  8495. Matrix.RotationZToRef = function (angle, result) {
  8496. var s = Math.sin(angle);
  8497. var c = Math.cos(angle);
  8498. Matrix.FromValuesToRef(c, s, 0.0, 0.0, -s, c, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, result);
  8499. result._updateIdentityStatus(c === 1 && s === 0);
  8500. };
  8501. /**
  8502. * Creates a new rotation matrix for "angle" radians around the given axis
  8503. * @param axis defines the axis to use
  8504. * @param angle defines the angle (in radians) to use
  8505. * @return the new matrix
  8506. */
  8507. Matrix.RotationAxis = function (axis, angle) {
  8508. var result = new Matrix();
  8509. Matrix.RotationAxisToRef(axis, angle, result);
  8510. return result;
  8511. };
  8512. /**
  8513. * Creates a new rotation matrix for "angle" radians around the given axis and stores it in a given matrix
  8514. * @param axis defines the axis to use
  8515. * @param angle defines the angle (in radians) to use
  8516. * @param result defines the target matrix
  8517. */
  8518. Matrix.RotationAxisToRef = function (axis, angle, result) {
  8519. var s = Math.sin(-angle);
  8520. var c = Math.cos(-angle);
  8521. var c1 = 1 - c;
  8522. axis.normalize();
  8523. var m = result._m;
  8524. m[0] = (axis.x * axis.x) * c1 + c;
  8525. m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  8526. m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  8527. m[3] = 0.0;
  8528. m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  8529. m[5] = (axis.y * axis.y) * c1 + c;
  8530. m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  8531. m[7] = 0.0;
  8532. m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  8533. m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  8534. m[10] = (axis.z * axis.z) * c1 + c;
  8535. m[11] = 0.0;
  8536. m[12] = 0.0;
  8537. m[13] = 0.0;
  8538. m[14] = 0.0;
  8539. m[15] = 1.0;
  8540. result._markAsUpdated();
  8541. };
  8542. /**
  8543. * Creates a rotation matrix
  8544. * @param yaw defines the yaw angle in radians (Y axis)
  8545. * @param pitch defines the pitch angle in radians (X axis)
  8546. * @param roll defines the roll angle in radians (X axis)
  8547. * @returns the new rotation matrix
  8548. */
  8549. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  8550. var result = new Matrix();
  8551. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  8552. return result;
  8553. };
  8554. /**
  8555. * Creates a rotation matrix and stores it in a given matrix
  8556. * @param yaw defines the yaw angle in radians (Y axis)
  8557. * @param pitch defines the pitch angle in radians (X axis)
  8558. * @param roll defines the roll angle in radians (X axis)
  8559. * @param result defines the target matrix
  8560. */
  8561. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  8562. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, MathTmp.Quaternion[0]);
  8563. MathTmp.Quaternion[0].toRotationMatrix(result);
  8564. };
  8565. /**
  8566. * Creates a scaling matrix
  8567. * @param x defines the scale factor on X axis
  8568. * @param y defines the scale factor on Y axis
  8569. * @param z defines the scale factor on Z axis
  8570. * @returns the new matrix
  8571. */
  8572. Matrix.Scaling = function (x, y, z) {
  8573. var result = new Matrix();
  8574. Matrix.ScalingToRef(x, y, z, result);
  8575. return result;
  8576. };
  8577. /**
  8578. * Creates a scaling matrix and stores it in a given matrix
  8579. * @param x defines the scale factor on X axis
  8580. * @param y defines the scale factor on Y axis
  8581. * @param z defines the scale factor on Z axis
  8582. * @param result defines the target matrix
  8583. */
  8584. Matrix.ScalingToRef = function (x, y, z, result) {
  8585. Matrix.FromValuesToRef(x, 0.0, 0.0, 0.0, 0.0, y, 0.0, 0.0, 0.0, 0.0, z, 0.0, 0.0, 0.0, 0.0, 1.0, result);
  8586. result._updateIdentityStatus(x === 1 && y === 1 && z === 1);
  8587. };
  8588. /**
  8589. * Creates a translation matrix
  8590. * @param x defines the translation on X axis
  8591. * @param y defines the translation on Y axis
  8592. * @param z defines the translationon Z axis
  8593. * @returns the new matrix
  8594. */
  8595. Matrix.Translation = function (x, y, z) {
  8596. var result = new Matrix();
  8597. Matrix.TranslationToRef(x, y, z, result);
  8598. return result;
  8599. };
  8600. /**
  8601. * Creates a translation matrix and stores it in a given matrix
  8602. * @param x defines the translation on X axis
  8603. * @param y defines the translation on Y axis
  8604. * @param z defines the translationon Z axis
  8605. * @param result defines the target matrix
  8606. */
  8607. Matrix.TranslationToRef = function (x, y, z, result) {
  8608. 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);
  8609. result._updateIdentityStatus(x === 0 && y === 0 && z === 0);
  8610. };
  8611. /**
  8612. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  8613. * @param startValue defines the start value
  8614. * @param endValue defines the end value
  8615. * @param gradient defines the gradient factor
  8616. * @returns the new matrix
  8617. */
  8618. Matrix.Lerp = function (startValue, endValue, gradient) {
  8619. var result = new Matrix();
  8620. Matrix.LerpToRef(startValue, endValue, gradient, result);
  8621. return result;
  8622. };
  8623. /**
  8624. * Set the given matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  8625. * @param startValue defines the start value
  8626. * @param endValue defines the end value
  8627. * @param gradient defines the gradient factor
  8628. * @param result defines the Matrix object where to store data
  8629. */
  8630. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  8631. var resultM = result._m;
  8632. var startM = startValue.m;
  8633. var endM = endValue.m;
  8634. for (var index = 0; index < 16; index++) {
  8635. resultM[index] = startM[index] * (1.0 - gradient) + endM[index] * gradient;
  8636. }
  8637. result._markAsUpdated();
  8638. };
  8639. /**
  8640. * Builds a new matrix whose values are computed by:
  8641. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  8642. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  8643. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  8644. * @param startValue defines the first matrix
  8645. * @param endValue defines the second matrix
  8646. * @param gradient defines the gradient between the two matrices
  8647. * @returns the new matrix
  8648. */
  8649. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  8650. var result = new Matrix();
  8651. Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  8652. return result;
  8653. };
  8654. /**
  8655. * Update a matrix to values which are computed by:
  8656. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  8657. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  8658. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  8659. * @param startValue defines the first matrix
  8660. * @param endValue defines the second matrix
  8661. * @param gradient defines the gradient between the two matrices
  8662. * @param result defines the target matrix
  8663. */
  8664. Matrix.DecomposeLerpToRef = function (startValue, endValue, gradient, result) {
  8665. var startScale = MathTmp.Vector3[0];
  8666. var startRotation = MathTmp.Quaternion[0];
  8667. var startTranslation = MathTmp.Vector3[1];
  8668. startValue.decompose(startScale, startRotation, startTranslation);
  8669. var endScale = MathTmp.Vector3[2];
  8670. var endRotation = MathTmp.Quaternion[1];
  8671. var endTranslation = MathTmp.Vector3[3];
  8672. endValue.decompose(endScale, endRotation, endTranslation);
  8673. var resultScale = MathTmp.Vector3[4];
  8674. Vector3.LerpToRef(startScale, endScale, gradient, resultScale);
  8675. var resultRotation = MathTmp.Quaternion[2];
  8676. Quaternion.SlerpToRef(startRotation, endRotation, gradient, resultRotation);
  8677. var resultTranslation = MathTmp.Vector3[5];
  8678. Vector3.LerpToRef(startTranslation, endTranslation, gradient, resultTranslation);
  8679. Matrix.ComposeToRef(resultScale, resultRotation, resultTranslation, result);
  8680. };
  8681. /**
  8682. * 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"
  8683. * This function works in left handed mode
  8684. * @param eye defines the final position of the entity
  8685. * @param target defines where the entity should look at
  8686. * @param up defines the up vector for the entity
  8687. * @returns the new matrix
  8688. */
  8689. Matrix.LookAtLH = function (eye, target, up) {
  8690. var result = new Matrix();
  8691. Matrix.LookAtLHToRef(eye, target, up, result);
  8692. return result;
  8693. };
  8694. /**
  8695. * 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".
  8696. * This function works in left handed mode
  8697. * @param eye defines the final position of the entity
  8698. * @param target defines where the entity should look at
  8699. * @param up defines the up vector for the entity
  8700. * @param result defines the target matrix
  8701. */
  8702. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  8703. var xAxis = MathTmp.Vector3[0];
  8704. var yAxis = MathTmp.Vector3[1];
  8705. var zAxis = MathTmp.Vector3[2];
  8706. // Z axis
  8707. target.subtractToRef(eye, zAxis);
  8708. zAxis.normalize();
  8709. // X axis
  8710. Vector3.CrossToRef(up, zAxis, xAxis);
  8711. var xSquareLength = xAxis.lengthSquared();
  8712. if (xSquareLength === 0) {
  8713. xAxis.x = 1.0;
  8714. }
  8715. else {
  8716. xAxis.normalizeFromLength(Math.sqrt(xSquareLength));
  8717. }
  8718. // Y axis
  8719. Vector3.CrossToRef(zAxis, xAxis, yAxis);
  8720. yAxis.normalize();
  8721. // Eye angles
  8722. var ex = -Vector3.Dot(xAxis, eye);
  8723. var ey = -Vector3.Dot(yAxis, eye);
  8724. var ez = -Vector3.Dot(zAxis, eye);
  8725. Matrix.FromValuesToRef(xAxis.x, yAxis.x, zAxis.x, 0.0, xAxis.y, yAxis.y, zAxis.y, 0.0, xAxis.z, yAxis.z, zAxis.z, 0.0, ex, ey, ez, 1.0, result);
  8726. };
  8727. /**
  8728. * 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"
  8729. * This function works in right handed mode
  8730. * @param eye defines the final position of the entity
  8731. * @param target defines where the entity should look at
  8732. * @param up defines the up vector for the entity
  8733. * @returns the new matrix
  8734. */
  8735. Matrix.LookAtRH = function (eye, target, up) {
  8736. var result = new Matrix();
  8737. Matrix.LookAtRHToRef(eye, target, up, result);
  8738. return result;
  8739. };
  8740. /**
  8741. * 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".
  8742. * This function works in right handed mode
  8743. * @param eye defines the final position of the entity
  8744. * @param target defines where the entity should look at
  8745. * @param up defines the up vector for the entity
  8746. * @param result defines the target matrix
  8747. */
  8748. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  8749. var xAxis = MathTmp.Vector3[0];
  8750. var yAxis = MathTmp.Vector3[1];
  8751. var zAxis = MathTmp.Vector3[2];
  8752. // Z axis
  8753. eye.subtractToRef(target, zAxis);
  8754. zAxis.normalize();
  8755. // X axis
  8756. Vector3.CrossToRef(up, zAxis, xAxis);
  8757. var xSquareLength = xAxis.lengthSquared();
  8758. if (xSquareLength === 0) {
  8759. xAxis.x = 1.0;
  8760. }
  8761. else {
  8762. xAxis.normalizeFromLength(Math.sqrt(xSquareLength));
  8763. }
  8764. // Y axis
  8765. Vector3.CrossToRef(zAxis, xAxis, yAxis);
  8766. yAxis.normalize();
  8767. // Eye angles
  8768. var ex = -Vector3.Dot(xAxis, eye);
  8769. var ey = -Vector3.Dot(yAxis, eye);
  8770. var ez = -Vector3.Dot(zAxis, eye);
  8771. Matrix.FromValuesToRef(xAxis.x, yAxis.x, zAxis.x, 0.0, xAxis.y, yAxis.y, zAxis.y, 0.0, xAxis.z, yAxis.z, zAxis.z, 0.0, ex, ey, ez, 1.0, result);
  8772. };
  8773. /**
  8774. * Create a left-handed orthographic projection matrix
  8775. * @param width defines the viewport width
  8776. * @param height defines the viewport height
  8777. * @param znear defines the near clip plane
  8778. * @param zfar defines the far clip plane
  8779. * @returns a new matrix as a left-handed orthographic projection matrix
  8780. */
  8781. Matrix.OrthoLH = function (width, height, znear, zfar) {
  8782. var matrix = new Matrix();
  8783. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  8784. return matrix;
  8785. };
  8786. /**
  8787. * Store a left-handed orthographic projection to a given matrix
  8788. * @param width defines the viewport width
  8789. * @param height defines the viewport height
  8790. * @param znear defines the near clip plane
  8791. * @param zfar defines the far clip plane
  8792. * @param result defines the target matrix
  8793. */
  8794. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  8795. var n = znear;
  8796. var f = zfar;
  8797. var a = 2.0 / width;
  8798. var b = 2.0 / height;
  8799. var c = 2.0 / (f - n);
  8800. var d = -(f + n) / (f - n);
  8801. 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);
  8802. result._updateIdentityStatus(a === 1 && b === 1 && c === 1 && d === 0);
  8803. };
  8804. /**
  8805. * Create a left-handed orthographic projection matrix
  8806. * @param left defines the viewport left coordinate
  8807. * @param right defines the viewport right coordinate
  8808. * @param bottom defines the viewport bottom coordinate
  8809. * @param top defines the viewport top coordinate
  8810. * @param znear defines the near clip plane
  8811. * @param zfar defines the far clip plane
  8812. * @returns a new matrix as a left-handed orthographic projection matrix
  8813. */
  8814. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  8815. var matrix = new Matrix();
  8816. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  8817. return matrix;
  8818. };
  8819. /**
  8820. * Stores a left-handed orthographic projection into a given matrix
  8821. * @param left defines the viewport left coordinate
  8822. * @param right defines the viewport right coordinate
  8823. * @param bottom defines the viewport bottom coordinate
  8824. * @param top defines the viewport top coordinate
  8825. * @param znear defines the near clip plane
  8826. * @param zfar defines the far clip plane
  8827. * @param result defines the target matrix
  8828. */
  8829. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  8830. var n = znear;
  8831. var f = zfar;
  8832. var a = 2.0 / (right - left);
  8833. var b = 2.0 / (top - bottom);
  8834. var c = 2.0 / (f - n);
  8835. var d = -(f + n) / (f - n);
  8836. var i0 = (left + right) / (left - right);
  8837. var i1 = (top + bottom) / (bottom - top);
  8838. 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);
  8839. result._markAsUpdated();
  8840. };
  8841. /**
  8842. * Creates a right-handed orthographic projection matrix
  8843. * @param left defines the viewport left coordinate
  8844. * @param right defines the viewport right coordinate
  8845. * @param bottom defines the viewport bottom coordinate
  8846. * @param top defines the viewport top coordinate
  8847. * @param znear defines the near clip plane
  8848. * @param zfar defines the far clip plane
  8849. * @returns a new matrix as a right-handed orthographic projection matrix
  8850. */
  8851. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  8852. var matrix = new Matrix();
  8853. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  8854. return matrix;
  8855. };
  8856. /**
  8857. * Stores a right-handed orthographic projection into a given matrix
  8858. * @param left defines the viewport left coordinate
  8859. * @param right defines the viewport right coordinate
  8860. * @param bottom defines the viewport bottom coordinate
  8861. * @param top defines the viewport top coordinate
  8862. * @param znear defines the near clip plane
  8863. * @param zfar defines the far clip plane
  8864. * @param result defines the target matrix
  8865. */
  8866. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  8867. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  8868. result._m[10] *= -1; // No need to call _markAsUpdated as previous function already called it and let _isIdentityDirty to true
  8869. };
  8870. /**
  8871. * Creates a left-handed perspective projection matrix
  8872. * @param width defines the viewport width
  8873. * @param height defines the viewport height
  8874. * @param znear defines the near clip plane
  8875. * @param zfar defines the far clip plane
  8876. * @returns a new matrix as a left-handed perspective projection matrix
  8877. */
  8878. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  8879. var matrix = new Matrix();
  8880. var n = znear;
  8881. var f = zfar;
  8882. var a = 2.0 * n / width;
  8883. var b = 2.0 * n / height;
  8884. var c = (f + n) / (f - n);
  8885. var d = -2.0 * f * n / (f - n);
  8886. 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);
  8887. matrix._updateIdentityStatus(false);
  8888. return matrix;
  8889. };
  8890. /**
  8891. * Creates a left-handed perspective projection matrix
  8892. * @param fov defines the horizontal field of view
  8893. * @param aspect defines the aspect ratio
  8894. * @param znear defines the near clip plane
  8895. * @param zfar defines the far clip plane
  8896. * @returns a new matrix as a left-handed perspective projection matrix
  8897. */
  8898. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  8899. var matrix = new Matrix();
  8900. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  8901. return matrix;
  8902. };
  8903. /**
  8904. * Stores a left-handed perspective projection into a given matrix
  8905. * @param fov defines the horizontal field of view
  8906. * @param aspect defines the aspect ratio
  8907. * @param znear defines the near clip plane
  8908. * @param zfar defines the far clip plane
  8909. * @param result defines the target matrix
  8910. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  8911. */
  8912. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  8913. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  8914. var n = znear;
  8915. var f = zfar;
  8916. var t = 1.0 / (Math.tan(fov * 0.5));
  8917. var a = isVerticalFovFixed ? (t / aspect) : t;
  8918. var b = isVerticalFovFixed ? t : (t * aspect);
  8919. var c = (f + n) / (f - n);
  8920. var d = -2.0 * f * n / (f - n);
  8921. 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);
  8922. result._updateIdentityStatus(false);
  8923. };
  8924. /**
  8925. * Creates a right-handed perspective projection matrix
  8926. * @param fov defines the horizontal field of view
  8927. * @param aspect defines the aspect ratio
  8928. * @param znear defines the near clip plane
  8929. * @param zfar defines the far clip plane
  8930. * @returns a new matrix as a right-handed perspective projection matrix
  8931. */
  8932. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  8933. var matrix = new Matrix();
  8934. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  8935. return matrix;
  8936. };
  8937. /**
  8938. * Stores a right-handed perspective projection into a given matrix
  8939. * @param fov defines the horizontal field of view
  8940. * @param aspect defines the aspect ratio
  8941. * @param znear defines the near clip plane
  8942. * @param zfar defines the far clip plane
  8943. * @param result defines the target matrix
  8944. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  8945. */
  8946. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  8947. //alternatively this could be expressed as:
  8948. // m = PerspectiveFovLHToRef
  8949. // m[10] *= -1.0;
  8950. // m[11] *= -1.0;
  8951. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  8952. var n = znear;
  8953. var f = zfar;
  8954. var t = 1.0 / (Math.tan(fov * 0.5));
  8955. var a = isVerticalFovFixed ? (t / aspect) : t;
  8956. var b = isVerticalFovFixed ? t : (t * aspect);
  8957. var c = -(f + n) / (f - n);
  8958. var d = -2 * f * n / (f - n);
  8959. 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);
  8960. result._updateIdentityStatus(false);
  8961. };
  8962. /**
  8963. * Stores a perspective projection for WebVR info a given matrix
  8964. * @param fov defines the field of view
  8965. * @param znear defines the near clip plane
  8966. * @param zfar defines the far clip plane
  8967. * @param result defines the target matrix
  8968. * @param rightHanded defines if the matrix must be in right-handed mode (false by default)
  8969. */
  8970. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  8971. if (rightHanded === void 0) { rightHanded = false; }
  8972. var rightHandedFactor = rightHanded ? -1 : 1;
  8973. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  8974. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  8975. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  8976. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  8977. var xScale = 2.0 / (leftTan + rightTan);
  8978. var yScale = 2.0 / (upTan + downTan);
  8979. var m = result._m;
  8980. m[0] = xScale;
  8981. m[1] = m[2] = m[3] = m[4] = 0.0;
  8982. m[5] = yScale;
  8983. m[6] = m[7] = 0.0;
  8984. m[8] = ((leftTan - rightTan) * xScale * 0.5);
  8985. m[9] = -((upTan - downTan) * yScale * 0.5);
  8986. m[10] = -zfar / (znear - zfar);
  8987. m[11] = 1.0 * rightHandedFactor;
  8988. m[12] = m[13] = m[15] = 0.0;
  8989. m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  8990. result._markAsUpdated();
  8991. };
  8992. /**
  8993. * Computes a complete transformation matrix
  8994. * @param viewport defines the viewport to use
  8995. * @param world defines the world matrix
  8996. * @param view defines the view matrix
  8997. * @param projection defines the projection matrix
  8998. * @param zmin defines the near clip plane
  8999. * @param zmax defines the far clip plane
  9000. * @returns the transformation matrix
  9001. */
  9002. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  9003. var cw = viewport.width;
  9004. var ch = viewport.height;
  9005. var cx = viewport.x;
  9006. var cy = viewport.y;
  9007. 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.0);
  9008. var matrix = MathTmp.Matrix[0];
  9009. world.multiplyToRef(view, matrix);
  9010. matrix.multiplyToRef(projection, matrix);
  9011. return matrix.multiply(viewportMatrix);
  9012. };
  9013. /**
  9014. * Extracts a 2x2 matrix from a given matrix and store the result in a Float32Array
  9015. * @param matrix defines the matrix to use
  9016. * @returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the given matrix
  9017. */
  9018. Matrix.GetAsMatrix2x2 = function (matrix) {
  9019. var m = matrix.m;
  9020. return new Float32Array([m[0], m[1], m[4], m[5]]);
  9021. };
  9022. /**
  9023. * Extracts a 3x3 matrix from a given matrix and store the result in a Float32Array
  9024. * @param matrix defines the matrix to use
  9025. * @returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the given matrix
  9026. */
  9027. Matrix.GetAsMatrix3x3 = function (matrix) {
  9028. var m = matrix.m;
  9029. return new Float32Array([
  9030. m[0], m[1], m[2],
  9031. m[4], m[5], m[6],
  9032. m[8], m[9], m[10]
  9033. ]);
  9034. };
  9035. /**
  9036. * Compute the transpose of a given matrix
  9037. * @param matrix defines the matrix to transpose
  9038. * @returns the new matrix
  9039. */
  9040. Matrix.Transpose = function (matrix) {
  9041. var result = new Matrix();
  9042. Matrix.TransposeToRef(matrix, result);
  9043. return result;
  9044. };
  9045. /**
  9046. * Compute the transpose of a matrix and store it in a target matrix
  9047. * @param matrix defines the matrix to transpose
  9048. * @param result defines the target matrix
  9049. */
  9050. Matrix.TransposeToRef = function (matrix, result) {
  9051. var rm = result._m;
  9052. var mm = matrix.m;
  9053. rm[0] = mm[0];
  9054. rm[1] = mm[4];
  9055. rm[2] = mm[8];
  9056. rm[3] = mm[12];
  9057. rm[4] = mm[1];
  9058. rm[5] = mm[5];
  9059. rm[6] = mm[9];
  9060. rm[7] = mm[13];
  9061. rm[8] = mm[2];
  9062. rm[9] = mm[6];
  9063. rm[10] = mm[10];
  9064. rm[11] = mm[14];
  9065. rm[12] = mm[3];
  9066. rm[13] = mm[7];
  9067. rm[14] = mm[11];
  9068. rm[15] = mm[15];
  9069. // identity-ness does not change when transposing
  9070. result._updateIdentityStatus(matrix._isIdentity, matrix._isIdentityDirty);
  9071. };
  9072. /**
  9073. * Computes a reflection matrix from a plane
  9074. * @param plane defines the reflection plane
  9075. * @returns a new matrix
  9076. */
  9077. Matrix.Reflection = function (plane) {
  9078. var matrix = new Matrix();
  9079. Matrix.ReflectionToRef(plane, matrix);
  9080. return matrix;
  9081. };
  9082. /**
  9083. * Computes a reflection matrix from a plane
  9084. * @param plane defines the reflection plane
  9085. * @param result defines the target matrix
  9086. */
  9087. Matrix.ReflectionToRef = function (plane, result) {
  9088. plane.normalize();
  9089. var x = plane.normal.x;
  9090. var y = plane.normal.y;
  9091. var z = plane.normal.z;
  9092. var temp = -2 * x;
  9093. var temp2 = -2 * y;
  9094. var temp3 = -2 * z;
  9095. Matrix.FromValuesToRef(temp * x + 1, temp2 * x, temp3 * x, 0.0, temp * y, temp2 * y + 1, temp3 * y, 0.0, temp * z, temp2 * z, temp3 * z + 1, 0.0, temp * plane.d, temp2 * plane.d, temp3 * plane.d, 1.0, result);
  9096. };
  9097. /**
  9098. * Sets the given matrix as a rotation matrix composed from the 3 left handed axes
  9099. * @param xaxis defines the value of the 1st axis
  9100. * @param yaxis defines the value of the 2nd axis
  9101. * @param zaxis defines the value of the 3rd axis
  9102. * @param result defines the target matrix
  9103. */
  9104. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  9105. Matrix.FromValuesToRef(xaxis.x, xaxis.y, xaxis.z, 0.0, yaxis.x, yaxis.y, yaxis.z, 0.0, zaxis.x, zaxis.y, zaxis.z, 0.0, 0.0, 0.0, 0.0, 1.0, result);
  9106. };
  9107. /**
  9108. * Creates a rotation matrix from a quaternion and stores it in a target matrix
  9109. * @param quat defines the quaternion to use
  9110. * @param result defines the target matrix
  9111. */
  9112. Matrix.FromQuaternionToRef = function (quat, result) {
  9113. var xx = quat.x * quat.x;
  9114. var yy = quat.y * quat.y;
  9115. var zz = quat.z * quat.z;
  9116. var xy = quat.x * quat.y;
  9117. var zw = quat.z * quat.w;
  9118. var zx = quat.z * quat.x;
  9119. var yw = quat.y * quat.w;
  9120. var yz = quat.y * quat.z;
  9121. var xw = quat.x * quat.w;
  9122. result._m[0] = 1.0 - (2.0 * (yy + zz));
  9123. result._m[1] = 2.0 * (xy + zw);
  9124. result._m[2] = 2.0 * (zx - yw);
  9125. result._m[3] = 0.0;
  9126. result._m[4] = 2.0 * (xy - zw);
  9127. result._m[5] = 1.0 - (2.0 * (zz + xx));
  9128. result._m[6] = 2.0 * (yz + xw);
  9129. result._m[7] = 0.0;
  9130. result._m[8] = 2.0 * (zx + yw);
  9131. result._m[9] = 2.0 * (yz - xw);
  9132. result._m[10] = 1.0 - (2.0 * (yy + xx));
  9133. result._m[11] = 0.0;
  9134. result._m[12] = 0.0;
  9135. result._m[13] = 0.0;
  9136. result._m[14] = 0.0;
  9137. result._m[15] = 1.0;
  9138. result._markAsUpdated();
  9139. };
  9140. Matrix._updateFlagSeed = 0;
  9141. Matrix._identityReadOnly = Matrix.Identity();
  9142. return Matrix;
  9143. }());
  9144. BABYLON.Matrix = Matrix;
  9145. /**
  9146. * Represens a plane by the equation ax + by + cz + d = 0
  9147. */
  9148. var Plane = /** @class */ (function () {
  9149. /**
  9150. * Creates a Plane object according to the given floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  9151. * @param a a component of the plane
  9152. * @param b b component of the plane
  9153. * @param c c component of the plane
  9154. * @param d d component of the plane
  9155. */
  9156. function Plane(a, b, c, d) {
  9157. this.normal = new Vector3(a, b, c);
  9158. this.d = d;
  9159. }
  9160. /**
  9161. * @returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  9162. */
  9163. Plane.prototype.asArray = function () {
  9164. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  9165. };
  9166. // Methods
  9167. /**
  9168. * @returns a new plane copied from the current Plane.
  9169. */
  9170. Plane.prototype.clone = function () {
  9171. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  9172. };
  9173. /**
  9174. * @returns the string "Plane".
  9175. */
  9176. Plane.prototype.getClassName = function () {
  9177. return "Plane";
  9178. };
  9179. /**
  9180. * @returns the Plane hash code.
  9181. */
  9182. Plane.prototype.getHashCode = function () {
  9183. var hash = this.normal.getHashCode();
  9184. hash = (hash * 397) ^ (this.d || 0);
  9185. return hash;
  9186. };
  9187. /**
  9188. * Normalize the current Plane in place.
  9189. * @returns the updated Plane.
  9190. */
  9191. Plane.prototype.normalize = function () {
  9192. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  9193. var magnitude = 0.0;
  9194. if (norm !== 0) {
  9195. magnitude = 1.0 / norm;
  9196. }
  9197. this.normal.x *= magnitude;
  9198. this.normal.y *= magnitude;
  9199. this.normal.z *= magnitude;
  9200. this.d *= magnitude;
  9201. return this;
  9202. };
  9203. /**
  9204. * Applies a transformation the plane and returns the result
  9205. * @param transformation the transformation matrix to be applied to the plane
  9206. * @returns a new Plane as the result of the transformation of the current Plane by the given matrix.
  9207. */
  9208. Plane.prototype.transform = function (transformation) {
  9209. var transposedMatrix = MathTmp.Matrix[0];
  9210. Matrix.TransposeToRef(transformation, transposedMatrix);
  9211. var m = transposedMatrix.m;
  9212. var x = this.normal.x;
  9213. var y = this.normal.y;
  9214. var z = this.normal.z;
  9215. var d = this.d;
  9216. var normalX = x * m[0] + y * m[1] + z * m[2] + d * m[3];
  9217. var normalY = x * m[4] + y * m[5] + z * m[6] + d * m[7];
  9218. var normalZ = x * m[8] + y * m[9] + z * m[10] + d * m[11];
  9219. var finalD = x * m[12] + y * m[13] + z * m[14] + d * m[15];
  9220. return new Plane(normalX, normalY, normalZ, finalD);
  9221. };
  9222. /**
  9223. * Calcualtte the dot product between the point and the plane normal
  9224. * @param point point to calculate the dot product with
  9225. * @returns the dot product (float) of the point coordinates and the plane normal.
  9226. */
  9227. Plane.prototype.dotCoordinate = function (point) {
  9228. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  9229. };
  9230. /**
  9231. * Updates the current Plane from the plane defined by the three given points.
  9232. * @param point1 one of the points used to contruct the plane
  9233. * @param point2 one of the points used to contruct the plane
  9234. * @param point3 one of the points used to contruct the plane
  9235. * @returns the updated Plane.
  9236. */
  9237. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  9238. var x1 = point2.x - point1.x;
  9239. var y1 = point2.y - point1.y;
  9240. var z1 = point2.z - point1.z;
  9241. var x2 = point3.x - point1.x;
  9242. var y2 = point3.y - point1.y;
  9243. var z2 = point3.z - point1.z;
  9244. var yz = (y1 * z2) - (z1 * y2);
  9245. var xz = (z1 * x2) - (x1 * z2);
  9246. var xy = (x1 * y2) - (y1 * x2);
  9247. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  9248. var invPyth;
  9249. if (pyth !== 0) {
  9250. invPyth = 1.0 / pyth;
  9251. }
  9252. else {
  9253. invPyth = 0.0;
  9254. }
  9255. this.normal.x = yz * invPyth;
  9256. this.normal.y = xz * invPyth;
  9257. this.normal.z = xy * invPyth;
  9258. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  9259. return this;
  9260. };
  9261. /**
  9262. * Checks if the plane is facing a given direction
  9263. * @param direction the direction to check if the plane is facing
  9264. * @param epsilon value the dot product is compared against (returns true if dot <= epsilon)
  9265. * @returns True is the vector "direction" is the same side than the plane normal.
  9266. */
  9267. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  9268. var dot = Vector3.Dot(this.normal, direction);
  9269. return (dot <= epsilon);
  9270. };
  9271. /**
  9272. * Calculates the distance to a point
  9273. * @param point point to calculate distance to
  9274. * @returns the signed distance (float) from the given point to the Plane.
  9275. */
  9276. Plane.prototype.signedDistanceTo = function (point) {
  9277. return Vector3.Dot(point, this.normal) + this.d;
  9278. };
  9279. // Statics
  9280. /**
  9281. * Creates a plane from an array
  9282. * @param array the array to create a plane from
  9283. * @returns a new Plane from the given array.
  9284. */
  9285. Plane.FromArray = function (array) {
  9286. return new Plane(array[0], array[1], array[2], array[3]);
  9287. };
  9288. /**
  9289. * Creates a plane from three points
  9290. * @param point1 point used to create the plane
  9291. * @param point2 point used to create the plane
  9292. * @param point3 point used to create the plane
  9293. * @returns a new Plane defined by the three given points.
  9294. */
  9295. Plane.FromPoints = function (point1, point2, point3) {
  9296. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  9297. result.copyFromPoints(point1, point2, point3);
  9298. return result;
  9299. };
  9300. /**
  9301. * Creates a plane from an origin point and a normal
  9302. * @param origin origin of the plane to be constructed
  9303. * @param normal normal of the plane to be constructed
  9304. * @returns a new Plane the normal vector to this plane at the given origin point.
  9305. * Note : the vector "normal" is updated because normalized.
  9306. */
  9307. Plane.FromPositionAndNormal = function (origin, normal) {
  9308. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  9309. normal.normalize();
  9310. result.normal = normal;
  9311. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  9312. return result;
  9313. };
  9314. /**
  9315. * Calculates the distance from a plane and a point
  9316. * @param origin origin of the plane to be constructed
  9317. * @param normal normal of the plane to be constructed
  9318. * @param point point to calculate distance to
  9319. * @returns the signed distance between the plane defined by the normal vector at the "origin"" point and the given other point.
  9320. */
  9321. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  9322. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  9323. return Vector3.Dot(point, normal) + d;
  9324. };
  9325. return Plane;
  9326. }());
  9327. BABYLON.Plane = Plane;
  9328. /**
  9329. * Class used to represent a viewport on screen
  9330. */
  9331. var Viewport = /** @class */ (function () {
  9332. /**
  9333. * Creates a Viewport object located at (x, y) and sized (width, height)
  9334. * @param x defines viewport left coordinate
  9335. * @param y defines viewport top coordinate
  9336. * @param width defines the viewport width
  9337. * @param height defines the viewport height
  9338. */
  9339. function Viewport(
  9340. /** viewport left coordinate */
  9341. x,
  9342. /** viewport top coordinate */
  9343. y,
  9344. /**viewport width */
  9345. width,
  9346. /** viewport height */
  9347. height) {
  9348. this.x = x;
  9349. this.y = y;
  9350. this.width = width;
  9351. this.height = height;
  9352. }
  9353. /**
  9354. * Creates a new viewport using absolute sizing (from 0-> width, 0-> height instead of 0->1)
  9355. * @param renderWidthOrEngine defines either an engine or the rendering width
  9356. * @param renderHeight defines the rendering height
  9357. * @returns a new Viewport
  9358. */
  9359. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  9360. if (renderWidthOrEngine.getRenderWidth) {
  9361. var engine = renderWidthOrEngine;
  9362. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  9363. }
  9364. var renderWidth = renderWidthOrEngine;
  9365. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  9366. };
  9367. /**
  9368. * Returns a new Viewport copied from the current one
  9369. * @returns a new Viewport
  9370. */
  9371. Viewport.prototype.clone = function () {
  9372. return new Viewport(this.x, this.y, this.width, this.height);
  9373. };
  9374. return Viewport;
  9375. }());
  9376. BABYLON.Viewport = Viewport;
  9377. /**
  9378. * Reprasents a camera frustum
  9379. */
  9380. var Frustum = /** @class */ (function () {
  9381. function Frustum() {
  9382. }
  9383. /**
  9384. * Gets the planes representing the frustum
  9385. * @param transform matrix to be applied to the returned planes
  9386. * @returns a new array of 6 Frustum planes computed by the given transformation matrix.
  9387. */
  9388. Frustum.GetPlanes = function (transform) {
  9389. var frustumPlanes = [];
  9390. for (var index = 0; index < 6; index++) {
  9391. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  9392. }
  9393. Frustum.GetPlanesToRef(transform, frustumPlanes);
  9394. return frustumPlanes;
  9395. };
  9396. /**
  9397. * Gets the near frustum plane transformed by the transform matrix
  9398. * @param transform transformation matrix to be applied to the resulting frustum plane
  9399. * @param frustumPlane the resuling frustum plane
  9400. */
  9401. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  9402. var m = transform.m;
  9403. frustumPlane.normal.x = m[3] + m[2];
  9404. frustumPlane.normal.y = m[7] + m[6];
  9405. frustumPlane.normal.z = m[11] + m[10];
  9406. frustumPlane.d = m[15] + m[14];
  9407. frustumPlane.normalize();
  9408. };
  9409. /**
  9410. * Gets the far frustum plane transformed by the transform matrix
  9411. * @param transform transformation matrix to be applied to the resulting frustum plane
  9412. * @param frustumPlane the resuling frustum plane
  9413. */
  9414. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  9415. var m = transform.m;
  9416. frustumPlane.normal.x = m[3] - m[2];
  9417. frustumPlane.normal.y = m[7] - m[6];
  9418. frustumPlane.normal.z = m[11] - m[10];
  9419. frustumPlane.d = m[15] - m[14];
  9420. frustumPlane.normalize();
  9421. };
  9422. /**
  9423. * Gets the left frustum plane transformed by the transform matrix
  9424. * @param transform transformation matrix to be applied to the resulting frustum plane
  9425. * @param frustumPlane the resuling frustum plane
  9426. */
  9427. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  9428. var m = transform.m;
  9429. frustumPlane.normal.x = m[3] + m[0];
  9430. frustumPlane.normal.y = m[7] + m[4];
  9431. frustumPlane.normal.z = m[11] + m[8];
  9432. frustumPlane.d = m[15] + m[12];
  9433. frustumPlane.normalize();
  9434. };
  9435. /**
  9436. * Gets the right frustum plane transformed by the transform matrix
  9437. * @param transform transformation matrix to be applied to the resulting frustum plane
  9438. * @param frustumPlane the resuling frustum plane
  9439. */
  9440. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  9441. var m = transform.m;
  9442. frustumPlane.normal.x = m[3] - m[0];
  9443. frustumPlane.normal.y = m[7] - m[4];
  9444. frustumPlane.normal.z = m[11] - m[8];
  9445. frustumPlane.d = m[15] - m[12];
  9446. frustumPlane.normalize();
  9447. };
  9448. /**
  9449. * Gets the top frustum plane transformed by the transform matrix
  9450. * @param transform transformation matrix to be applied to the resulting frustum plane
  9451. * @param frustumPlane the resuling frustum plane
  9452. */
  9453. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  9454. var m = transform.m;
  9455. frustumPlane.normal.x = m[3] - m[1];
  9456. frustumPlane.normal.y = m[7] - m[5];
  9457. frustumPlane.normal.z = m[11] - m[9];
  9458. frustumPlane.d = m[15] - m[13];
  9459. frustumPlane.normalize();
  9460. };
  9461. /**
  9462. * Gets the bottom frustum plane transformed by the transform matrix
  9463. * @param transform transformation matrix to be applied to the resulting frustum plane
  9464. * @param frustumPlane the resuling frustum plane
  9465. */
  9466. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  9467. var m = transform.m;
  9468. frustumPlane.normal.x = m[3] + m[1];
  9469. frustumPlane.normal.y = m[7] + m[5];
  9470. frustumPlane.normal.z = m[11] + m[9];
  9471. frustumPlane.d = m[15] + m[13];
  9472. frustumPlane.normalize();
  9473. };
  9474. /**
  9475. * Sets the given array "frustumPlanes" with the 6 Frustum planes computed by the given transformation matrix.
  9476. * @param transform transformation matrix to be applied to the resulting frustum planes
  9477. * @param frustumPlanes the resuling frustum planes
  9478. */
  9479. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  9480. // Near
  9481. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  9482. // Far
  9483. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  9484. // Left
  9485. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  9486. // Right
  9487. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  9488. // Top
  9489. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  9490. // Bottom
  9491. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  9492. };
  9493. return Frustum;
  9494. }());
  9495. BABYLON.Frustum = Frustum;
  9496. /** Defines supported spaces */
  9497. var Space;
  9498. (function (Space) {
  9499. /** Local (object) space */
  9500. Space[Space["LOCAL"] = 0] = "LOCAL";
  9501. /** World space */
  9502. Space[Space["WORLD"] = 1] = "WORLD";
  9503. /** Bone space */
  9504. Space[Space["BONE"] = 2] = "BONE";
  9505. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  9506. /** Defines the 3 main axes */
  9507. var Axis = /** @class */ (function () {
  9508. function Axis() {
  9509. }
  9510. /** X axis */
  9511. Axis.X = new Vector3(1.0, 0.0, 0.0);
  9512. /** Y axis */
  9513. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  9514. /** Z axis */
  9515. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  9516. return Axis;
  9517. }());
  9518. BABYLON.Axis = Axis;
  9519. /** Class used to represent a Bezier curve */
  9520. var BezierCurve = /** @class */ (function () {
  9521. function BezierCurve() {
  9522. }
  9523. /**
  9524. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the given x1, y1, x2, y2 floats
  9525. * @param t defines the time
  9526. * @param x1 defines the left coordinate on X axis
  9527. * @param y1 defines the left coordinate on Y axis
  9528. * @param x2 defines the right coordinate on X axis
  9529. * @param y2 defines the right coordinate on Y axis
  9530. * @returns the interpolated value
  9531. */
  9532. BezierCurve.Interpolate = function (t, x1, y1, x2, y2) {
  9533. // Extract X (which is equal to time here)
  9534. var f0 = 1 - 3 * x2 + 3 * x1;
  9535. var f1 = 3 * x2 - 6 * x1;
  9536. var f2 = 3 * x1;
  9537. var refinedT = t;
  9538. for (var i = 0; i < 5; i++) {
  9539. var refinedT2 = refinedT * refinedT;
  9540. var refinedT3 = refinedT2 * refinedT;
  9541. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  9542. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  9543. refinedT -= (x - t) * slope;
  9544. refinedT = Math.min(1, Math.max(0, refinedT));
  9545. }
  9546. // Resolve cubic bezier for the given x
  9547. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  9548. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  9549. Math.pow(refinedT, 3);
  9550. };
  9551. return BezierCurve;
  9552. }());
  9553. BABYLON.BezierCurve = BezierCurve;
  9554. /**
  9555. * Defines potential orientation for back face culling
  9556. */
  9557. var Orientation;
  9558. (function (Orientation) {
  9559. /**
  9560. * Clockwise
  9561. */
  9562. Orientation[Orientation["CW"] = 0] = "CW";
  9563. /** Counter clockwise */
  9564. Orientation[Orientation["CCW"] = 1] = "CCW";
  9565. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  9566. /**
  9567. * Defines angle representation
  9568. */
  9569. var Angle = /** @class */ (function () {
  9570. /**
  9571. * Creates an Angle object of "radians" radians (float).
  9572. */
  9573. function Angle(radians) {
  9574. this._radians = radians;
  9575. if (this._radians < 0.0) {
  9576. this._radians += (2.0 * Math.PI);
  9577. }
  9578. }
  9579. /**
  9580. * Get value in degrees
  9581. * @returns the Angle value in degrees (float)
  9582. */
  9583. Angle.prototype.degrees = function () {
  9584. return this._radians * 180.0 / Math.PI;
  9585. };
  9586. /**
  9587. * Get value in radians
  9588. * @returns the Angle value in radians (float)
  9589. */
  9590. Angle.prototype.radians = function () {
  9591. return this._radians;
  9592. };
  9593. /**
  9594. * Gets a new Angle object valued with the angle value in radians between the two given vectors
  9595. * @param a defines first vector
  9596. * @param b defines second vector
  9597. * @returns a new Angle
  9598. */
  9599. Angle.BetweenTwoPoints = function (a, b) {
  9600. var delta = b.subtract(a);
  9601. var theta = Math.atan2(delta.y, delta.x);
  9602. return new Angle(theta);
  9603. };
  9604. /**
  9605. * Gets a new Angle object from the given float in radians
  9606. * @param radians defines the angle value in radians
  9607. * @returns a new Angle
  9608. */
  9609. Angle.FromRadians = function (radians) {
  9610. return new Angle(radians);
  9611. };
  9612. /**
  9613. * Gets a new Angle object from the given float in degrees
  9614. * @param degrees defines the angle value in degrees
  9615. * @returns a new Angle
  9616. */
  9617. Angle.FromDegrees = function (degrees) {
  9618. return new Angle(degrees * Math.PI / 180.0);
  9619. };
  9620. return Angle;
  9621. }());
  9622. BABYLON.Angle = Angle;
  9623. /**
  9624. * This represents an arc in a 2d space.
  9625. */
  9626. var Arc2 = /** @class */ (function () {
  9627. /**
  9628. * Creates an Arc object from the three given points : start, middle and end.
  9629. * @param startPoint Defines the start point of the arc
  9630. * @param midPoint Defines the midlle point of the arc
  9631. * @param endPoint Defines the end point of the arc
  9632. */
  9633. function Arc2(
  9634. /** Defines the start point of the arc */
  9635. startPoint,
  9636. /** Defines the mid point of the arc */
  9637. midPoint,
  9638. /** Defines the end point of the arc */
  9639. endPoint) {
  9640. this.startPoint = startPoint;
  9641. this.midPoint = midPoint;
  9642. this.endPoint = endPoint;
  9643. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  9644. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  9645. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  9646. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  9647. 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);
  9648. this.radius = this.centerPoint.subtract(this.startPoint).length();
  9649. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  9650. var a1 = this.startAngle.degrees();
  9651. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  9652. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  9653. // angles correction
  9654. if (a2 - a1 > +180.0) {
  9655. a2 -= 360.0;
  9656. }
  9657. if (a2 - a1 < -180.0) {
  9658. a2 += 360.0;
  9659. }
  9660. if (a3 - a2 > +180.0) {
  9661. a3 -= 360.0;
  9662. }
  9663. if (a3 - a2 < -180.0) {
  9664. a3 += 360.0;
  9665. }
  9666. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  9667. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  9668. }
  9669. return Arc2;
  9670. }());
  9671. BABYLON.Arc2 = Arc2;
  9672. /**
  9673. * Represents a 2D path made up of multiple 2D points
  9674. */
  9675. var Path2 = /** @class */ (function () {
  9676. /**
  9677. * Creates a Path2 object from the starting 2D coordinates x and y.
  9678. * @param x the starting points x value
  9679. * @param y the starting points y value
  9680. */
  9681. function Path2(x, y) {
  9682. this._points = new Array();
  9683. this._length = 0.0;
  9684. /**
  9685. * If the path start and end point are the same
  9686. */
  9687. this.closed = false;
  9688. this._points.push(new Vector2(x, y));
  9689. }
  9690. /**
  9691. * Adds a new segment until the given coordinates (x, y) to the current Path2.
  9692. * @param x the added points x value
  9693. * @param y the added points y value
  9694. * @returns the updated Path2.
  9695. */
  9696. Path2.prototype.addLineTo = function (x, y) {
  9697. if (this.closed) {
  9698. return this;
  9699. }
  9700. var newPoint = new Vector2(x, y);
  9701. var previousPoint = this._points[this._points.length - 1];
  9702. this._points.push(newPoint);
  9703. this._length += newPoint.subtract(previousPoint).length();
  9704. return this;
  9705. };
  9706. /**
  9707. * 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.
  9708. * @param midX middle point x value
  9709. * @param midY middle point y value
  9710. * @param endX end point x value
  9711. * @param endY end point y value
  9712. * @param numberOfSegments (default: 36)
  9713. * @returns the updated Path2.
  9714. */
  9715. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  9716. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  9717. if (this.closed) {
  9718. return this;
  9719. }
  9720. var startPoint = this._points[this._points.length - 1];
  9721. var midPoint = new Vector2(midX, midY);
  9722. var endPoint = new Vector2(endX, endY);
  9723. var arc = new Arc2(startPoint, midPoint, endPoint);
  9724. var increment = arc.angle.radians() / numberOfSegments;
  9725. if (arc.orientation === Orientation.CW) {
  9726. increment *= -1;
  9727. }
  9728. var currentAngle = arc.startAngle.radians() + increment;
  9729. for (var i = 0; i < numberOfSegments; i++) {
  9730. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  9731. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  9732. this.addLineTo(x, y);
  9733. currentAngle += increment;
  9734. }
  9735. return this;
  9736. };
  9737. /**
  9738. * Closes the Path2.
  9739. * @returns the Path2.
  9740. */
  9741. Path2.prototype.close = function () {
  9742. this.closed = true;
  9743. return this;
  9744. };
  9745. /**
  9746. * Gets the sum of the distance between each sequential point in the path
  9747. * @returns the Path2 total length (float).
  9748. */
  9749. Path2.prototype.length = function () {
  9750. var result = this._length;
  9751. if (!this.closed) {
  9752. var lastPoint = this._points[this._points.length - 1];
  9753. var firstPoint = this._points[0];
  9754. result += (firstPoint.subtract(lastPoint).length());
  9755. }
  9756. return result;
  9757. };
  9758. /**
  9759. * Gets the points which construct the path
  9760. * @returns the Path2 internal array of points.
  9761. */
  9762. Path2.prototype.getPoints = function () {
  9763. return this._points;
  9764. };
  9765. /**
  9766. * Retreives the point at the distance aways from the starting point
  9767. * @param normalizedLengthPosition the length along the path to retreive the point from
  9768. * @returns a new Vector2 located at a percentage of the Path2 total length on this path.
  9769. */
  9770. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  9771. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  9772. return Vector2.Zero();
  9773. }
  9774. var lengthPosition = normalizedLengthPosition * this.length();
  9775. var previousOffset = 0;
  9776. for (var i = 0; i < this._points.length; i++) {
  9777. var j = (i + 1) % this._points.length;
  9778. var a = this._points[i];
  9779. var b = this._points[j];
  9780. var bToA = b.subtract(a);
  9781. var nextOffset = (bToA.length() + previousOffset);
  9782. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  9783. var dir = bToA.normalize();
  9784. var localOffset = lengthPosition - previousOffset;
  9785. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  9786. }
  9787. previousOffset = nextOffset;
  9788. }
  9789. return Vector2.Zero();
  9790. };
  9791. /**
  9792. * Creates a new path starting from an x and y position
  9793. * @param x starting x value
  9794. * @param y starting y value
  9795. * @returns a new Path2 starting at the coordinates (x, y).
  9796. */
  9797. Path2.StartingAt = function (x, y) {
  9798. return new Path2(x, y);
  9799. };
  9800. return Path2;
  9801. }());
  9802. BABYLON.Path2 = Path2;
  9803. /**
  9804. * Represents a 3D path made up of multiple 3D points
  9805. */
  9806. var Path3D = /** @class */ (function () {
  9807. /**
  9808. * new Path3D(path, normal, raw)
  9809. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  9810. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  9811. * @param path an array of Vector3, the curve axis of the Path3D
  9812. * @param normal (options) Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  9813. * @param raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  9814. */
  9815. function Path3D(
  9816. /**
  9817. * an array of Vector3, the curve axis of the Path3D
  9818. */
  9819. path, firstNormal, raw) {
  9820. if (firstNormal === void 0) { firstNormal = null; }
  9821. this.path = path;
  9822. this._curve = new Array();
  9823. this._distances = new Array();
  9824. this._tangents = new Array();
  9825. this._normals = new Array();
  9826. this._binormals = new Array();
  9827. for (var p = 0; p < path.length; p++) {
  9828. this._curve[p] = path[p].clone(); // hard copy
  9829. }
  9830. this._raw = raw || false;
  9831. this._compute(firstNormal);
  9832. }
  9833. /**
  9834. * Returns the Path3D array of successive Vector3 designing its curve.
  9835. * @returns the Path3D array of successive Vector3 designing its curve.
  9836. */
  9837. Path3D.prototype.getCurve = function () {
  9838. return this._curve;
  9839. };
  9840. /**
  9841. * Returns an array populated with tangent vectors on each Path3D curve point.
  9842. * @returns an array populated with tangent vectors on each Path3D curve point.
  9843. */
  9844. Path3D.prototype.getTangents = function () {
  9845. return this._tangents;
  9846. };
  9847. /**
  9848. * Returns an array populated with normal vectors on each Path3D curve point.
  9849. * @returns an array populated with normal vectors on each Path3D curve point.
  9850. */
  9851. Path3D.prototype.getNormals = function () {
  9852. return this._normals;
  9853. };
  9854. /**
  9855. * Returns an array populated with binormal vectors on each Path3D curve point.
  9856. * @returns an array populated with binormal vectors on each Path3D curve point.
  9857. */
  9858. Path3D.prototype.getBinormals = function () {
  9859. return this._binormals;
  9860. };
  9861. /**
  9862. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  9863. * @returns an array populated with distances (float) of the i-th point from the first curve point.
  9864. */
  9865. Path3D.prototype.getDistances = function () {
  9866. return this._distances;
  9867. };
  9868. /**
  9869. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  9870. * @param path path which all values are copied into the curves points
  9871. * @param firstNormal which should be projected onto the curve
  9872. * @returns the same object updated.
  9873. */
  9874. Path3D.prototype.update = function (path, firstNormal) {
  9875. if (firstNormal === void 0) { firstNormal = null; }
  9876. for (var p = 0; p < path.length; p++) {
  9877. this._curve[p].x = path[p].x;
  9878. this._curve[p].y = path[p].y;
  9879. this._curve[p].z = path[p].z;
  9880. }
  9881. this._compute(firstNormal);
  9882. return this;
  9883. };
  9884. // private function compute() : computes tangents, normals and binormals
  9885. Path3D.prototype._compute = function (firstNormal) {
  9886. var l = this._curve.length;
  9887. // first and last tangents
  9888. this._tangents[0] = this._getFirstNonNullVector(0);
  9889. if (!this._raw) {
  9890. this._tangents[0].normalize();
  9891. }
  9892. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  9893. if (!this._raw) {
  9894. this._tangents[l - 1].normalize();
  9895. }
  9896. // normals and binormals at first point : arbitrary vector with _normalVector()
  9897. var tg0 = this._tangents[0];
  9898. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  9899. this._normals[0] = pp0;
  9900. if (!this._raw) {
  9901. this._normals[0].normalize();
  9902. }
  9903. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  9904. if (!this._raw) {
  9905. this._binormals[0].normalize();
  9906. }
  9907. this._distances[0] = 0.0;
  9908. // normals and binormals : next points
  9909. var prev; // previous vector (segment)
  9910. var cur; // current vector (segment)
  9911. var curTang; // current tangent
  9912. // previous normal
  9913. var prevBinor; // previous binormal
  9914. for (var i = 1; i < l; i++) {
  9915. // tangents
  9916. prev = this._getLastNonNullVector(i);
  9917. if (i < l - 1) {
  9918. cur = this._getFirstNonNullVector(i);
  9919. this._tangents[i] = prev.add(cur);
  9920. this._tangents[i].normalize();
  9921. }
  9922. this._distances[i] = this._distances[i - 1] + prev.length();
  9923. // normals and binormals
  9924. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  9925. curTang = this._tangents[i];
  9926. prevBinor = this._binormals[i - 1];
  9927. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  9928. if (!this._raw) {
  9929. this._normals[i].normalize();
  9930. }
  9931. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  9932. if (!this._raw) {
  9933. this._binormals[i].normalize();
  9934. }
  9935. }
  9936. };
  9937. // private function getFirstNonNullVector(index)
  9938. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  9939. Path3D.prototype._getFirstNonNullVector = function (index) {
  9940. var i = 1;
  9941. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  9942. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  9943. i++;
  9944. nNVector = this._curve[index + i].subtract(this._curve[index]);
  9945. }
  9946. return nNVector;
  9947. };
  9948. // private function getLastNonNullVector(index)
  9949. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  9950. Path3D.prototype._getLastNonNullVector = function (index) {
  9951. var i = 1;
  9952. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  9953. while (nLVector.length() === 0 && index > i + 1) {
  9954. i++;
  9955. nLVector = this._curve[index].subtract(this._curve[index - i]);
  9956. }
  9957. return nLVector;
  9958. };
  9959. // private function normalVector(v0, vt, va) :
  9960. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  9961. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  9962. Path3D.prototype._normalVector = function (v0, vt, va) {
  9963. var normal0;
  9964. var tgl = vt.length();
  9965. if (tgl === 0.0) {
  9966. tgl = 1.0;
  9967. }
  9968. if (va === undefined || va === null) {
  9969. var point;
  9970. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) { // search for a point in the plane
  9971. point = new Vector3(0.0, -1.0, 0.0);
  9972. }
  9973. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  9974. point = new Vector3(1.0, 0.0, 0.0);
  9975. }
  9976. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  9977. point = new Vector3(0.0, 0.0, 1.0);
  9978. }
  9979. else {
  9980. point = Vector3.Zero();
  9981. }
  9982. normal0 = Vector3.Cross(vt, point);
  9983. }
  9984. else {
  9985. normal0 = Vector3.Cross(vt, va);
  9986. Vector3.CrossToRef(normal0, vt, normal0);
  9987. }
  9988. normal0.normalize();
  9989. return normal0;
  9990. };
  9991. return Path3D;
  9992. }());
  9993. BABYLON.Path3D = Path3D;
  9994. /**
  9995. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  9996. * A Curve3 is designed from a series of successive Vector3.
  9997. * @see https://doc.babylonjs.com/how_to/how_to_use_curve3
  9998. */
  9999. var Curve3 = /** @class */ (function () {
  10000. /**
  10001. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  10002. * A Curve3 is designed from a series of successive Vector3.
  10003. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  10004. * @param points points which make up the curve
  10005. */
  10006. function Curve3(points) {
  10007. this._length = 0.0;
  10008. this._points = points;
  10009. this._length = this._computeLength(points);
  10010. }
  10011. /**
  10012. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  10013. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  10014. * @param v1 (Vector3) the control point
  10015. * @param v2 (Vector3) the end point of the Quadratic Bezier
  10016. * @param nbPoints (integer) the wanted number of points in the curve
  10017. * @returns the created Curve3
  10018. */
  10019. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  10020. nbPoints = nbPoints > 2 ? nbPoints : 3;
  10021. var bez = new Array();
  10022. var equation = function (t, val0, val1, val2) {
  10023. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  10024. return res;
  10025. };
  10026. for (var i = 0; i <= nbPoints; i++) {
  10027. 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)));
  10028. }
  10029. return new Curve3(bez);
  10030. };
  10031. /**
  10032. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  10033. * @param v0 (Vector3) the origin point of the Cubic Bezier
  10034. * @param v1 (Vector3) the first control point
  10035. * @param v2 (Vector3) the second control point
  10036. * @param v3 (Vector3) the end point of the Cubic Bezier
  10037. * @param nbPoints (integer) the wanted number of points in the curve
  10038. * @returns the created Curve3
  10039. */
  10040. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  10041. nbPoints = nbPoints > 3 ? nbPoints : 4;
  10042. var bez = new Array();
  10043. var equation = function (t, val0, val1, val2, val3) {
  10044. 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;
  10045. return res;
  10046. };
  10047. for (var i = 0; i <= nbPoints; i++) {
  10048. 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)));
  10049. }
  10050. return new Curve3(bez);
  10051. };
  10052. /**
  10053. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  10054. * @param p1 (Vector3) the origin point of the Hermite Spline
  10055. * @param t1 (Vector3) the tangent vector at the origin point
  10056. * @param p2 (Vector3) the end point of the Hermite Spline
  10057. * @param t2 (Vector3) the tangent vector at the end point
  10058. * @param nbPoints (integer) the wanted number of points in the curve
  10059. * @returns the created Curve3
  10060. */
  10061. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  10062. var hermite = new Array();
  10063. var step = 1.0 / nbPoints;
  10064. for (var i = 0; i <= nbPoints; i++) {
  10065. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  10066. }
  10067. return new Curve3(hermite);
  10068. };
  10069. /**
  10070. * Returns a Curve3 object along a CatmullRom Spline curve :
  10071. * @param points (array of Vector3) the points the spline must pass through. At least, four points required
  10072. * @param nbPoints (integer) the wanted number of points between each curve control points
  10073. * @param closed (boolean) optional with default false, when true forms a closed loop from the points
  10074. * @returns the created Curve3
  10075. */
  10076. Curve3.CreateCatmullRomSpline = function (points, nbPoints, closed) {
  10077. var catmullRom = new Array();
  10078. var step = 1.0 / nbPoints;
  10079. var amount = 0.0;
  10080. if (closed) {
  10081. var pointsCount = points.length;
  10082. for (var i = 0; i < pointsCount; i++) {
  10083. amount = 0;
  10084. for (var c = 0; c < nbPoints; c++) {
  10085. catmullRom.push(Vector3.CatmullRom(points[i % pointsCount], points[(i + 1) % pointsCount], points[(i + 2) % pointsCount], points[(i + 3) % pointsCount], amount));
  10086. amount += step;
  10087. }
  10088. }
  10089. catmullRom.push(catmullRom[0]);
  10090. }
  10091. else {
  10092. var totalPoints = new Array();
  10093. totalPoints.push(points[0].clone());
  10094. Array.prototype.push.apply(totalPoints, points);
  10095. totalPoints.push(points[points.length - 1].clone());
  10096. for (var i = 0; i < totalPoints.length - 3; i++) {
  10097. amount = 0;
  10098. for (var c = 0; c < nbPoints; c++) {
  10099. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  10100. amount += step;
  10101. }
  10102. }
  10103. i--;
  10104. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  10105. }
  10106. return new Curve3(catmullRom);
  10107. };
  10108. /**
  10109. * @returns the Curve3 stored array of successive Vector3
  10110. */
  10111. Curve3.prototype.getPoints = function () {
  10112. return this._points;
  10113. };
  10114. /**
  10115. * @returns the computed length (float) of the curve.
  10116. */
  10117. Curve3.prototype.length = function () {
  10118. return this._length;
  10119. };
  10120. /**
  10121. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  10122. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  10123. * curveA and curveB keep unchanged.
  10124. * @param curve the curve to continue from this curve
  10125. * @returns the newly constructed curve
  10126. */
  10127. Curve3.prototype.continue = function (curve) {
  10128. var lastPoint = this._points[this._points.length - 1];
  10129. var continuedPoints = this._points.slice();
  10130. var curvePoints = curve.getPoints();
  10131. for (var i = 1; i < curvePoints.length; i++) {
  10132. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  10133. }
  10134. var continuedCurve = new Curve3(continuedPoints);
  10135. return continuedCurve;
  10136. };
  10137. Curve3.prototype._computeLength = function (path) {
  10138. var l = 0;
  10139. for (var i = 1; i < path.length; i++) {
  10140. l += (path[i].subtract(path[i - 1])).length();
  10141. }
  10142. return l;
  10143. };
  10144. return Curve3;
  10145. }());
  10146. BABYLON.Curve3 = Curve3;
  10147. // Vertex formats
  10148. /**
  10149. * Contains position and normal vectors for a vertex
  10150. */
  10151. var PositionNormalVertex = /** @class */ (function () {
  10152. /**
  10153. * Creates a PositionNormalVertex
  10154. * @param position the position of the vertex (defaut: 0,0,0)
  10155. * @param normal the normal of the vertex (defaut: 0,1,0)
  10156. */
  10157. function PositionNormalVertex(
  10158. /** the position of the vertex (defaut: 0,0,0) */
  10159. position,
  10160. /** the normal of the vertex (defaut: 0,1,0) */
  10161. normal) {
  10162. if (position === void 0) { position = Vector3.Zero(); }
  10163. if (normal === void 0) { normal = Vector3.Up(); }
  10164. this.position = position;
  10165. this.normal = normal;
  10166. }
  10167. /**
  10168. * Clones the PositionNormalVertex
  10169. * @returns the cloned PositionNormalVertex
  10170. */
  10171. PositionNormalVertex.prototype.clone = function () {
  10172. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  10173. };
  10174. return PositionNormalVertex;
  10175. }());
  10176. BABYLON.PositionNormalVertex = PositionNormalVertex;
  10177. /**
  10178. * Contains position, normal and uv vectors for a vertex
  10179. */
  10180. var PositionNormalTextureVertex = /** @class */ (function () {
  10181. /**
  10182. * Creates a PositionNormalTextureVertex
  10183. * @param position the position of the vertex (defaut: 0,0,0)
  10184. * @param normal the normal of the vertex (defaut: 0,1,0)
  10185. * @param uv the uv of the vertex (default: 0,0)
  10186. */
  10187. function PositionNormalTextureVertex(
  10188. /** the position of the vertex (defaut: 0,0,0) */
  10189. position,
  10190. /** the normal of the vertex (defaut: 0,1,0) */
  10191. normal,
  10192. /** the uv of the vertex (default: 0,0) */
  10193. uv) {
  10194. if (position === void 0) { position = Vector3.Zero(); }
  10195. if (normal === void 0) { normal = Vector3.Up(); }
  10196. if (uv === void 0) { uv = Vector2.Zero(); }
  10197. this.position = position;
  10198. this.normal = normal;
  10199. this.uv = uv;
  10200. }
  10201. /**
  10202. * Clones the PositionNormalTextureVertex
  10203. * @returns the cloned PositionNormalTextureVertex
  10204. */
  10205. PositionNormalTextureVertex.prototype.clone = function () {
  10206. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  10207. };
  10208. return PositionNormalTextureVertex;
  10209. }());
  10210. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  10211. // Temporary pre-allocated objects for engine internal use
  10212. // usage in any internal function :
  10213. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  10214. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  10215. /**
  10216. * @hidden
  10217. */
  10218. var Tmp = /** @class */ (function () {
  10219. function Tmp() {
  10220. }
  10221. Tmp.Color3 = BABYLON.Tools.BuildArray(3, Color3.Black);
  10222. Tmp.Color4 = BABYLON.Tools.BuildArray(3, function () { return new Color4(0, 0, 0, 0); });
  10223. Tmp.Vector2 = BABYLON.Tools.BuildArray(3, Vector2.Zero); // 3 temp Vector2 at once should be enough
  10224. Tmp.Vector3 = BABYLON.Tools.BuildArray(13, Vector3.Zero); // 13 temp Vector3 at once should be enough
  10225. Tmp.Vector4 = BABYLON.Tools.BuildArray(3, Vector4.Zero); // 3 temp Vector4 at once should be enough
  10226. Tmp.Quaternion = BABYLON.Tools.BuildArray(2, Quaternion.Zero); // 2 temp Quaternion at once should be enough
  10227. Tmp.Matrix = BABYLON.Tools.BuildArray(8, Matrix.Identity); // 8 temp Matrices at once should be enough
  10228. return Tmp;
  10229. }());
  10230. BABYLON.Tmp = Tmp;
  10231. /**
  10232. * @hidden
  10233. * Same as Tmp but not exported to keep it only for math functions to avoid conflicts
  10234. */
  10235. var MathTmp = /** @class */ (function () {
  10236. function MathTmp() {
  10237. }
  10238. MathTmp.Vector3 = BABYLON.Tools.BuildArray(6, Vector3.Zero);
  10239. MathTmp.Matrix = BABYLON.Tools.BuildArray(2, Matrix.Identity);
  10240. MathTmp.Quaternion = BABYLON.Tools.BuildArray(3, Quaternion.Zero);
  10241. return MathTmp;
  10242. }());
  10243. })(BABYLON || (BABYLON = {}));
  10244. //# sourceMappingURL=babylon.math.js.map
  10245. var BABYLON;
  10246. (function (BABYLON) {
  10247. /**
  10248. * Scalar computation library
  10249. */
  10250. var Scalar = /** @class */ (function () {
  10251. function Scalar() {
  10252. }
  10253. /**
  10254. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  10255. * @param a number
  10256. * @param b number
  10257. * @param epsilon (default = 1.401298E-45)
  10258. * @returns true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  10259. */
  10260. Scalar.WithinEpsilon = function (a, b, epsilon) {
  10261. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  10262. var num = a - b;
  10263. return -epsilon <= num && num <= epsilon;
  10264. };
  10265. /**
  10266. * Returns a string : the upper case translation of the number i to hexadecimal.
  10267. * @param i number
  10268. * @returns the upper case translation of the number i to hexadecimal.
  10269. */
  10270. Scalar.ToHex = function (i) {
  10271. var str = i.toString(16);
  10272. if (i <= 15) {
  10273. return ("0" + str).toUpperCase();
  10274. }
  10275. return str.toUpperCase();
  10276. };
  10277. /**
  10278. * Returns -1 if value is negative and +1 is value is positive.
  10279. * @param value the value
  10280. * @returns the value itself if it's equal to zero.
  10281. */
  10282. Scalar.Sign = function (value) {
  10283. value = +value; // convert to a number
  10284. if (value === 0 || isNaN(value)) {
  10285. return value;
  10286. }
  10287. return value > 0 ? 1 : -1;
  10288. };
  10289. /**
  10290. * Returns the value itself if it's between min and max.
  10291. * Returns min if the value is lower than min.
  10292. * Returns max if the value is greater than max.
  10293. * @param value the value to clmap
  10294. * @param min the min value to clamp to (default: 0)
  10295. * @param max the max value to clamp to (default: 1)
  10296. * @returns the clamped value
  10297. */
  10298. Scalar.Clamp = function (value, min, max) {
  10299. if (min === void 0) { min = 0; }
  10300. if (max === void 0) { max = 1; }
  10301. return Math.min(max, Math.max(min, value));
  10302. };
  10303. /**
  10304. * the log2 of value.
  10305. * @param value the value to compute log2 of
  10306. * @returns the log2 of value.
  10307. */
  10308. Scalar.Log2 = function (value) {
  10309. return Math.log(value) * Math.LOG2E;
  10310. };
  10311. /**
  10312. * Loops the value, so that it is never larger than length and never smaller than 0.
  10313. *
  10314. * This is similar to the modulo operator but it works with floating point numbers.
  10315. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  10316. * With t = 5 and length = 2.5, the result would be 0.0.
  10317. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  10318. * @param value the value
  10319. * @param length the length
  10320. * @returns the looped value
  10321. */
  10322. Scalar.Repeat = function (value, length) {
  10323. return value - Math.floor(value / length) * length;
  10324. };
  10325. /**
  10326. * Normalize the value between 0.0 and 1.0 using min and max values
  10327. * @param value value to normalize
  10328. * @param min max to normalize between
  10329. * @param max min to normalize between
  10330. * @returns the normalized value
  10331. */
  10332. Scalar.Normalize = function (value, min, max) {
  10333. return (value - min) / (max - min);
  10334. };
  10335. /**
  10336. * Denormalize the value from 0.0 and 1.0 using min and max values
  10337. * @param normalized value to denormalize
  10338. * @param min max to denormalize between
  10339. * @param max min to denormalize between
  10340. * @returns the denormalized value
  10341. */
  10342. Scalar.Denormalize = function (normalized, min, max) {
  10343. return (normalized * (max - min) + min);
  10344. };
  10345. /**
  10346. * Calculates the shortest difference between two given angles given in degrees.
  10347. * @param current current angle in degrees
  10348. * @param target target angle in degrees
  10349. * @returns the delta
  10350. */
  10351. Scalar.DeltaAngle = function (current, target) {
  10352. var num = Scalar.Repeat(target - current, 360.0);
  10353. if (num > 180.0) {
  10354. num -= 360.0;
  10355. }
  10356. return num;
  10357. };
  10358. /**
  10359. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  10360. * @param tx value
  10361. * @param length length
  10362. * @returns The returned value will move back and forth between 0 and length
  10363. */
  10364. Scalar.PingPong = function (tx, length) {
  10365. var t = Scalar.Repeat(tx, length * 2.0);
  10366. return length - Math.abs(t - length);
  10367. };
  10368. /**
  10369. * Interpolates between min and max with smoothing at the limits.
  10370. *
  10371. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  10372. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  10373. * @param from from
  10374. * @param to to
  10375. * @param tx value
  10376. * @returns the smooth stepped value
  10377. */
  10378. Scalar.SmoothStep = function (from, to, tx) {
  10379. var t = Scalar.Clamp(tx);
  10380. t = -2.0 * t * t * t + 3.0 * t * t;
  10381. return to * t + from * (1.0 - t);
  10382. };
  10383. /**
  10384. * Moves a value current towards target.
  10385. *
  10386. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  10387. * Negative values of maxDelta pushes the value away from target.
  10388. * @param current current value
  10389. * @param target target value
  10390. * @param maxDelta max distance to move
  10391. * @returns resulting value
  10392. */
  10393. Scalar.MoveTowards = function (current, target, maxDelta) {
  10394. var result = 0;
  10395. if (Math.abs(target - current) <= maxDelta) {
  10396. result = target;
  10397. }
  10398. else {
  10399. result = current + Scalar.Sign(target - current) * maxDelta;
  10400. }
  10401. return result;
  10402. };
  10403. /**
  10404. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  10405. *
  10406. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  10407. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  10408. * @param current current value
  10409. * @param target target value
  10410. * @param maxDelta max distance to move
  10411. * @returns resulting angle
  10412. */
  10413. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  10414. var num = Scalar.DeltaAngle(current, target);
  10415. var result = 0;
  10416. if (-maxDelta < num && num < maxDelta) {
  10417. result = target;
  10418. }
  10419. else {
  10420. target = current + num;
  10421. result = Scalar.MoveTowards(current, target, maxDelta);
  10422. }
  10423. return result;
  10424. };
  10425. /**
  10426. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  10427. * @param start start value
  10428. * @param end target value
  10429. * @param amount amount to lerp between
  10430. * @returns the lerped value
  10431. */
  10432. Scalar.Lerp = function (start, end, amount) {
  10433. return start + ((end - start) * amount);
  10434. };
  10435. /**
  10436. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  10437. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  10438. * @param start start value
  10439. * @param end target value
  10440. * @param amount amount to lerp between
  10441. * @returns the lerped value
  10442. */
  10443. Scalar.LerpAngle = function (start, end, amount) {
  10444. var num = Scalar.Repeat(end - start, 360.0);
  10445. if (num > 180.0) {
  10446. num -= 360.0;
  10447. }
  10448. return start + num * Scalar.Clamp(amount);
  10449. };
  10450. /**
  10451. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  10452. * @param a start value
  10453. * @param b target value
  10454. * @param value value between a and b
  10455. * @returns the inverseLerp value
  10456. */
  10457. Scalar.InverseLerp = function (a, b, value) {
  10458. var result = 0;
  10459. if (a != b) {
  10460. result = Scalar.Clamp((value - a) / (b - a));
  10461. }
  10462. else {
  10463. result = 0.0;
  10464. }
  10465. return result;
  10466. };
  10467. /**
  10468. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  10469. * @see http://mathworld.wolfram.com/HermitePolynomial.html
  10470. * @param value1 spline value
  10471. * @param tangent1 spline value
  10472. * @param value2 spline value
  10473. * @param tangent2 spline value
  10474. * @param amount input value
  10475. * @returns hermite result
  10476. */
  10477. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  10478. var squared = amount * amount;
  10479. var cubed = amount * squared;
  10480. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  10481. var part2 = (-2.0 * cubed) + (3.0 * squared);
  10482. var part3 = (cubed - (2.0 * squared)) + amount;
  10483. var part4 = cubed - squared;
  10484. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  10485. };
  10486. /**
  10487. * Returns a random float number between and min and max values
  10488. * @param min min value of random
  10489. * @param max max value of random
  10490. * @returns random value
  10491. */
  10492. Scalar.RandomRange = function (min, max) {
  10493. if (min === max) {
  10494. return min;
  10495. }
  10496. return ((Math.random() * (max - min)) + min);
  10497. };
  10498. /**
  10499. * This function returns percentage of a number in a given range.
  10500. *
  10501. * RangeToPercent(40,20,60) will return 0.5 (50%)
  10502. * RangeToPercent(34,0,100) will return 0.34 (34%)
  10503. * @param number to convert to percentage
  10504. * @param min min range
  10505. * @param max max range
  10506. * @returns the percentage
  10507. */
  10508. Scalar.RangeToPercent = function (number, min, max) {
  10509. return ((number - min) / (max - min));
  10510. };
  10511. /**
  10512. * This function returns number that corresponds to the percentage in a given range.
  10513. *
  10514. * PercentToRange(0.34,0,100) will return 34.
  10515. * @param percent to convert to number
  10516. * @param min min range
  10517. * @param max max range
  10518. * @returns the number
  10519. */
  10520. Scalar.PercentToRange = function (percent, min, max) {
  10521. return ((max - min) * percent + min);
  10522. };
  10523. /**
  10524. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  10525. * @param angle The angle to normalize in radian.
  10526. * @return The converted angle.
  10527. */
  10528. Scalar.NormalizeRadians = function (angle) {
  10529. // More precise but slower version kept for reference.
  10530. // angle = angle % Tools.TwoPi;
  10531. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  10532. //if (angle > Math.PI) {
  10533. // angle -= Tools.TwoPi;
  10534. //}
  10535. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  10536. return angle;
  10537. };
  10538. /**
  10539. * Two pi constants convenient for computation.
  10540. */
  10541. Scalar.TwoPi = Math.PI * 2;
  10542. return Scalar;
  10543. }());
  10544. BABYLON.Scalar = Scalar;
  10545. })(BABYLON || (BABYLON = {}));
  10546. //# sourceMappingURL=babylon.math.scalar.js.map
  10547. //# sourceMappingURL=babylon.mixins.js.map
  10548. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  10549. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  10550. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  10551. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  10552. //# sourceMappingURL=babylon.webgl2.js.map
  10553. var BABYLON;
  10554. (function (BABYLON) {
  10555. var __decoratorInitialStore = {};
  10556. var __mergedStore = {};
  10557. var _copySource = function (creationFunction, source, instanciate) {
  10558. var destination = creationFunction();
  10559. // Tags
  10560. if (BABYLON.Tags) {
  10561. BABYLON.Tags.AddTagsTo(destination, source.tags);
  10562. }
  10563. var classStore = getMergedStore(destination);
  10564. // Properties
  10565. for (var property in classStore) {
  10566. var propertyDescriptor = classStore[property];
  10567. var sourceProperty = source[property];
  10568. var propertyType = propertyDescriptor.type;
  10569. if (sourceProperty !== undefined && sourceProperty !== null) {
  10570. switch (propertyType) {
  10571. case 0: // Value
  10572. case 6: // Mesh reference
  10573. case 11: // Camera reference
  10574. destination[property] = sourceProperty;
  10575. break;
  10576. case 1: // Texture
  10577. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  10578. break;
  10579. case 2: // Color3
  10580. case 3: // FresnelParameters
  10581. case 4: // Vector2
  10582. case 5: // Vector3
  10583. case 7: // Color Curves
  10584. case 10: // Quaternion
  10585. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  10586. break;
  10587. }
  10588. }
  10589. }
  10590. return destination;
  10591. };
  10592. function getDirectStore(target) {
  10593. var classKey = target.getClassName();
  10594. if (!__decoratorInitialStore[classKey]) {
  10595. __decoratorInitialStore[classKey] = {};
  10596. }
  10597. return __decoratorInitialStore[classKey];
  10598. }
  10599. /**
  10600. * Return the list of properties flagged as serializable
  10601. * @param target: host object
  10602. */
  10603. function getMergedStore(target) {
  10604. var classKey = target.getClassName();
  10605. if (__mergedStore[classKey]) {
  10606. return __mergedStore[classKey];
  10607. }
  10608. __mergedStore[classKey] = {};
  10609. var store = __mergedStore[classKey];
  10610. var currentTarget = target;
  10611. var currentKey = classKey;
  10612. while (currentKey) {
  10613. var initialStore = __decoratorInitialStore[currentKey];
  10614. for (var property in initialStore) {
  10615. store[property] = initialStore[property];
  10616. }
  10617. var parent_1 = void 0;
  10618. var done = false;
  10619. do {
  10620. parent_1 = Object.getPrototypeOf(currentTarget);
  10621. if (!parent_1.getClassName) {
  10622. done = true;
  10623. break;
  10624. }
  10625. if (parent_1.getClassName() !== currentKey) {
  10626. break;
  10627. }
  10628. currentTarget = parent_1;
  10629. } while (parent_1);
  10630. if (done) {
  10631. break;
  10632. }
  10633. currentKey = parent_1.getClassName();
  10634. currentTarget = parent_1;
  10635. }
  10636. return store;
  10637. }
  10638. function generateSerializableMember(type, sourceName) {
  10639. return function (target, propertyKey) {
  10640. var classStore = getDirectStore(target);
  10641. if (!classStore[propertyKey]) {
  10642. classStore[propertyKey] = { type: type, sourceName: sourceName };
  10643. }
  10644. };
  10645. }
  10646. function generateExpandMember(setCallback, targetKey) {
  10647. if (targetKey === void 0) { targetKey = null; }
  10648. return function (target, propertyKey) {
  10649. var key = targetKey || ("_" + propertyKey);
  10650. Object.defineProperty(target, propertyKey, {
  10651. get: function () {
  10652. return this[key];
  10653. },
  10654. set: function (value) {
  10655. if (this[key] === value) {
  10656. return;
  10657. }
  10658. this[key] = value;
  10659. target[setCallback].apply(this);
  10660. },
  10661. enumerable: true,
  10662. configurable: true
  10663. });
  10664. };
  10665. }
  10666. function expandToProperty(callback, targetKey) {
  10667. if (targetKey === void 0) { targetKey = null; }
  10668. return generateExpandMember(callback, targetKey);
  10669. }
  10670. BABYLON.expandToProperty = expandToProperty;
  10671. function serialize(sourceName) {
  10672. return generateSerializableMember(0, sourceName); // value member
  10673. }
  10674. BABYLON.serialize = serialize;
  10675. function serializeAsTexture(sourceName) {
  10676. return generateSerializableMember(1, sourceName); // texture member
  10677. }
  10678. BABYLON.serializeAsTexture = serializeAsTexture;
  10679. function serializeAsColor3(sourceName) {
  10680. return generateSerializableMember(2, sourceName); // color3 member
  10681. }
  10682. BABYLON.serializeAsColor3 = serializeAsColor3;
  10683. function serializeAsFresnelParameters(sourceName) {
  10684. return generateSerializableMember(3, sourceName); // fresnel parameters member
  10685. }
  10686. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  10687. function serializeAsVector2(sourceName) {
  10688. return generateSerializableMember(4, sourceName); // vector2 member
  10689. }
  10690. BABYLON.serializeAsVector2 = serializeAsVector2;
  10691. function serializeAsVector3(sourceName) {
  10692. return generateSerializableMember(5, sourceName); // vector3 member
  10693. }
  10694. BABYLON.serializeAsVector3 = serializeAsVector3;
  10695. function serializeAsMeshReference(sourceName) {
  10696. return generateSerializableMember(6, sourceName); // mesh reference member
  10697. }
  10698. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  10699. function serializeAsColorCurves(sourceName) {
  10700. return generateSerializableMember(7, sourceName); // color curves
  10701. }
  10702. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  10703. function serializeAsColor4(sourceName) {
  10704. return generateSerializableMember(8, sourceName); // color 4
  10705. }
  10706. BABYLON.serializeAsColor4 = serializeAsColor4;
  10707. function serializeAsImageProcessingConfiguration(sourceName) {
  10708. return generateSerializableMember(9, sourceName); // image processing
  10709. }
  10710. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  10711. function serializeAsQuaternion(sourceName) {
  10712. return generateSerializableMember(10, sourceName); // quaternion member
  10713. }
  10714. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  10715. /**
  10716. * Decorator used to define property that can be serialized as reference to a camera
  10717. * @param sourceName defines the name of the property to decorate
  10718. */
  10719. function serializeAsCameraReference(sourceName) {
  10720. return generateSerializableMember(11, sourceName); // camera reference member
  10721. }
  10722. BABYLON.serializeAsCameraReference = serializeAsCameraReference;
  10723. /**
  10724. * Class used to help serialization objects
  10725. */
  10726. var SerializationHelper = /** @class */ (function () {
  10727. function SerializationHelper() {
  10728. }
  10729. /**
  10730. * Static function used to serialized a specific entity
  10731. * @param entity defines the entity to serialize
  10732. * @param serializationObject defines the optional target obecjt where serialization data will be stored
  10733. * @returns a JSON compatible object representing the serialization of the entity
  10734. */
  10735. SerializationHelper.Serialize = function (entity, serializationObject) {
  10736. if (!serializationObject) {
  10737. serializationObject = {};
  10738. }
  10739. // Tags
  10740. if (BABYLON.Tags) {
  10741. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  10742. }
  10743. var serializedProperties = getMergedStore(entity);
  10744. // Properties
  10745. for (var property in serializedProperties) {
  10746. var propertyDescriptor = serializedProperties[property];
  10747. var targetPropertyName = propertyDescriptor.sourceName || property;
  10748. var propertyType = propertyDescriptor.type;
  10749. var sourceProperty = entity[property];
  10750. if (sourceProperty !== undefined && sourceProperty !== null) {
  10751. switch (propertyType) {
  10752. case 0: // Value
  10753. serializationObject[targetPropertyName] = sourceProperty;
  10754. break;
  10755. case 1: // Texture
  10756. serializationObject[targetPropertyName] = sourceProperty.serialize();
  10757. break;
  10758. case 2: // Color3
  10759. serializationObject[targetPropertyName] = sourceProperty.asArray();
  10760. break;
  10761. case 3: // FresnelParameters
  10762. serializationObject[targetPropertyName] = sourceProperty.serialize();
  10763. break;
  10764. case 4: // Vector2
  10765. serializationObject[targetPropertyName] = sourceProperty.asArray();
  10766. break;
  10767. case 5: // Vector3
  10768. serializationObject[targetPropertyName] = sourceProperty.asArray();
  10769. break;
  10770. case 6: // Mesh reference
  10771. serializationObject[targetPropertyName] = sourceProperty.id;
  10772. break;
  10773. case 7: // Color Curves
  10774. serializationObject[targetPropertyName] = sourceProperty.serialize();
  10775. break;
  10776. case 8: // Color 4
  10777. serializationObject[targetPropertyName] = sourceProperty.asArray();
  10778. break;
  10779. case 9: // Image Processing
  10780. serializationObject[targetPropertyName] = sourceProperty.serialize();
  10781. break;
  10782. case 10: // Quaternion
  10783. serializationObject[targetPropertyName] = sourceProperty.asArray();
  10784. break;
  10785. case 11: // Camera reference
  10786. serializationObject[targetPropertyName] = sourceProperty.id;
  10787. break;
  10788. }
  10789. }
  10790. }
  10791. return serializationObject;
  10792. };
  10793. /**
  10794. * Creates a new entity from a serialization data object
  10795. * @param creationFunction defines a function used to instanciated the new entity
  10796. * @param source defines the source serialization data
  10797. * @param scene defines the hosting scene
  10798. * @param rootUrl defines the root url for resources
  10799. * @returns a new entity
  10800. */
  10801. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  10802. if (rootUrl === void 0) { rootUrl = null; }
  10803. var destination = creationFunction();
  10804. if (!rootUrl) {
  10805. rootUrl = "";
  10806. }
  10807. // Tags
  10808. if (BABYLON.Tags) {
  10809. BABYLON.Tags.AddTagsTo(destination, source.tags);
  10810. }
  10811. var classStore = getMergedStore(destination);
  10812. // Properties
  10813. for (var property in classStore) {
  10814. var propertyDescriptor = classStore[property];
  10815. var sourceProperty = source[propertyDescriptor.sourceName || property];
  10816. var propertyType = propertyDescriptor.type;
  10817. if (sourceProperty !== undefined && sourceProperty !== null) {
  10818. var dest = destination;
  10819. switch (propertyType) {
  10820. case 0: // Value
  10821. dest[property] = sourceProperty;
  10822. break;
  10823. case 1: // Texture
  10824. if (scene) {
  10825. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  10826. }
  10827. break;
  10828. case 2: // Color3
  10829. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  10830. break;
  10831. case 3: // FresnelParameters
  10832. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  10833. break;
  10834. case 4: // Vector2
  10835. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  10836. break;
  10837. case 5: // Vector3
  10838. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  10839. break;
  10840. case 6: // Mesh reference
  10841. if (scene) {
  10842. dest[property] = scene.getLastMeshByID(sourceProperty);
  10843. }
  10844. break;
  10845. case 7: // Color Curves
  10846. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  10847. break;
  10848. case 8: // Color 4
  10849. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  10850. break;
  10851. case 9: // Image Processing
  10852. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  10853. break;
  10854. case 10: // Quaternion
  10855. dest[property] = BABYLON.Quaternion.FromArray(sourceProperty);
  10856. break;
  10857. case 11: // Camera reference
  10858. if (scene) {
  10859. dest[property] = scene.getCameraByID(sourceProperty);
  10860. }
  10861. break;
  10862. }
  10863. }
  10864. }
  10865. return destination;
  10866. };
  10867. /**
  10868. * Clones an object
  10869. * @param creationFunction defines the function used to instanciate the new object
  10870. * @param source defines the source object
  10871. * @returns the cloned object
  10872. */
  10873. SerializationHelper.Clone = function (creationFunction, source) {
  10874. return _copySource(creationFunction, source, false);
  10875. };
  10876. /**
  10877. * Instanciates a new object based on a source one (some data will be shared between both object)
  10878. * @param creationFunction defines the function used to instanciate the new object
  10879. * @param source defines the source object
  10880. * @returns the new object
  10881. */
  10882. SerializationHelper.Instanciate = function (creationFunction, source) {
  10883. return _copySource(creationFunction, source, true);
  10884. };
  10885. return SerializationHelper;
  10886. }());
  10887. BABYLON.SerializationHelper = SerializationHelper;
  10888. })(BABYLON || (BABYLON = {}));
  10889. //# sourceMappingURL=babylon.decorators.js.map
  10890. var BABYLON;
  10891. (function (BABYLON) {
  10892. /**
  10893. * Wrapper class for promise with external resolve and reject.
  10894. */
  10895. var Deferred = /** @class */ (function () {
  10896. /**
  10897. * Constructor for this deferred object.
  10898. */
  10899. function Deferred() {
  10900. var _this = this;
  10901. this.promise = new Promise(function (resolve, reject) {
  10902. _this._resolve = resolve;
  10903. _this._reject = reject;
  10904. });
  10905. }
  10906. Object.defineProperty(Deferred.prototype, "resolve", {
  10907. /**
  10908. * The resolve method of the promise associated with this deferred object.
  10909. */
  10910. get: function () {
  10911. return this._resolve;
  10912. },
  10913. enumerable: true,
  10914. configurable: true
  10915. });
  10916. Object.defineProperty(Deferred.prototype, "reject", {
  10917. /**
  10918. * The reject method of the promise associated with this deferred object.
  10919. */
  10920. get: function () {
  10921. return this._reject;
  10922. },
  10923. enumerable: true,
  10924. configurable: true
  10925. });
  10926. return Deferred;
  10927. }());
  10928. BABYLON.Deferred = Deferred;
  10929. })(BABYLON || (BABYLON = {}));
  10930. //# sourceMappingURL=babylon.deferred.js.map
  10931. var BABYLON;
  10932. (function (BABYLON) {
  10933. /**
  10934. * A class serves as a medium between the observable and its observers
  10935. */
  10936. var EventState = /** @class */ (function () {
  10937. /**
  10938. * Create a new EventState
  10939. * @param mask defines the mask associated with this state
  10940. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  10941. * @param target defines the original target of the state
  10942. * @param currentTarget defines the current target of the state
  10943. */
  10944. function EventState(mask, skipNextObservers, target, currentTarget) {
  10945. if (skipNextObservers === void 0) { skipNextObservers = false; }
  10946. this.initalize(mask, skipNextObservers, target, currentTarget);
  10947. }
  10948. /**
  10949. * Initialize the current event state
  10950. * @param mask defines the mask associated with this state
  10951. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  10952. * @param target defines the original target of the state
  10953. * @param currentTarget defines the current target of the state
  10954. * @returns the current event state
  10955. */
  10956. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  10957. if (skipNextObservers === void 0) { skipNextObservers = false; }
  10958. this.mask = mask;
  10959. this.skipNextObservers = skipNextObservers;
  10960. this.target = target;
  10961. this.currentTarget = currentTarget;
  10962. return this;
  10963. };
  10964. return EventState;
  10965. }());
  10966. BABYLON.EventState = EventState;
  10967. /**
  10968. * Represent an Observer registered to a given Observable object.
  10969. */
  10970. var Observer = /** @class */ (function () {
  10971. /**
  10972. * Creates a new observer
  10973. * @param callback defines the callback to call when the observer is notified
  10974. * @param mask defines the mask of the observer (used to filter notifications)
  10975. * @param scope defines the current scope used to restore the JS context
  10976. */
  10977. function Observer(
  10978. /**
  10979. * Defines the callback to call when the observer is notified
  10980. */
  10981. callback,
  10982. /**
  10983. * Defines the mask of the observer (used to filter notifications)
  10984. */
  10985. mask,
  10986. /**
  10987. * Defines the current scope used to restore the JS context
  10988. */
  10989. scope) {
  10990. if (scope === void 0) { scope = null; }
  10991. this.callback = callback;
  10992. this.mask = mask;
  10993. this.scope = scope;
  10994. /** @hidden */
  10995. this._willBeUnregistered = false;
  10996. /**
  10997. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  10998. */
  10999. this.unregisterOnNextCall = false;
  11000. }
  11001. return Observer;
  11002. }());
  11003. BABYLON.Observer = Observer;
  11004. /**
  11005. * Represent a list of observers registered to multiple Observables object.
  11006. */
  11007. var MultiObserver = /** @class */ (function () {
  11008. function MultiObserver() {
  11009. }
  11010. /**
  11011. * Release associated resources
  11012. */
  11013. MultiObserver.prototype.dispose = function () {
  11014. if (this._observers && this._observables) {
  11015. for (var index = 0; index < this._observers.length; index++) {
  11016. this._observables[index].remove(this._observers[index]);
  11017. }
  11018. }
  11019. this._observers = null;
  11020. this._observables = null;
  11021. };
  11022. /**
  11023. * Raise a callback when one of the observable will notify
  11024. * @param observables defines a list of observables to watch
  11025. * @param callback defines the callback to call on notification
  11026. * @param mask defines the mask used to filter notifications
  11027. * @param scope defines the current scope used to restore the JS context
  11028. * @returns the new MultiObserver
  11029. */
  11030. MultiObserver.Watch = function (observables, callback, mask, scope) {
  11031. if (mask === void 0) { mask = -1; }
  11032. if (scope === void 0) { scope = null; }
  11033. var result = new MultiObserver();
  11034. result._observers = new Array();
  11035. result._observables = observables;
  11036. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  11037. var observable = observables_1[_i];
  11038. var observer = observable.add(callback, mask, false, scope);
  11039. if (observer) {
  11040. result._observers.push(observer);
  11041. }
  11042. }
  11043. return result;
  11044. };
  11045. return MultiObserver;
  11046. }());
  11047. BABYLON.MultiObserver = MultiObserver;
  11048. /**
  11049. * The Observable class is a simple implementation of the Observable pattern.
  11050. *
  11051. * 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.
  11052. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  11053. * 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).
  11054. * 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.
  11055. */
  11056. var Observable = /** @class */ (function () {
  11057. /**
  11058. * Creates a new observable
  11059. * @param onObserverAdded defines a callback to call when a new observer is added
  11060. */
  11061. function Observable(onObserverAdded) {
  11062. this._observers = new Array();
  11063. this._eventState = new EventState(0);
  11064. if (onObserverAdded) {
  11065. this._onObserverAdded = onObserverAdded;
  11066. }
  11067. }
  11068. /**
  11069. * Create a new Observer with the specified callback
  11070. * @param callback the callback that will be executed for that Observer
  11071. * @param mask the mask used to filter observers
  11072. * @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.
  11073. * @param scope optional scope for the callback to be called from
  11074. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  11075. * @returns the new observer created for the callback
  11076. */
  11077. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  11078. if (mask === void 0) { mask = -1; }
  11079. if (insertFirst === void 0) { insertFirst = false; }
  11080. if (scope === void 0) { scope = null; }
  11081. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  11082. if (!callback) {
  11083. return null;
  11084. }
  11085. var observer = new Observer(callback, mask, scope);
  11086. observer.unregisterOnNextCall = unregisterOnFirstCall;
  11087. if (insertFirst) {
  11088. this._observers.unshift(observer);
  11089. }
  11090. else {
  11091. this._observers.push(observer);
  11092. }
  11093. if (this._onObserverAdded) {
  11094. this._onObserverAdded(observer);
  11095. }
  11096. return observer;
  11097. };
  11098. /**
  11099. * Create a new Observer with the specified callback and unregisters after the next notification
  11100. * @param callback the callback that will be executed for that Observer
  11101. * @returns the new observer created for the callback
  11102. */
  11103. Observable.prototype.addOnce = function (callback) {
  11104. return this.add(callback, undefined, undefined, undefined, true);
  11105. };
  11106. /**
  11107. * Remove an Observer from the Observable object
  11108. * @param observer the instance of the Observer to remove
  11109. * @returns false if it doesn't belong to this Observable
  11110. */
  11111. Observable.prototype.remove = function (observer) {
  11112. if (!observer) {
  11113. return false;
  11114. }
  11115. var index = this._observers.indexOf(observer);
  11116. if (index !== -1) {
  11117. this._deferUnregister(observer);
  11118. return true;
  11119. }
  11120. return false;
  11121. };
  11122. /**
  11123. * Remove a callback from the Observable object
  11124. * @param callback the callback to remove
  11125. * @param scope optional scope. If used only the callbacks with this scope will be removed
  11126. * @returns false if it doesn't belong to this Observable
  11127. */
  11128. Observable.prototype.removeCallback = function (callback, scope) {
  11129. for (var index = 0; index < this._observers.length; index++) {
  11130. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  11131. this._deferUnregister(this._observers[index]);
  11132. return true;
  11133. }
  11134. }
  11135. return false;
  11136. };
  11137. Observable.prototype._deferUnregister = function (observer) {
  11138. var _this = this;
  11139. observer.unregisterOnNextCall = false;
  11140. observer._willBeUnregistered = true;
  11141. BABYLON.Tools.SetImmediate(function () {
  11142. _this._remove(observer);
  11143. });
  11144. };
  11145. // This should only be called when not iterating over _observers to avoid callback skipping.
  11146. // Removes an observer from the _observer Array.
  11147. Observable.prototype._remove = function (observer) {
  11148. if (!observer) {
  11149. return false;
  11150. }
  11151. var index = this._observers.indexOf(observer);
  11152. if (index !== -1) {
  11153. this._observers.splice(index, 1);
  11154. return true;
  11155. }
  11156. return false;
  11157. };
  11158. /**
  11159. * Notify all Observers by calling their respective callback with the given data
  11160. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  11161. * @param eventData defines the data to send to all observers
  11162. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  11163. * @param target defines the original target of the state
  11164. * @param currentTarget defines the current target of the state
  11165. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  11166. */
  11167. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  11168. if (mask === void 0) { mask = -1; }
  11169. if (!this._observers.length) {
  11170. return true;
  11171. }
  11172. var state = this._eventState;
  11173. state.mask = mask;
  11174. state.target = target;
  11175. state.currentTarget = currentTarget;
  11176. state.skipNextObservers = false;
  11177. state.lastReturnValue = eventData;
  11178. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  11179. var obs = _a[_i];
  11180. if (obs._willBeUnregistered) {
  11181. continue;
  11182. }
  11183. if (obs.mask & mask) {
  11184. if (obs.scope) {
  11185. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  11186. }
  11187. else {
  11188. state.lastReturnValue = obs.callback(eventData, state);
  11189. }
  11190. if (obs.unregisterOnNextCall) {
  11191. this._deferUnregister(obs);
  11192. }
  11193. }
  11194. if (state.skipNextObservers) {
  11195. return false;
  11196. }
  11197. }
  11198. return true;
  11199. };
  11200. /**
  11201. * Calling this will execute each callback, expecting it to be a promise or return a value.
  11202. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  11203. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  11204. * and it is crucial that all callbacks will be executed.
  11205. * The order of the callbacks is kept, callbacks are not executed parallel.
  11206. *
  11207. * @param eventData The data to be sent to each callback
  11208. * @param mask is used to filter observers defaults to -1
  11209. * @param target defines the callback target (see EventState)
  11210. * @param currentTarget defines he current object in the bubbling phase
  11211. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  11212. */
  11213. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  11214. var _this = this;
  11215. if (mask === void 0) { mask = -1; }
  11216. // create an empty promise
  11217. var p = Promise.resolve(eventData);
  11218. // no observers? return this promise.
  11219. if (!this._observers.length) {
  11220. return p;
  11221. }
  11222. var state = this._eventState;
  11223. state.mask = mask;
  11224. state.target = target;
  11225. state.currentTarget = currentTarget;
  11226. state.skipNextObservers = false;
  11227. // execute one callback after another (not using Promise.all, the order is important)
  11228. this._observers.forEach(function (obs) {
  11229. if (state.skipNextObservers) {
  11230. return;
  11231. }
  11232. if (obs._willBeUnregistered) {
  11233. return;
  11234. }
  11235. if (obs.mask & mask) {
  11236. if (obs.scope) {
  11237. p = p.then(function (lastReturnedValue) {
  11238. state.lastReturnValue = lastReturnedValue;
  11239. return obs.callback.apply(obs.scope, [eventData, state]);
  11240. });
  11241. }
  11242. else {
  11243. p = p.then(function (lastReturnedValue) {
  11244. state.lastReturnValue = lastReturnedValue;
  11245. return obs.callback(eventData, state);
  11246. });
  11247. }
  11248. if (obs.unregisterOnNextCall) {
  11249. _this._deferUnregister(obs);
  11250. }
  11251. }
  11252. });
  11253. // return the eventData
  11254. return p.then(function () { return eventData; });
  11255. };
  11256. /**
  11257. * Notify a specific observer
  11258. * @param observer defines the observer to notify
  11259. * @param eventData defines the data to be sent to each callback
  11260. * @param mask is used to filter observers defaults to -1
  11261. */
  11262. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  11263. if (mask === void 0) { mask = -1; }
  11264. var state = this._eventState;
  11265. state.mask = mask;
  11266. state.skipNextObservers = false;
  11267. observer.callback(eventData, state);
  11268. };
  11269. /**
  11270. * Gets a boolean indicating if the observable has at least one observer
  11271. * @returns true is the Observable has at least one Observer registered
  11272. */
  11273. Observable.prototype.hasObservers = function () {
  11274. return this._observers.length > 0;
  11275. };
  11276. /**
  11277. * Clear the list of observers
  11278. */
  11279. Observable.prototype.clear = function () {
  11280. this._observers = new Array();
  11281. this._onObserverAdded = null;
  11282. };
  11283. /**
  11284. * Clone the current observable
  11285. * @returns a new observable
  11286. */
  11287. Observable.prototype.clone = function () {
  11288. var result = new Observable();
  11289. result._observers = this._observers.slice(0);
  11290. return result;
  11291. };
  11292. /**
  11293. * Does this observable handles observer registered with a given mask
  11294. * @param mask defines the mask to be tested
  11295. * @return whether or not one observer registered with the given mask is handeled
  11296. **/
  11297. Observable.prototype.hasSpecificMask = function (mask) {
  11298. if (mask === void 0) { mask = -1; }
  11299. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  11300. var obs = _a[_i];
  11301. if (obs.mask & mask || obs.mask === mask) {
  11302. return true;
  11303. }
  11304. }
  11305. return false;
  11306. };
  11307. return Observable;
  11308. }());
  11309. BABYLON.Observable = Observable;
  11310. })(BABYLON || (BABYLON = {}));
  11311. //# sourceMappingURL=babylon.observable.js.map
  11312. var BABYLON;
  11313. (function (BABYLON) {
  11314. /**
  11315. * Defines an GC Friendly array where the backfield array do not shrink to prevent over allocations.
  11316. */
  11317. var SmartArray = /** @class */ (function () {
  11318. /**
  11319. * Instantiates a Smart Array.
  11320. * @param capacity defines the default capacity of the array.
  11321. */
  11322. function SmartArray(capacity) {
  11323. /**
  11324. * The active length of the array.
  11325. */
  11326. this.length = 0;
  11327. this.data = new Array(capacity);
  11328. this._id = SmartArray._GlobalId++;
  11329. }
  11330. /**
  11331. * Pushes a value at the end of the active data.
  11332. * @param value defines the object to push in the array.
  11333. */
  11334. SmartArray.prototype.push = function (value) {
  11335. this.data[this.length++] = value;
  11336. if (this.length > this.data.length) {
  11337. this.data.length *= 2;
  11338. }
  11339. };
  11340. /**
  11341. * Iterates over the active data and apply the lambda to them.
  11342. * @param func defines the action to apply on each value.
  11343. */
  11344. SmartArray.prototype.forEach = function (func) {
  11345. for (var index = 0; index < this.length; index++) {
  11346. func(this.data[index]);
  11347. }
  11348. };
  11349. /**
  11350. * Sorts the full sets of data.
  11351. * @param compareFn defines the comparison function to apply.
  11352. */
  11353. SmartArray.prototype.sort = function (compareFn) {
  11354. this.data.sort(compareFn);
  11355. };
  11356. /**
  11357. * Resets the active data to an empty array.
  11358. */
  11359. SmartArray.prototype.reset = function () {
  11360. this.length = 0;
  11361. };
  11362. /**
  11363. * Releases all the data from the array as well as the array.
  11364. */
  11365. SmartArray.prototype.dispose = function () {
  11366. this.reset();
  11367. if (this.data) {
  11368. this.data.length = 0;
  11369. this.data = [];
  11370. }
  11371. };
  11372. /**
  11373. * Concats the active data with a given array.
  11374. * @param array defines the data to concatenate with.
  11375. */
  11376. SmartArray.prototype.concat = function (array) {
  11377. if (array.length === 0) {
  11378. return;
  11379. }
  11380. if (this.length + array.length > this.data.length) {
  11381. this.data.length = (this.length + array.length) * 2;
  11382. }
  11383. for (var index = 0; index < array.length; index++) {
  11384. this.data[this.length++] = (array.data || array)[index];
  11385. }
  11386. };
  11387. /**
  11388. * Returns the position of a value in the active data.
  11389. * @param value defines the value to find the index for
  11390. * @returns the index if found in the active data otherwise -1
  11391. */
  11392. SmartArray.prototype.indexOf = function (value) {
  11393. var position = this.data.indexOf(value);
  11394. if (position >= this.length) {
  11395. return -1;
  11396. }
  11397. return position;
  11398. };
  11399. /**
  11400. * Returns whether an element is part of the active data.
  11401. * @param value defines the value to look for
  11402. * @returns true if found in the active data otherwise false
  11403. */
  11404. SmartArray.prototype.contains = function (value) {
  11405. return this.indexOf(value) !== -1;
  11406. };
  11407. // Statics
  11408. SmartArray._GlobalId = 0;
  11409. return SmartArray;
  11410. }());
  11411. BABYLON.SmartArray = SmartArray;
  11412. /**
  11413. * Defines an GC Friendly array where the backfield array do not shrink to prevent over allocations.
  11414. * The data in this array can only be present once
  11415. */
  11416. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  11417. __extends(SmartArrayNoDuplicate, _super);
  11418. function SmartArrayNoDuplicate() {
  11419. var _this = _super !== null && _super.apply(this, arguments) || this;
  11420. _this._duplicateId = 0;
  11421. return _this;
  11422. }
  11423. /**
  11424. * Pushes a value at the end of the active data.
  11425. * THIS DOES NOT PREVENT DUPPLICATE DATA
  11426. * @param value defines the object to push in the array.
  11427. */
  11428. SmartArrayNoDuplicate.prototype.push = function (value) {
  11429. _super.prototype.push.call(this, value);
  11430. if (!value.__smartArrayFlags) {
  11431. value.__smartArrayFlags = {};
  11432. }
  11433. value.__smartArrayFlags[this._id] = this._duplicateId;
  11434. };
  11435. /**
  11436. * Pushes a value at the end of the active data.
  11437. * If the data is already present, it won t be added again
  11438. * @param value defines the object to push in the array.
  11439. * @returns true if added false if it was already present
  11440. */
  11441. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  11442. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  11443. return false;
  11444. }
  11445. this.push(value);
  11446. return true;
  11447. };
  11448. /**
  11449. * Resets the active data to an empty array.
  11450. */
  11451. SmartArrayNoDuplicate.prototype.reset = function () {
  11452. _super.prototype.reset.call(this);
  11453. this._duplicateId++;
  11454. };
  11455. /**
  11456. * Concats the active data with a given array.
  11457. * This ensures no dupplicate will be present in the result.
  11458. * @param array defines the data to concatenate with.
  11459. */
  11460. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  11461. if (array.length === 0) {
  11462. return;
  11463. }
  11464. if (this.length + array.length > this.data.length) {
  11465. this.data.length = (this.length + array.length) * 2;
  11466. }
  11467. for (var index = 0; index < array.length; index++) {
  11468. var item = (array.data || array)[index];
  11469. this.pushNoDuplicate(item);
  11470. }
  11471. };
  11472. return SmartArrayNoDuplicate;
  11473. }(SmartArray));
  11474. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  11475. })(BABYLON || (BABYLON = {}));
  11476. //# sourceMappingURL=babylon.smartArray.js.map
  11477. var BABYLON;
  11478. (function (BABYLON) {
  11479. var PromiseStates;
  11480. (function (PromiseStates) {
  11481. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  11482. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  11483. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  11484. })(PromiseStates || (PromiseStates = {}));
  11485. var FulFillmentAgregator = /** @class */ (function () {
  11486. function FulFillmentAgregator() {
  11487. this.count = 0;
  11488. this.target = 0;
  11489. this.results = [];
  11490. }
  11491. return FulFillmentAgregator;
  11492. }());
  11493. var InternalPromise = /** @class */ (function () {
  11494. function InternalPromise(resolver) {
  11495. var _this = this;
  11496. this._state = PromiseStates.Pending;
  11497. this._children = new Array();
  11498. this._rejectWasConsumed = false;
  11499. if (!resolver) {
  11500. return;
  11501. }
  11502. try {
  11503. resolver(function (value) {
  11504. _this._resolve(value);
  11505. }, function (reason) {
  11506. _this._reject(reason);
  11507. });
  11508. }
  11509. catch (e) {
  11510. this._reject(e);
  11511. }
  11512. }
  11513. Object.defineProperty(InternalPromise.prototype, "_result", {
  11514. get: function () {
  11515. return this._resultValue;
  11516. },
  11517. set: function (value) {
  11518. this._resultValue = value;
  11519. if (this._parent && this._parent._result === undefined) {
  11520. this._parent._result = value;
  11521. }
  11522. },
  11523. enumerable: true,
  11524. configurable: true
  11525. });
  11526. InternalPromise.prototype.catch = function (onRejected) {
  11527. return this.then(undefined, onRejected);
  11528. };
  11529. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  11530. var _this = this;
  11531. var newPromise = new InternalPromise();
  11532. newPromise._onFulfilled = onFulfilled;
  11533. newPromise._onRejected = onRejected;
  11534. // Composition
  11535. this._children.push(newPromise);
  11536. newPromise._parent = this;
  11537. if (this._state !== PromiseStates.Pending) {
  11538. BABYLON.Tools.SetImmediate(function () {
  11539. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  11540. var returnedValue = newPromise._resolve(_this._result);
  11541. if (returnedValue !== undefined && returnedValue !== null) {
  11542. if (returnedValue._state !== undefined) {
  11543. var returnedPromise = returnedValue;
  11544. newPromise._children.push(returnedPromise);
  11545. returnedPromise._parent = newPromise;
  11546. newPromise = returnedPromise;
  11547. }
  11548. else {
  11549. newPromise._result = returnedValue;
  11550. }
  11551. }
  11552. }
  11553. else {
  11554. newPromise._reject(_this._reason);
  11555. }
  11556. });
  11557. }
  11558. return newPromise;
  11559. };
  11560. InternalPromise.prototype._moveChildren = function (children) {
  11561. var _this = this;
  11562. var _a;
  11563. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  11564. this._children.forEach(function (child) {
  11565. child._parent = _this;
  11566. });
  11567. if (this._state === PromiseStates.Fulfilled) {
  11568. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  11569. var child = _b[_i];
  11570. child._resolve(this._result);
  11571. }
  11572. }
  11573. else if (this._state === PromiseStates.Rejected) {
  11574. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  11575. var child = _d[_c];
  11576. child._reject(this._reason);
  11577. }
  11578. }
  11579. };
  11580. InternalPromise.prototype._resolve = function (value) {
  11581. try {
  11582. this._state = PromiseStates.Fulfilled;
  11583. var returnedValue = null;
  11584. if (this._onFulfilled) {
  11585. returnedValue = this._onFulfilled(value);
  11586. }
  11587. if (returnedValue !== undefined && returnedValue !== null) {
  11588. if (returnedValue._state !== undefined) {
  11589. // Transmit children
  11590. var returnedPromise = returnedValue;
  11591. returnedPromise._parent = this;
  11592. returnedPromise._moveChildren(this._children);
  11593. value = returnedPromise._result;
  11594. }
  11595. else {
  11596. value = returnedValue;
  11597. }
  11598. }
  11599. this._result = value;
  11600. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  11601. var child = _a[_i];
  11602. child._resolve(value);
  11603. }
  11604. this._children.length = 0;
  11605. delete this._onFulfilled;
  11606. delete this._onRejected;
  11607. }
  11608. catch (e) {
  11609. this._reject(e, true);
  11610. }
  11611. };
  11612. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  11613. if (onLocalThrow === void 0) { onLocalThrow = false; }
  11614. this._state = PromiseStates.Rejected;
  11615. this._reason = reason;
  11616. if (this._onRejected && !onLocalThrow) {
  11617. try {
  11618. this._onRejected(reason);
  11619. this._rejectWasConsumed = true;
  11620. }
  11621. catch (e) {
  11622. reason = e;
  11623. }
  11624. }
  11625. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  11626. var child = _a[_i];
  11627. if (this._rejectWasConsumed) {
  11628. child._resolve(null);
  11629. }
  11630. else {
  11631. child._reject(reason);
  11632. }
  11633. }
  11634. this._children.length = 0;
  11635. delete this._onFulfilled;
  11636. delete this._onRejected;
  11637. };
  11638. InternalPromise.resolve = function (value) {
  11639. var newPromise = new InternalPromise();
  11640. newPromise._resolve(value);
  11641. return newPromise;
  11642. };
  11643. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  11644. promise.then(function (value) {
  11645. agregator.results[index] = value;
  11646. agregator.count++;
  11647. if (agregator.count === agregator.target) {
  11648. agregator.rootPromise._resolve(agregator.results);
  11649. }
  11650. return null;
  11651. }, function (reason) {
  11652. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  11653. agregator.rootPromise._reject(reason);
  11654. }
  11655. });
  11656. };
  11657. InternalPromise.all = function (promises) {
  11658. var newPromise = new InternalPromise();
  11659. var agregator = new FulFillmentAgregator();
  11660. agregator.target = promises.length;
  11661. agregator.rootPromise = newPromise;
  11662. if (promises.length) {
  11663. for (var index = 0; index < promises.length; index++) {
  11664. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  11665. }
  11666. }
  11667. else {
  11668. newPromise._resolve([]);
  11669. }
  11670. return newPromise;
  11671. };
  11672. InternalPromise.race = function (promises) {
  11673. var newPromise = new InternalPromise();
  11674. if (promises.length) {
  11675. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  11676. var promise = promises_1[_i];
  11677. promise.then(function (value) {
  11678. if (newPromise) {
  11679. newPromise._resolve(value);
  11680. newPromise = null;
  11681. }
  11682. return null;
  11683. }, function (reason) {
  11684. if (newPromise) {
  11685. newPromise._reject(reason);
  11686. newPromise = null;
  11687. }
  11688. });
  11689. }
  11690. }
  11691. return newPromise;
  11692. };
  11693. return InternalPromise;
  11694. }());
  11695. /**
  11696. * Helper class that provides a small promise polyfill
  11697. */
  11698. var PromisePolyfill = /** @class */ (function () {
  11699. function PromisePolyfill() {
  11700. }
  11701. /**
  11702. * Static function used to check if the polyfill is required
  11703. * If this is the case then the function will inject the polyfill to window.Promise
  11704. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  11705. */
  11706. PromisePolyfill.Apply = function (force) {
  11707. if (force === void 0) { force = false; }
  11708. if (force || typeof Promise === 'undefined') {
  11709. var root = window;
  11710. root.Promise = InternalPromise;
  11711. }
  11712. };
  11713. return PromisePolyfill;
  11714. }());
  11715. BABYLON.PromisePolyfill = PromisePolyfill;
  11716. })(BABYLON || (BABYLON = {}));
  11717. //# sourceMappingURL=babylon.promise.js.map
  11718. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  11719. var BABYLON;
  11720. (function (BABYLON) {
  11721. /**
  11722. * Helper class to push actions to a pool of workers.
  11723. */
  11724. var WorkerPool = /** @class */ (function () {
  11725. /**
  11726. * Constructor
  11727. * @param workers Array of workers to use for actions
  11728. */
  11729. function WorkerPool(workers) {
  11730. this._pendingActions = new Array();
  11731. this._workerInfos = workers.map(function (worker) { return ({
  11732. worker: worker,
  11733. active: false
  11734. }); });
  11735. }
  11736. /**
  11737. * Terminates all workers and clears any pending actions.
  11738. */
  11739. WorkerPool.prototype.dispose = function () {
  11740. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  11741. var workerInfo = _a[_i];
  11742. workerInfo.worker.terminate();
  11743. }
  11744. delete this._workerInfos;
  11745. delete this._pendingActions;
  11746. };
  11747. /**
  11748. * Pushes an action to the worker pool. If all the workers are active, the action will be
  11749. * pended until a worker has completed its action.
  11750. * @param action The action to perform. Call onComplete when the action is complete.
  11751. */
  11752. WorkerPool.prototype.push = function (action) {
  11753. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  11754. var workerInfo = _a[_i];
  11755. if (!workerInfo.active) {
  11756. this._execute(workerInfo, action);
  11757. return;
  11758. }
  11759. }
  11760. this._pendingActions.push(action);
  11761. };
  11762. WorkerPool.prototype._execute = function (workerInfo, action) {
  11763. var _this = this;
  11764. workerInfo.active = true;
  11765. action(workerInfo.worker, function () {
  11766. workerInfo.active = false;
  11767. var nextAction = _this._pendingActions.shift();
  11768. if (nextAction) {
  11769. _this._execute(workerInfo, nextAction);
  11770. }
  11771. });
  11772. };
  11773. return WorkerPool;
  11774. }());
  11775. BABYLON.WorkerPool = WorkerPool;
  11776. })(BABYLON || (BABYLON = {}));
  11777. //# sourceMappingURL=babylon.workerPool.js.map
  11778. var BABYLON;
  11779. (function (BABYLON) {
  11780. /**
  11781. * @hidden
  11782. **/
  11783. var _AlphaState = /** @class */ (function () {
  11784. /**
  11785. * Initializes the state.
  11786. */
  11787. function _AlphaState() {
  11788. this._isAlphaBlendDirty = false;
  11789. this._isBlendFunctionParametersDirty = false;
  11790. this._isBlendEquationParametersDirty = false;
  11791. this._isBlendConstantsDirty = false;
  11792. this._alphaBlend = false;
  11793. this._blendFunctionParameters = new Array(4);
  11794. this._blendEquationParameters = new Array(2);
  11795. this._blendConstants = new Array(4);
  11796. this.reset();
  11797. }
  11798. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  11799. get: function () {
  11800. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  11801. },
  11802. enumerable: true,
  11803. configurable: true
  11804. });
  11805. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  11806. get: function () {
  11807. return this._alphaBlend;
  11808. },
  11809. set: function (value) {
  11810. if (this._alphaBlend === value) {
  11811. return;
  11812. }
  11813. this._alphaBlend = value;
  11814. this._isAlphaBlendDirty = true;
  11815. },
  11816. enumerable: true,
  11817. configurable: true
  11818. });
  11819. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  11820. if (this._blendConstants[0] === r &&
  11821. this._blendConstants[1] === g &&
  11822. this._blendConstants[2] === b &&
  11823. this._blendConstants[3] === a) {
  11824. return;
  11825. }
  11826. this._blendConstants[0] = r;
  11827. this._blendConstants[1] = g;
  11828. this._blendConstants[2] = b;
  11829. this._blendConstants[3] = a;
  11830. this._isBlendConstantsDirty = true;
  11831. };
  11832. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  11833. if (this._blendFunctionParameters[0] === value0 &&
  11834. this._blendFunctionParameters[1] === value1 &&
  11835. this._blendFunctionParameters[2] === value2 &&
  11836. this._blendFunctionParameters[3] === value3) {
  11837. return;
  11838. }
  11839. this._blendFunctionParameters[0] = value0;
  11840. this._blendFunctionParameters[1] = value1;
  11841. this._blendFunctionParameters[2] = value2;
  11842. this._blendFunctionParameters[3] = value3;
  11843. this._isBlendFunctionParametersDirty = true;
  11844. };
  11845. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  11846. if (this._blendEquationParameters[0] === rgb &&
  11847. this._blendEquationParameters[1] === alpha) {
  11848. return;
  11849. }
  11850. this._blendEquationParameters[0] = rgb;
  11851. this._blendEquationParameters[1] = alpha;
  11852. this._isBlendEquationParametersDirty = true;
  11853. };
  11854. _AlphaState.prototype.reset = function () {
  11855. this._alphaBlend = false;
  11856. this._blendFunctionParameters[0] = null;
  11857. this._blendFunctionParameters[1] = null;
  11858. this._blendFunctionParameters[2] = null;
  11859. this._blendFunctionParameters[3] = null;
  11860. this._blendEquationParameters[0] = null;
  11861. this._blendEquationParameters[1] = null;
  11862. this._blendConstants[0] = null;
  11863. this._blendConstants[1] = null;
  11864. this._blendConstants[2] = null;
  11865. this._blendConstants[3] = null;
  11866. this._isAlphaBlendDirty = true;
  11867. this._isBlendFunctionParametersDirty = false;
  11868. this._isBlendEquationParametersDirty = false;
  11869. this._isBlendConstantsDirty = false;
  11870. };
  11871. _AlphaState.prototype.apply = function (gl) {
  11872. if (!this.isDirty) {
  11873. return;
  11874. }
  11875. // Alpha blend
  11876. if (this._isAlphaBlendDirty) {
  11877. if (this._alphaBlend) {
  11878. gl.enable(gl.BLEND);
  11879. }
  11880. else {
  11881. gl.disable(gl.BLEND);
  11882. }
  11883. this._isAlphaBlendDirty = false;
  11884. }
  11885. // Alpha function
  11886. if (this._isBlendFunctionParametersDirty) {
  11887. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  11888. this._isBlendFunctionParametersDirty = false;
  11889. }
  11890. // Alpha equation
  11891. if (this._isBlendEquationParametersDirty) {
  11892. gl.blendEquationSeparate(this._blendEquationParameters[0], this._blendEquationParameters[1]);
  11893. this._isBlendEquationParametersDirty = false;
  11894. }
  11895. // Constants
  11896. if (this._isBlendConstantsDirty) {
  11897. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  11898. this._isBlendConstantsDirty = false;
  11899. }
  11900. };
  11901. return _AlphaState;
  11902. }());
  11903. BABYLON._AlphaState = _AlphaState;
  11904. })(BABYLON || (BABYLON = {}));
  11905. //# sourceMappingURL=babylon.alphaCullingState.js.map
  11906. var BABYLON;
  11907. (function (BABYLON) {
  11908. /**
  11909. * @hidden
  11910. **/
  11911. var _DepthCullingState = /** @class */ (function () {
  11912. /**
  11913. * Initializes the state.
  11914. */
  11915. function _DepthCullingState() {
  11916. this._isDepthTestDirty = false;
  11917. this._isDepthMaskDirty = false;
  11918. this._isDepthFuncDirty = false;
  11919. this._isCullFaceDirty = false;
  11920. this._isCullDirty = false;
  11921. this._isZOffsetDirty = false;
  11922. this._isFrontFaceDirty = false;
  11923. this.reset();
  11924. }
  11925. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  11926. get: function () {
  11927. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  11928. },
  11929. enumerable: true,
  11930. configurable: true
  11931. });
  11932. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  11933. get: function () {
  11934. return this._zOffset;
  11935. },
  11936. set: function (value) {
  11937. if (this._zOffset === value) {
  11938. return;
  11939. }
  11940. this._zOffset = value;
  11941. this._isZOffsetDirty = true;
  11942. },
  11943. enumerable: true,
  11944. configurable: true
  11945. });
  11946. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  11947. get: function () {
  11948. return this._cullFace;
  11949. },
  11950. set: function (value) {
  11951. if (this._cullFace === value) {
  11952. return;
  11953. }
  11954. this._cullFace = value;
  11955. this._isCullFaceDirty = true;
  11956. },
  11957. enumerable: true,
  11958. configurable: true
  11959. });
  11960. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  11961. get: function () {
  11962. return this._cull;
  11963. },
  11964. set: function (value) {
  11965. if (this._cull === value) {
  11966. return;
  11967. }
  11968. this._cull = value;
  11969. this._isCullDirty = true;
  11970. },
  11971. enumerable: true,
  11972. configurable: true
  11973. });
  11974. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  11975. get: function () {
  11976. return this._depthFunc;
  11977. },
  11978. set: function (value) {
  11979. if (this._depthFunc === value) {
  11980. return;
  11981. }
  11982. this._depthFunc = value;
  11983. this._isDepthFuncDirty = true;
  11984. },
  11985. enumerable: true,
  11986. configurable: true
  11987. });
  11988. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  11989. get: function () {
  11990. return this._depthMask;
  11991. },
  11992. set: function (value) {
  11993. if (this._depthMask === value) {
  11994. return;
  11995. }
  11996. this._depthMask = value;
  11997. this._isDepthMaskDirty = true;
  11998. },
  11999. enumerable: true,
  12000. configurable: true
  12001. });
  12002. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  12003. get: function () {
  12004. return this._depthTest;
  12005. },
  12006. set: function (value) {
  12007. if (this._depthTest === value) {
  12008. return;
  12009. }
  12010. this._depthTest = value;
  12011. this._isDepthTestDirty = true;
  12012. },
  12013. enumerable: true,
  12014. configurable: true
  12015. });
  12016. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  12017. get: function () {
  12018. return this._frontFace;
  12019. },
  12020. set: function (value) {
  12021. if (this._frontFace === value) {
  12022. return;
  12023. }
  12024. this._frontFace = value;
  12025. this._isFrontFaceDirty = true;
  12026. },
  12027. enumerable: true,
  12028. configurable: true
  12029. });
  12030. _DepthCullingState.prototype.reset = function () {
  12031. this._depthMask = true;
  12032. this._depthTest = true;
  12033. this._depthFunc = null;
  12034. this._cullFace = null;
  12035. this._cull = null;
  12036. this._zOffset = 0;
  12037. this._frontFace = null;
  12038. this._isDepthTestDirty = true;
  12039. this._isDepthMaskDirty = true;
  12040. this._isDepthFuncDirty = false;
  12041. this._isCullFaceDirty = false;
  12042. this._isCullDirty = false;
  12043. this._isZOffsetDirty = false;
  12044. this._isFrontFaceDirty = false;
  12045. };
  12046. _DepthCullingState.prototype.apply = function (gl) {
  12047. if (!this.isDirty) {
  12048. return;
  12049. }
  12050. // Cull
  12051. if (this._isCullDirty) {
  12052. if (this.cull) {
  12053. gl.enable(gl.CULL_FACE);
  12054. }
  12055. else {
  12056. gl.disable(gl.CULL_FACE);
  12057. }
  12058. this._isCullDirty = false;
  12059. }
  12060. // Cull face
  12061. if (this._isCullFaceDirty) {
  12062. gl.cullFace(this.cullFace);
  12063. this._isCullFaceDirty = false;
  12064. }
  12065. // Depth mask
  12066. if (this._isDepthMaskDirty) {
  12067. gl.depthMask(this.depthMask);
  12068. this._isDepthMaskDirty = false;
  12069. }
  12070. // Depth test
  12071. if (this._isDepthTestDirty) {
  12072. if (this.depthTest) {
  12073. gl.enable(gl.DEPTH_TEST);
  12074. }
  12075. else {
  12076. gl.disable(gl.DEPTH_TEST);
  12077. }
  12078. this._isDepthTestDirty = false;
  12079. }
  12080. // Depth func
  12081. if (this._isDepthFuncDirty) {
  12082. gl.depthFunc(this.depthFunc);
  12083. this._isDepthFuncDirty = false;
  12084. }
  12085. // zOffset
  12086. if (this._isZOffsetDirty) {
  12087. if (this.zOffset) {
  12088. gl.enable(gl.POLYGON_OFFSET_FILL);
  12089. gl.polygonOffset(this.zOffset, 0);
  12090. }
  12091. else {
  12092. gl.disable(gl.POLYGON_OFFSET_FILL);
  12093. }
  12094. this._isZOffsetDirty = false;
  12095. }
  12096. // Front face
  12097. if (this._isFrontFaceDirty) {
  12098. gl.frontFace(this.frontFace);
  12099. this._isFrontFaceDirty = false;
  12100. }
  12101. };
  12102. return _DepthCullingState;
  12103. }());
  12104. BABYLON._DepthCullingState = _DepthCullingState;
  12105. })(BABYLON || (BABYLON = {}));
  12106. //# sourceMappingURL=babylon.depthCullingState.js.map
  12107. var BABYLON;
  12108. (function (BABYLON) {
  12109. /**
  12110. * @hidden
  12111. **/
  12112. var _StencilState = /** @class */ (function () {
  12113. function _StencilState() {
  12114. this._isStencilTestDirty = false;
  12115. this._isStencilMaskDirty = false;
  12116. this._isStencilFuncDirty = false;
  12117. this._isStencilOpDirty = false;
  12118. this.reset();
  12119. }
  12120. Object.defineProperty(_StencilState.prototype, "isDirty", {
  12121. get: function () {
  12122. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  12123. },
  12124. enumerable: true,
  12125. configurable: true
  12126. });
  12127. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  12128. get: function () {
  12129. return this._stencilFunc;
  12130. },
  12131. set: function (value) {
  12132. if (this._stencilFunc === value) {
  12133. return;
  12134. }
  12135. this._stencilFunc = value;
  12136. this._isStencilFuncDirty = true;
  12137. },
  12138. enumerable: true,
  12139. configurable: true
  12140. });
  12141. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  12142. get: function () {
  12143. return this._stencilFuncRef;
  12144. },
  12145. set: function (value) {
  12146. if (this._stencilFuncRef === value) {
  12147. return;
  12148. }
  12149. this._stencilFuncRef = value;
  12150. this._isStencilFuncDirty = true;
  12151. },
  12152. enumerable: true,
  12153. configurable: true
  12154. });
  12155. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  12156. get: function () {
  12157. return this._stencilFuncMask;
  12158. },
  12159. set: function (value) {
  12160. if (this._stencilFuncMask === value) {
  12161. return;
  12162. }
  12163. this._stencilFuncMask = value;
  12164. this._isStencilFuncDirty = true;
  12165. },
  12166. enumerable: true,
  12167. configurable: true
  12168. });
  12169. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  12170. get: function () {
  12171. return this._stencilOpStencilFail;
  12172. },
  12173. set: function (value) {
  12174. if (this._stencilOpStencilFail === value) {
  12175. return;
  12176. }
  12177. this._stencilOpStencilFail = value;
  12178. this._isStencilOpDirty = true;
  12179. },
  12180. enumerable: true,
  12181. configurable: true
  12182. });
  12183. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  12184. get: function () {
  12185. return this._stencilOpDepthFail;
  12186. },
  12187. set: function (value) {
  12188. if (this._stencilOpDepthFail === value) {
  12189. return;
  12190. }
  12191. this._stencilOpDepthFail = value;
  12192. this._isStencilOpDirty = true;
  12193. },
  12194. enumerable: true,
  12195. configurable: true
  12196. });
  12197. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  12198. get: function () {
  12199. return this._stencilOpStencilDepthPass;
  12200. },
  12201. set: function (value) {
  12202. if (this._stencilOpStencilDepthPass === value) {
  12203. return;
  12204. }
  12205. this._stencilOpStencilDepthPass = value;
  12206. this._isStencilOpDirty = true;
  12207. },
  12208. enumerable: true,
  12209. configurable: true
  12210. });
  12211. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  12212. get: function () {
  12213. return this._stencilMask;
  12214. },
  12215. set: function (value) {
  12216. if (this._stencilMask === value) {
  12217. return;
  12218. }
  12219. this._stencilMask = value;
  12220. this._isStencilMaskDirty = true;
  12221. },
  12222. enumerable: true,
  12223. configurable: true
  12224. });
  12225. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  12226. get: function () {
  12227. return this._stencilTest;
  12228. },
  12229. set: function (value) {
  12230. if (this._stencilTest === value) {
  12231. return;
  12232. }
  12233. this._stencilTest = value;
  12234. this._isStencilTestDirty = true;
  12235. },
  12236. enumerable: true,
  12237. configurable: true
  12238. });
  12239. _StencilState.prototype.reset = function () {
  12240. this._stencilTest = false;
  12241. this._stencilMask = 0xFF;
  12242. this._stencilFunc = BABYLON.Engine.ALWAYS;
  12243. this._stencilFuncRef = 1;
  12244. this._stencilFuncMask = 0xFF;
  12245. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  12246. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  12247. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  12248. this._isStencilTestDirty = true;
  12249. this._isStencilMaskDirty = true;
  12250. this._isStencilFuncDirty = true;
  12251. this._isStencilOpDirty = true;
  12252. };
  12253. _StencilState.prototype.apply = function (gl) {
  12254. if (!this.isDirty) {
  12255. return;
  12256. }
  12257. // Stencil test
  12258. if (this._isStencilTestDirty) {
  12259. if (this.stencilTest) {
  12260. gl.enable(gl.STENCIL_TEST);
  12261. }
  12262. else {
  12263. gl.disable(gl.STENCIL_TEST);
  12264. }
  12265. this._isStencilTestDirty = false;
  12266. }
  12267. // Stencil mask
  12268. if (this._isStencilMaskDirty) {
  12269. gl.stencilMask(this.stencilMask);
  12270. this._isStencilMaskDirty = false;
  12271. }
  12272. // Stencil func
  12273. if (this._isStencilFuncDirty) {
  12274. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  12275. this._isStencilFuncDirty = false;
  12276. }
  12277. // Stencil op
  12278. if (this._isStencilOpDirty) {
  12279. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  12280. this._isStencilOpDirty = false;
  12281. }
  12282. };
  12283. return _StencilState;
  12284. }());
  12285. BABYLON._StencilState = _StencilState;
  12286. })(BABYLON || (BABYLON = {}));
  12287. //# sourceMappingURL=babylon.stencilState.js.map
  12288. var __assign = (this && this.__assign) || function () {
  12289. __assign = Object.assign || function(t) {
  12290. for (var s, i = 1, n = arguments.length; i < n; i++) {
  12291. s = arguments[i];
  12292. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  12293. t[p] = s[p];
  12294. }
  12295. return t;
  12296. };
  12297. return __assign.apply(this, arguments);
  12298. };
  12299. var BABYLON;
  12300. (function (BABYLON) {
  12301. /**
  12302. * Keeps track of all the buffer info used in engine.
  12303. */
  12304. var BufferPointer = /** @class */ (function () {
  12305. function BufferPointer() {
  12306. }
  12307. return BufferPointer;
  12308. }());
  12309. /**
  12310. * Interface for attribute information associated with buffer instanciation
  12311. */
  12312. var InstancingAttributeInfo = /** @class */ (function () {
  12313. function InstancingAttributeInfo() {
  12314. }
  12315. return InstancingAttributeInfo;
  12316. }());
  12317. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  12318. /**
  12319. * Define options used to create a render target texture
  12320. */
  12321. var RenderTargetCreationOptions = /** @class */ (function () {
  12322. function RenderTargetCreationOptions() {
  12323. }
  12324. return RenderTargetCreationOptions;
  12325. }());
  12326. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  12327. /**
  12328. * Define options used to create a depth texture
  12329. */
  12330. var DepthTextureCreationOptions = /** @class */ (function () {
  12331. function DepthTextureCreationOptions() {
  12332. }
  12333. return DepthTextureCreationOptions;
  12334. }());
  12335. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  12336. /**
  12337. * Class used to describe the capabilities of the engine relatively to the current browser
  12338. */
  12339. var EngineCapabilities = /** @class */ (function () {
  12340. function EngineCapabilities() {
  12341. }
  12342. return EngineCapabilities;
  12343. }());
  12344. BABYLON.EngineCapabilities = EngineCapabilities;
  12345. /**
  12346. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  12347. */
  12348. var Engine = /** @class */ (function () {
  12349. /**
  12350. * Creates a new engine
  12351. * @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
  12352. * @param antialias defines enable antialiasing (default: false)
  12353. * @param options defines further options to be sent to the getContext() function
  12354. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  12355. */
  12356. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  12357. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  12358. var _this = this;
  12359. // Public members
  12360. /**
  12361. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  12362. */
  12363. this.forcePOTTextures = false;
  12364. /**
  12365. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  12366. */
  12367. this.isFullscreen = false;
  12368. /**
  12369. * Gets a boolean indicating if the pointer is currently locked
  12370. */
  12371. this.isPointerLock = false;
  12372. /**
  12373. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  12374. */
  12375. this.cullBackFaces = true;
  12376. /**
  12377. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  12378. */
  12379. this.renderEvenInBackground = true;
  12380. /**
  12381. * Gets or sets a boolean indicating that cache can be kept between frames
  12382. */
  12383. this.preventCacheWipeBetweenFrames = false;
  12384. /**
  12385. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  12386. **/
  12387. this.enableOfflineSupport = false;
  12388. /**
  12389. * 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)
  12390. **/
  12391. this.disableManifestCheck = false;
  12392. /**
  12393. * Gets the list of created scenes
  12394. */
  12395. this.scenes = new Array();
  12396. /**
  12397. * Event raised when a new scene is created
  12398. */
  12399. this.onNewSceneAddedObservable = new BABYLON.Observable();
  12400. /**
  12401. * Gets the list of created postprocesses
  12402. */
  12403. this.postProcesses = new Array();
  12404. /** Gets or sets a boolean indicating if the engine should validate programs after compilation */
  12405. this.validateShaderPrograms = false;
  12406. // Observables
  12407. /**
  12408. * Observable event triggered each time the rendering canvas is resized
  12409. */
  12410. this.onResizeObservable = new BABYLON.Observable();
  12411. /**
  12412. * Observable event triggered each time the canvas loses focus
  12413. */
  12414. this.onCanvasBlurObservable = new BABYLON.Observable();
  12415. /**
  12416. * Observable event triggered each time the canvas gains focus
  12417. */
  12418. this.onCanvasFocusObservable = new BABYLON.Observable();
  12419. /**
  12420. * Observable event triggered each time the canvas receives pointerout event
  12421. */
  12422. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  12423. /**
  12424. * Observable event triggered before each texture is initialized
  12425. */
  12426. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  12427. //WebVR
  12428. this._vrDisplay = undefined;
  12429. this._vrSupported = false;
  12430. this._vrExclusivePointerMode = false;
  12431. // Uniform buffers list
  12432. /**
  12433. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  12434. */
  12435. this.disableUniformBuffers = false;
  12436. /** @hidden */
  12437. this._uniformBuffers = new Array();
  12438. // Observables
  12439. /**
  12440. * Observable raised when the engine begins a new frame
  12441. */
  12442. this.onBeginFrameObservable = new BABYLON.Observable();
  12443. /**
  12444. * If set, will be used to request the next animation frame for the render loop
  12445. */
  12446. this.customAnimationFrameRequester = null;
  12447. /**
  12448. * Observable raised when the engine ends the current frame
  12449. */
  12450. this.onEndFrameObservable = new BABYLON.Observable();
  12451. /**
  12452. * Observable raised when the engine is about to compile a shader
  12453. */
  12454. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  12455. /**
  12456. * Observable raised when the engine has jsut compiled a shader
  12457. */
  12458. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  12459. this._windowIsBackground = false;
  12460. this._webGLVersion = 1.0;
  12461. /** @hidden */
  12462. this._badOS = false;
  12463. /** @hidden */
  12464. this._badDesktopOS = false;
  12465. /**
  12466. * Gets or sets a value indicating if we want to disable texture binding optimization.
  12467. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  12468. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  12469. */
  12470. this.disableTextureBindingOptimization = false;
  12471. /**
  12472. * Observable signaled when VR display mode changes
  12473. */
  12474. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  12475. /**
  12476. * Observable signaled when VR request present is complete
  12477. */
  12478. this.onVRRequestPresentComplete = new BABYLON.Observable();
  12479. /**
  12480. * Observable signaled when VR request present starts
  12481. */
  12482. this.onVRRequestPresentStart = new BABYLON.Observable();
  12483. this._colorWrite = true;
  12484. /** @hidden */
  12485. this._drawCalls = new BABYLON.PerfCounter();
  12486. /** @hidden */
  12487. this._textureCollisions = new BABYLON.PerfCounter();
  12488. this._renderingQueueLaunched = false;
  12489. this._activeRenderLoops = new Array();
  12490. // Deterministic lockstepMaxSteps
  12491. this._deterministicLockstep = false;
  12492. this._lockstepMaxSteps = 4;
  12493. // Lost context
  12494. /**
  12495. * Observable signaled when a context lost event is raised
  12496. */
  12497. this.onContextLostObservable = new BABYLON.Observable();
  12498. /**
  12499. * Observable signaled when a context restored event is raised
  12500. */
  12501. this.onContextRestoredObservable = new BABYLON.Observable();
  12502. this._contextWasLost = false;
  12503. this._doNotHandleContextLost = false;
  12504. // FPS
  12505. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  12506. this._fps = 60;
  12507. this._deltaTime = 0;
  12508. /**
  12509. * Turn this value on if you want to pause FPS computation when in background
  12510. */
  12511. this.disablePerformanceMonitorInBackground = false;
  12512. // States
  12513. /** @hidden */
  12514. this._depthCullingState = new BABYLON._DepthCullingState();
  12515. /** @hidden */
  12516. this._stencilState = new BABYLON._StencilState();
  12517. /** @hidden */
  12518. this._alphaState = new BABYLON._AlphaState();
  12519. /** @hidden */
  12520. this._alphaMode = Engine.ALPHA_DISABLE;
  12521. // Cache
  12522. this._internalTexturesCache = new Array();
  12523. /** @hidden */
  12524. this._activeChannel = 0;
  12525. this._currentTextureChannel = -1;
  12526. /** @hidden */
  12527. this._boundTexturesCache = {};
  12528. this._compiledEffects = {};
  12529. this._vertexAttribArraysEnabled = [];
  12530. this._uintIndicesCurrentlySet = false;
  12531. this._currentBoundBuffer = new Array();
  12532. /** @hidden */
  12533. this._currentFramebuffer = null;
  12534. this._currentBufferPointers = new Array();
  12535. this._currentInstanceLocations = new Array();
  12536. this._currentInstanceBuffers = new Array();
  12537. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  12538. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  12539. this._vaoRecordInProgress = false;
  12540. this._mustWipeVertexAttributes = false;
  12541. this._nextFreeTextureSlots = new Array();
  12542. this._maxSimultaneousTextures = 0;
  12543. this._activeRequests = new Array();
  12544. // Hardware supported Compressed Textures
  12545. this._texturesSupported = new Array();
  12546. /**
  12547. * Defines whether the engine has been created with the premultipliedAlpha option on or not.
  12548. */
  12549. this.premultipliedAlpha = true;
  12550. this._viewportCached = new BABYLON.Vector4(0, 0, 0, 0);
  12551. this._onVRFullScreenTriggered = function () {
  12552. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  12553. //get the old size before we change
  12554. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  12555. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  12556. //get the width and height, change the render size
  12557. var leftEye = _this._vrDisplay.getEyeParameters('left');
  12558. _this.setHardwareScalingLevel(1);
  12559. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  12560. }
  12561. else {
  12562. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  12563. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  12564. }
  12565. };
  12566. this._unpackFlipYCached = null;
  12567. /**
  12568. * In case you are sharing the context with other applications, it might
  12569. * be interested to not cache the unpack flip y state to ensure a consistent
  12570. * value would be set.
  12571. */
  12572. this.enableUnpackFlipYCached = true;
  12573. this._boundUniforms = {};
  12574. // Register promises
  12575. BABYLON.PromisePolyfill.Apply();
  12576. var canvas = null;
  12577. Engine.Instances.push(this);
  12578. if (!canvasOrContext) {
  12579. return;
  12580. }
  12581. options = options || {};
  12582. if (canvasOrContext.getContext) {
  12583. canvas = canvasOrContext;
  12584. this._renderingCanvas = canvas;
  12585. if (antialias != null) {
  12586. options.antialias = antialias;
  12587. }
  12588. if (options.deterministicLockstep === undefined) {
  12589. options.deterministicLockstep = false;
  12590. }
  12591. if (options.lockstepMaxSteps === undefined) {
  12592. options.lockstepMaxSteps = 4;
  12593. }
  12594. if (options.preserveDrawingBuffer === undefined) {
  12595. options.preserveDrawingBuffer = false;
  12596. }
  12597. if (options.audioEngine === undefined) {
  12598. options.audioEngine = true;
  12599. }
  12600. if (options.stencil === undefined) {
  12601. options.stencil = true;
  12602. }
  12603. if (options.premultipliedAlpha === false) {
  12604. this.premultipliedAlpha = false;
  12605. }
  12606. this._deterministicLockstep = options.deterministicLockstep;
  12607. this._lockstepMaxSteps = options.lockstepMaxSteps;
  12608. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  12609. // Exceptions
  12610. if (navigator && navigator.userAgent) {
  12611. var ua = navigator.userAgent;
  12612. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  12613. var exception = _a[_i];
  12614. var key = exception.key;
  12615. var targets = exception.targets;
  12616. if (ua.indexOf(key) > -1) {
  12617. if (exception.capture && exception.captureConstraint) {
  12618. var capture = exception.capture;
  12619. var constraint = exception.captureConstraint;
  12620. var regex = new RegExp(capture);
  12621. var matches = regex.exec(ua);
  12622. if (matches && matches.length > 0) {
  12623. var capturedValue = parseInt(matches[matches.length - 1]);
  12624. if (capturedValue >= constraint) {
  12625. continue;
  12626. }
  12627. }
  12628. }
  12629. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  12630. var target = targets_1[_b];
  12631. switch (target) {
  12632. case "uniformBuffer":
  12633. this.disableUniformBuffers = true;
  12634. break;
  12635. case "textureBindingOptimization":
  12636. this.disableTextureBindingOptimization = true;
  12637. break;
  12638. }
  12639. }
  12640. }
  12641. }
  12642. }
  12643. // GL
  12644. if (!options.disableWebGL2Support) {
  12645. try {
  12646. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  12647. if (this._gl) {
  12648. this._webGLVersion = 2.0;
  12649. // Prevent weird browsers to lie :-)
  12650. if (!this._gl.deleteQuery) {
  12651. this._webGLVersion = 1.0;
  12652. }
  12653. }
  12654. }
  12655. catch (e) {
  12656. // Do nothing
  12657. }
  12658. }
  12659. if (!this._gl) {
  12660. if (!canvas) {
  12661. throw new Error("The provided canvas is null or undefined.");
  12662. }
  12663. try {
  12664. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  12665. }
  12666. catch (e) {
  12667. throw new Error("WebGL not supported");
  12668. }
  12669. }
  12670. if (!this._gl) {
  12671. throw new Error("WebGL not supported");
  12672. }
  12673. this._onCanvasFocus = function () {
  12674. _this.onCanvasFocusObservable.notifyObservers(_this);
  12675. };
  12676. this._onCanvasBlur = function () {
  12677. _this.onCanvasBlurObservable.notifyObservers(_this);
  12678. };
  12679. canvas.addEventListener("focus", this._onCanvasFocus);
  12680. canvas.addEventListener("blur", this._onCanvasBlur);
  12681. this._onBlur = function () {
  12682. if (_this.disablePerformanceMonitorInBackground) {
  12683. _this._performanceMonitor.disable();
  12684. }
  12685. _this._windowIsBackground = true;
  12686. };
  12687. this._onFocus = function () {
  12688. if (_this.disablePerformanceMonitorInBackground) {
  12689. _this._performanceMonitor.enable();
  12690. }
  12691. _this._windowIsBackground = false;
  12692. };
  12693. this._onCanvasPointerOut = function (ev) {
  12694. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  12695. };
  12696. if (BABYLON.Tools.IsWindowObjectExist()) {
  12697. window.addEventListener("blur", this._onBlur);
  12698. window.addEventListener("focus", this._onFocus);
  12699. }
  12700. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  12701. // Context lost
  12702. if (!this._doNotHandleContextLost) {
  12703. this._onContextLost = function (evt) {
  12704. evt.preventDefault();
  12705. _this._contextWasLost = true;
  12706. BABYLON.Tools.Warn("WebGL context lost.");
  12707. _this.onContextLostObservable.notifyObservers(_this);
  12708. };
  12709. this._onContextRestored = function (evt) {
  12710. // Adding a timeout to avoid race condition at browser level
  12711. setTimeout(function () {
  12712. // Rebuild gl context
  12713. _this._initGLContext();
  12714. // Rebuild effects
  12715. _this._rebuildEffects();
  12716. // Rebuild textures
  12717. _this._rebuildInternalTextures();
  12718. // Rebuild buffers
  12719. _this._rebuildBuffers();
  12720. // Cache
  12721. _this.wipeCaches(true);
  12722. BABYLON.Tools.Warn("WebGL context successfully restored.");
  12723. _this.onContextRestoredObservable.notifyObservers(_this);
  12724. _this._contextWasLost = false;
  12725. }, 0);
  12726. };
  12727. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  12728. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  12729. }
  12730. }
  12731. else {
  12732. this._gl = canvasOrContext;
  12733. this._renderingCanvas = this._gl.canvas;
  12734. if (this._gl.renderbufferStorageMultisample) {
  12735. this._webGLVersion = 2.0;
  12736. }
  12737. var attributes = this._gl.getContextAttributes();
  12738. if (attributes) {
  12739. options.stencil = attributes.stencil;
  12740. }
  12741. }
  12742. // Viewport
  12743. var devicePixelRatio = BABYLON.Tools.IsWindowObjectExist() ? (window.devicePixelRatio || 1.0) : 1.0;
  12744. var limitDeviceRatio = options.limitDeviceRatio || devicePixelRatio;
  12745. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, devicePixelRatio) : 1.0;
  12746. this.resize();
  12747. this._isStencilEnable = options.stencil ? true : false;
  12748. this._initGLContext();
  12749. if (canvas) {
  12750. // Fullscreen
  12751. this._onFullscreenChange = function () {
  12752. if (document.fullscreen !== undefined) {
  12753. _this.isFullscreen = document.fullscreen;
  12754. }
  12755. else if (document.mozFullScreen !== undefined) {
  12756. _this.isFullscreen = document.mozFullScreen;
  12757. }
  12758. else if (document.webkitIsFullScreen !== undefined) {
  12759. _this.isFullscreen = document.webkitIsFullScreen;
  12760. }
  12761. else if (document.msIsFullScreen !== undefined) {
  12762. _this.isFullscreen = document.msIsFullScreen;
  12763. }
  12764. // Pointer lock
  12765. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  12766. canvas.requestPointerLock = canvas.requestPointerLock ||
  12767. canvas.msRequestPointerLock ||
  12768. canvas.mozRequestPointerLock ||
  12769. canvas.webkitRequestPointerLock;
  12770. if (canvas.requestPointerLock) {
  12771. canvas.requestPointerLock();
  12772. }
  12773. }
  12774. };
  12775. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  12776. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  12777. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  12778. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  12779. // Pointer lock
  12780. this._onPointerLockChange = function () {
  12781. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  12782. document.webkitPointerLockElement === canvas ||
  12783. document.msPointerLockElement === canvas ||
  12784. document.pointerLockElement === canvas);
  12785. };
  12786. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  12787. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  12788. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  12789. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  12790. this._onVRDisplayPointerRestricted = function () {
  12791. if (canvas) {
  12792. canvas.requestPointerLock();
  12793. }
  12794. };
  12795. this._onVRDisplayPointerUnrestricted = function () {
  12796. document.exitPointerLock();
  12797. };
  12798. if (BABYLON.Tools.IsWindowObjectExist()) {
  12799. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  12800. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  12801. }
  12802. }
  12803. // Create Audio Engine if needed.
  12804. if (!Engine.audioEngine && options.audioEngine && Engine.AudioEngineFactory) {
  12805. Engine.audioEngine = Engine.AudioEngineFactory(this.getRenderingCanvas());
  12806. }
  12807. // Prepare buffer pointers
  12808. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  12809. this._currentBufferPointers[i] = new BufferPointer();
  12810. }
  12811. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  12812. // Load WebVR Devices
  12813. if (options.autoEnableWebVR) {
  12814. this.initWebVR();
  12815. }
  12816. // Detect if we are running on a faulty buggy OS.
  12817. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  12818. // Detect if we are running on a faulty buggy desktop OS.
  12819. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  12820. console.log("Babylon.js v" + Engine.Version + " - " + this.description);
  12821. this.enableOfflineSupport = Engine.OfflineProviderFactory !== undefined;
  12822. }
  12823. Object.defineProperty(Engine, "LastCreatedEngine", {
  12824. /**
  12825. * Gets the latest created engine
  12826. */
  12827. get: function () {
  12828. if (Engine.Instances.length === 0) {
  12829. return null;
  12830. }
  12831. return Engine.Instances[Engine.Instances.length - 1];
  12832. },
  12833. enumerable: true,
  12834. configurable: true
  12835. });
  12836. Object.defineProperty(Engine, "LastCreatedScene", {
  12837. /**
  12838. * Gets the latest created scene
  12839. */
  12840. get: function () {
  12841. var lastCreatedEngine = Engine.LastCreatedEngine;
  12842. if (!lastCreatedEngine) {
  12843. return null;
  12844. }
  12845. if (lastCreatedEngine.scenes.length === 0) {
  12846. return null;
  12847. }
  12848. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  12849. },
  12850. enumerable: true,
  12851. configurable: true
  12852. });
  12853. /**
  12854. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  12855. * @param flag defines which part of the materials must be marked as dirty
  12856. * @param predicate defines a predicate used to filter which materials should be affected
  12857. */
  12858. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  12859. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  12860. var engine = Engine.Instances[engineIndex];
  12861. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  12862. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  12863. }
  12864. }
  12865. };
  12866. Object.defineProperty(Engine, "Version", {
  12867. /**
  12868. * Returns the current version of the framework
  12869. */
  12870. get: function () {
  12871. return "4.0.0-alpha.7";
  12872. },
  12873. enumerable: true,
  12874. configurable: true
  12875. });
  12876. Object.defineProperty(Engine.prototype, "description", {
  12877. /**
  12878. * Returns a string describing the current engine
  12879. */
  12880. get: function () {
  12881. var description = "WebGL" + this.webGLVersion;
  12882. if (this._caps.parallelShaderCompile) {
  12883. description += " - Parallel shader compilation";
  12884. }
  12885. return description;
  12886. },
  12887. enumerable: true,
  12888. configurable: true
  12889. });
  12890. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  12891. /**
  12892. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  12893. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  12894. */
  12895. get: function () {
  12896. return this._vrExclusivePointerMode;
  12897. },
  12898. enumerable: true,
  12899. configurable: true
  12900. });
  12901. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  12902. /**
  12903. * Gets a boolean indicating that the engine supports uniform buffers
  12904. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12905. */
  12906. get: function () {
  12907. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  12908. },
  12909. enumerable: true,
  12910. configurable: true
  12911. });
  12912. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  12913. /**
  12914. * Gets a boolean indicating that only power of 2 textures are supported
  12915. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  12916. */
  12917. get: function () {
  12918. return this._webGLVersion < 2 || this.forcePOTTextures;
  12919. },
  12920. enumerable: true,
  12921. configurable: true
  12922. });
  12923. Object.defineProperty(Engine.prototype, "doNotHandleContextLost", {
  12924. /**
  12925. * Gets or sets a boolean indicating if resources should be retained to be able to handle context lost events
  12926. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#handling-webgl-context-lost
  12927. */
  12928. get: function () {
  12929. return this._doNotHandleContextLost;
  12930. },
  12931. set: function (value) {
  12932. this._doNotHandleContextLost = value;
  12933. },
  12934. enumerable: true,
  12935. configurable: true
  12936. });
  12937. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  12938. /**
  12939. * Gets the performance monitor attached to this engine
  12940. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  12941. */
  12942. get: function () {
  12943. return this._performanceMonitor;
  12944. },
  12945. enumerable: true,
  12946. configurable: true
  12947. });
  12948. Object.defineProperty(Engine.prototype, "texturesSupported", {
  12949. /**
  12950. * Gets the list of texture formats supported
  12951. */
  12952. get: function () {
  12953. return this._texturesSupported;
  12954. },
  12955. enumerable: true,
  12956. configurable: true
  12957. });
  12958. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  12959. /**
  12960. * Gets the list of texture formats in use
  12961. */
  12962. get: function () {
  12963. return this._textureFormatInUse;
  12964. },
  12965. enumerable: true,
  12966. configurable: true
  12967. });
  12968. Object.defineProperty(Engine.prototype, "currentViewport", {
  12969. /**
  12970. * Gets the current viewport
  12971. */
  12972. get: function () {
  12973. return this._cachedViewport;
  12974. },
  12975. enumerable: true,
  12976. configurable: true
  12977. });
  12978. Object.defineProperty(Engine.prototype, "emptyTexture", {
  12979. /**
  12980. * Gets the default empty texture
  12981. */
  12982. get: function () {
  12983. if (!this._emptyTexture) {
  12984. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  12985. }
  12986. return this._emptyTexture;
  12987. },
  12988. enumerable: true,
  12989. configurable: true
  12990. });
  12991. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  12992. /**
  12993. * Gets the default empty 3D texture
  12994. */
  12995. get: function () {
  12996. if (!this._emptyTexture3D) {
  12997. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  12998. }
  12999. return this._emptyTexture3D;
  13000. },
  13001. enumerable: true,
  13002. configurable: true
  13003. });
  13004. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  13005. /**
  13006. * Gets the default empty cube texture
  13007. */
  13008. get: function () {
  13009. if (!this._emptyCubeTexture) {
  13010. var faceData = new Uint8Array(4);
  13011. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  13012. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  13013. }
  13014. return this._emptyCubeTexture;
  13015. },
  13016. enumerable: true,
  13017. configurable: true
  13018. });
  13019. Engine.prototype._rebuildInternalTextures = function () {
  13020. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  13021. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  13022. var internalTexture = currentState_1[_i];
  13023. internalTexture._rebuild();
  13024. }
  13025. };
  13026. Engine.prototype._rebuildEffects = function () {
  13027. for (var key in this._compiledEffects) {
  13028. var effect = this._compiledEffects[key];
  13029. effect._prepareEffect();
  13030. }
  13031. BABYLON.Effect.ResetCache();
  13032. };
  13033. /**
  13034. * Gets a boolean indicating if all created effects are ready
  13035. * @returns true if all effects are ready
  13036. */
  13037. Engine.prototype.areAllEffectsReady = function () {
  13038. for (var key in this._compiledEffects) {
  13039. var effect = this._compiledEffects[key];
  13040. if (!effect.isReady()) {
  13041. return false;
  13042. }
  13043. }
  13044. return true;
  13045. };
  13046. Engine.prototype._rebuildBuffers = function () {
  13047. // Index / Vertex
  13048. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  13049. var scene = _a[_i];
  13050. scene.resetCachedMaterial();
  13051. scene._rebuildGeometries();
  13052. scene._rebuildTextures();
  13053. }
  13054. // Uniforms
  13055. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  13056. var uniformBuffer = _c[_b];
  13057. uniformBuffer._rebuild();
  13058. }
  13059. };
  13060. Engine.prototype._initGLContext = function () {
  13061. // Caps
  13062. this._caps = new EngineCapabilities();
  13063. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  13064. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  13065. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  13066. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  13067. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  13068. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  13069. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  13070. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  13071. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  13072. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  13073. // Infos
  13074. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  13075. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  13076. if (rendererInfo != null) {
  13077. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  13078. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  13079. }
  13080. if (!this._glVendor) {
  13081. this._glVendor = "Unknown vendor";
  13082. }
  13083. if (!this._glRenderer) {
  13084. this._glRenderer = "Unknown renderer";
  13085. }
  13086. // Constants
  13087. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  13088. if (this._gl.RGBA16F !== 0x881A) {
  13089. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  13090. }
  13091. if (this._gl.RGBA32F !== 0x8814) {
  13092. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  13093. }
  13094. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  13095. this._gl.DEPTH24_STENCIL8 = 35056;
  13096. }
  13097. // Extensions
  13098. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  13099. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  13100. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  13101. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  13102. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  13103. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  13104. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  13105. 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');
  13106. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  13107. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  13108. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  13109. this._caps.highPrecisionShaderSupported = false;
  13110. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  13111. if (this._caps.timerQuery) {
  13112. if (this._webGLVersion === 1) {
  13113. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  13114. }
  13115. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  13116. }
  13117. // Checks if some of the format renders first to allow the use of webgl inspector.
  13118. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  13119. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  13120. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  13121. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  13122. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  13123. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  13124. if (this._webGLVersion > 1) {
  13125. this._gl.HALF_FLOAT_OES = 0x140B;
  13126. }
  13127. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  13128. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  13129. // Draw buffers
  13130. if (this._webGLVersion > 1) {
  13131. this._caps.drawBuffersExtension = true;
  13132. }
  13133. else {
  13134. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  13135. if (drawBuffersExtension !== null) {
  13136. this._caps.drawBuffersExtension = true;
  13137. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  13138. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  13139. for (var i = 0; i < 16; i++) {
  13140. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  13141. }
  13142. }
  13143. else {
  13144. this._caps.drawBuffersExtension = false;
  13145. }
  13146. }
  13147. // Shader compiler threads
  13148. this._caps.parallelShaderCompile = this._gl.getExtension('KHR_parallel_shader_compile');
  13149. if (this._caps.parallelShaderCompile) {
  13150. var threads = this._gl.getParameter(this._caps.parallelShaderCompile.MAX_SHADER_COMPILER_THREADS_KHR);
  13151. this._caps.parallelShaderCompile.maxShaderCompilerThreadsKHR(threads);
  13152. }
  13153. // Depth Texture
  13154. if (this._webGLVersion > 1) {
  13155. this._caps.depthTextureExtension = true;
  13156. }
  13157. else {
  13158. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  13159. if (depthTextureExtension != null) {
  13160. this._caps.depthTextureExtension = true;
  13161. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  13162. }
  13163. }
  13164. // Vertex array object
  13165. if (this._webGLVersion > 1) {
  13166. this._caps.vertexArrayObject = true;
  13167. }
  13168. else {
  13169. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  13170. if (vertexArrayObjectExtension != null) {
  13171. this._caps.vertexArrayObject = true;
  13172. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  13173. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  13174. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  13175. }
  13176. else {
  13177. this._caps.vertexArrayObject = false;
  13178. }
  13179. }
  13180. // Instances count
  13181. if (this._webGLVersion > 1) {
  13182. this._caps.instancedArrays = true;
  13183. }
  13184. else {
  13185. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  13186. if (instanceExtension != null) {
  13187. this._caps.instancedArrays = true;
  13188. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  13189. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  13190. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  13191. }
  13192. else {
  13193. this._caps.instancedArrays = false;
  13194. }
  13195. }
  13196. // Intelligently add supported compressed formats in order to check for.
  13197. // Check for ASTC support first as it is most powerful and to be very cross platform.
  13198. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  13199. // Likely no hardware which supports both PVR & DXT, so order matters little.
  13200. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  13201. if (this._caps.astc) {
  13202. this.texturesSupported.push('-astc.ktx');
  13203. }
  13204. if (this._caps.s3tc) {
  13205. this.texturesSupported.push('-dxt.ktx');
  13206. }
  13207. if (this._caps.pvrtc) {
  13208. this.texturesSupported.push('-pvrtc.ktx');
  13209. }
  13210. if (this._caps.etc2) {
  13211. this.texturesSupported.push('-etc2.ktx');
  13212. }
  13213. if (this._caps.etc1) {
  13214. this.texturesSupported.push('-etc1.ktx');
  13215. }
  13216. if (this._gl.getShaderPrecisionFormat) {
  13217. var vertex_highp = this._gl.getShaderPrecisionFormat(this._gl.VERTEX_SHADER, this._gl.HIGH_FLOAT);
  13218. var fragment_highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  13219. if (vertex_highp && fragment_highp) {
  13220. this._caps.highPrecisionShaderSupported = vertex_highp.precision !== 0 && fragment_highp.precision !== 0;
  13221. }
  13222. }
  13223. // Depth buffer
  13224. this.setDepthBuffer(true);
  13225. this.setDepthFunctionToLessOrEqual();
  13226. this.setDepthWrite(true);
  13227. // Texture maps
  13228. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  13229. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  13230. this._nextFreeTextureSlots.push(slot);
  13231. }
  13232. };
  13233. Object.defineProperty(Engine.prototype, "webGLVersion", {
  13234. /**
  13235. * Gets version of the current webGL context
  13236. */
  13237. get: function () {
  13238. return this._webGLVersion;
  13239. },
  13240. enumerable: true,
  13241. configurable: true
  13242. });
  13243. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  13244. /**
  13245. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  13246. */
  13247. get: function () {
  13248. return this._isStencilEnable;
  13249. },
  13250. enumerable: true,
  13251. configurable: true
  13252. });
  13253. Engine.prototype._prepareWorkingCanvas = function () {
  13254. if (this._workingCanvas) {
  13255. return;
  13256. }
  13257. this._workingCanvas = document.createElement("canvas");
  13258. var context = this._workingCanvas.getContext("2d");
  13259. if (context) {
  13260. this._workingContext = context;
  13261. }
  13262. };
  13263. /**
  13264. * Reset the texture cache to empty state
  13265. */
  13266. Engine.prototype.resetTextureCache = function () {
  13267. for (var key in this._boundTexturesCache) {
  13268. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  13269. continue;
  13270. }
  13271. var boundTexture = this._boundTexturesCache[key];
  13272. if (boundTexture) {
  13273. this._removeDesignatedSlot(boundTexture);
  13274. }
  13275. this._boundTexturesCache[key] = null;
  13276. }
  13277. if (!this.disableTextureBindingOptimization) {
  13278. this._nextFreeTextureSlots = [];
  13279. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  13280. this._nextFreeTextureSlots.push(slot);
  13281. }
  13282. }
  13283. this._currentTextureChannel = -1;
  13284. };
  13285. /**
  13286. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  13287. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  13288. * @returns true if engine is in deterministic lock step mode
  13289. */
  13290. Engine.prototype.isDeterministicLockStep = function () {
  13291. return this._deterministicLockstep;
  13292. };
  13293. /**
  13294. * Gets the max steps when engine is running in deterministic lock step
  13295. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  13296. * @returns the max steps
  13297. */
  13298. Engine.prototype.getLockstepMaxSteps = function () {
  13299. return this._lockstepMaxSteps;
  13300. };
  13301. /**
  13302. * Gets an object containing information about the current webGL context
  13303. * @returns an object containing the vender, the renderer and the version of the current webGL context
  13304. */
  13305. Engine.prototype.getGlInfo = function () {
  13306. return {
  13307. vendor: this._glVendor,
  13308. renderer: this._glRenderer,
  13309. version: this._glVersion
  13310. };
  13311. };
  13312. /**
  13313. * Gets current aspect ratio
  13314. * @param camera defines the camera to use to get the aspect ratio
  13315. * @param useScreen defines if screen size must be used (or the current render target if any)
  13316. * @returns a number defining the aspect ratio
  13317. */
  13318. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  13319. if (useScreen === void 0) { useScreen = false; }
  13320. var viewport = camera.viewport;
  13321. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  13322. };
  13323. /**
  13324. * Gets current screen aspect ratio
  13325. * @returns a number defining the aspect ratio
  13326. */
  13327. Engine.prototype.getScreenAspectRatio = function () {
  13328. return (this.getRenderWidth(true)) / (this.getRenderHeight(true));
  13329. };
  13330. /**
  13331. * Gets the current render width
  13332. * @param useScreen defines if screen size must be used (or the current render target if any)
  13333. * @returns a number defining the current render width
  13334. */
  13335. Engine.prototype.getRenderWidth = function (useScreen) {
  13336. if (useScreen === void 0) { useScreen = false; }
  13337. if (!useScreen && this._currentRenderTarget) {
  13338. return this._currentRenderTarget.width;
  13339. }
  13340. return this._gl.drawingBufferWidth;
  13341. };
  13342. /**
  13343. * Gets the current render height
  13344. * @param useScreen defines if screen size must be used (or the current render target if any)
  13345. * @returns a number defining the current render height
  13346. */
  13347. Engine.prototype.getRenderHeight = function (useScreen) {
  13348. if (useScreen === void 0) { useScreen = false; }
  13349. if (!useScreen && this._currentRenderTarget) {
  13350. return this._currentRenderTarget.height;
  13351. }
  13352. return this._gl.drawingBufferHeight;
  13353. };
  13354. /**
  13355. * Gets the HTML canvas attached with the current webGL context
  13356. * @returns a HTML canvas
  13357. */
  13358. Engine.prototype.getRenderingCanvas = function () {
  13359. return this._renderingCanvas;
  13360. };
  13361. /**
  13362. * Gets the client rect of the HTML canvas attached with the current webGL context
  13363. * @returns a client rectanglee
  13364. */
  13365. Engine.prototype.getRenderingCanvasClientRect = function () {
  13366. if (!this._renderingCanvas) {
  13367. return null;
  13368. }
  13369. return this._renderingCanvas.getBoundingClientRect();
  13370. };
  13371. /**
  13372. * Defines the hardware scaling level.
  13373. * By default the hardware scaling level is computed from the window device ratio.
  13374. * 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.
  13375. * @param level defines the level to use
  13376. */
  13377. Engine.prototype.setHardwareScalingLevel = function (level) {
  13378. this._hardwareScalingLevel = level;
  13379. this.resize();
  13380. };
  13381. /**
  13382. * Gets the current hardware scaling level.
  13383. * By default the hardware scaling level is computed from the window device ratio.
  13384. * 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.
  13385. * @returns a number indicating the current hardware scaling level
  13386. */
  13387. Engine.prototype.getHardwareScalingLevel = function () {
  13388. return this._hardwareScalingLevel;
  13389. };
  13390. /**
  13391. * Gets the list of loaded textures
  13392. * @returns an array containing all loaded textures
  13393. */
  13394. Engine.prototype.getLoadedTexturesCache = function () {
  13395. return this._internalTexturesCache;
  13396. };
  13397. /**
  13398. * Gets the object containing all engine capabilities
  13399. * @returns the EngineCapabilities object
  13400. */
  13401. Engine.prototype.getCaps = function () {
  13402. return this._caps;
  13403. };
  13404. /**
  13405. * Gets the current depth function
  13406. * @returns a number defining the depth function
  13407. */
  13408. Engine.prototype.getDepthFunction = function () {
  13409. return this._depthCullingState.depthFunc;
  13410. };
  13411. /**
  13412. * Sets the current depth function
  13413. * @param depthFunc defines the function to use
  13414. */
  13415. Engine.prototype.setDepthFunction = function (depthFunc) {
  13416. this._depthCullingState.depthFunc = depthFunc;
  13417. };
  13418. /**
  13419. * Sets the current depth function to GREATER
  13420. */
  13421. Engine.prototype.setDepthFunctionToGreater = function () {
  13422. this._depthCullingState.depthFunc = this._gl.GREATER;
  13423. };
  13424. /**
  13425. * Sets the current depth function to GEQUAL
  13426. */
  13427. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  13428. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  13429. };
  13430. /**
  13431. * Sets the current depth function to LESS
  13432. */
  13433. Engine.prototype.setDepthFunctionToLess = function () {
  13434. this._depthCullingState.depthFunc = this._gl.LESS;
  13435. };
  13436. /**
  13437. * Sets the current depth function to LEQUAL
  13438. */
  13439. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  13440. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  13441. };
  13442. /**
  13443. * Gets a boolean indicating if stencil buffer is enabled
  13444. * @returns the current stencil buffer state
  13445. */
  13446. Engine.prototype.getStencilBuffer = function () {
  13447. return this._stencilState.stencilTest;
  13448. };
  13449. /**
  13450. * Enable or disable the stencil buffer
  13451. * @param enable defines if the stencil buffer must be enabled or disabled
  13452. */
  13453. Engine.prototype.setStencilBuffer = function (enable) {
  13454. this._stencilState.stencilTest = enable;
  13455. };
  13456. /**
  13457. * Gets the current stencil mask
  13458. * @returns a number defining the new stencil mask to use
  13459. */
  13460. Engine.prototype.getStencilMask = function () {
  13461. return this._stencilState.stencilMask;
  13462. };
  13463. /**
  13464. * Sets the current stencil mask
  13465. * @param mask defines the new stencil mask to use
  13466. */
  13467. Engine.prototype.setStencilMask = function (mask) {
  13468. this._stencilState.stencilMask = mask;
  13469. };
  13470. /**
  13471. * Gets the current stencil function
  13472. * @returns a number defining the stencil function to use
  13473. */
  13474. Engine.prototype.getStencilFunction = function () {
  13475. return this._stencilState.stencilFunc;
  13476. };
  13477. /**
  13478. * Gets the current stencil reference value
  13479. * @returns a number defining the stencil reference value to use
  13480. */
  13481. Engine.prototype.getStencilFunctionReference = function () {
  13482. return this._stencilState.stencilFuncRef;
  13483. };
  13484. /**
  13485. * Gets the current stencil mask
  13486. * @returns a number defining the stencil mask to use
  13487. */
  13488. Engine.prototype.getStencilFunctionMask = function () {
  13489. return this._stencilState.stencilFuncMask;
  13490. };
  13491. /**
  13492. * Sets the current stencil function
  13493. * @param stencilFunc defines the new stencil function to use
  13494. */
  13495. Engine.prototype.setStencilFunction = function (stencilFunc) {
  13496. this._stencilState.stencilFunc = stencilFunc;
  13497. };
  13498. /**
  13499. * Sets the current stencil reference
  13500. * @param reference defines the new stencil reference to use
  13501. */
  13502. Engine.prototype.setStencilFunctionReference = function (reference) {
  13503. this._stencilState.stencilFuncRef = reference;
  13504. };
  13505. /**
  13506. * Sets the current stencil mask
  13507. * @param mask defines the new stencil mask to use
  13508. */
  13509. Engine.prototype.setStencilFunctionMask = function (mask) {
  13510. this._stencilState.stencilFuncMask = mask;
  13511. };
  13512. /**
  13513. * Gets the current stencil operation when stencil fails
  13514. * @returns a number defining stencil operation to use when stencil fails
  13515. */
  13516. Engine.prototype.getStencilOperationFail = function () {
  13517. return this._stencilState.stencilOpStencilFail;
  13518. };
  13519. /**
  13520. * Gets the current stencil operation when depth fails
  13521. * @returns a number defining stencil operation to use when depth fails
  13522. */
  13523. Engine.prototype.getStencilOperationDepthFail = function () {
  13524. return this._stencilState.stencilOpDepthFail;
  13525. };
  13526. /**
  13527. * Gets the current stencil operation when stencil passes
  13528. * @returns a number defining stencil operation to use when stencil passes
  13529. */
  13530. Engine.prototype.getStencilOperationPass = function () {
  13531. return this._stencilState.stencilOpStencilDepthPass;
  13532. };
  13533. /**
  13534. * Sets the stencil operation to use when stencil fails
  13535. * @param operation defines the stencil operation to use when stencil fails
  13536. */
  13537. Engine.prototype.setStencilOperationFail = function (operation) {
  13538. this._stencilState.stencilOpStencilFail = operation;
  13539. };
  13540. /**
  13541. * Sets the stencil operation to use when depth fails
  13542. * @param operation defines the stencil operation to use when depth fails
  13543. */
  13544. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  13545. this._stencilState.stencilOpDepthFail = operation;
  13546. };
  13547. /**
  13548. * Sets the stencil operation to use when stencil passes
  13549. * @param operation defines the stencil operation to use when stencil passes
  13550. */
  13551. Engine.prototype.setStencilOperationPass = function (operation) {
  13552. this._stencilState.stencilOpStencilDepthPass = operation;
  13553. };
  13554. /**
  13555. * Sets a boolean indicating if the dithering state is enabled or disabled
  13556. * @param value defines the dithering state
  13557. */
  13558. Engine.prototype.setDitheringState = function (value) {
  13559. if (value) {
  13560. this._gl.enable(this._gl.DITHER);
  13561. }
  13562. else {
  13563. this._gl.disable(this._gl.DITHER);
  13564. }
  13565. };
  13566. /**
  13567. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  13568. * @param value defines the rasterizer state
  13569. */
  13570. Engine.prototype.setRasterizerState = function (value) {
  13571. if (value) {
  13572. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  13573. }
  13574. else {
  13575. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  13576. }
  13577. };
  13578. /**
  13579. * stop executing a render loop function and remove it from the execution array
  13580. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  13581. */
  13582. Engine.prototype.stopRenderLoop = function (renderFunction) {
  13583. if (!renderFunction) {
  13584. this._activeRenderLoops = [];
  13585. return;
  13586. }
  13587. var index = this._activeRenderLoops.indexOf(renderFunction);
  13588. if (index >= 0) {
  13589. this._activeRenderLoops.splice(index, 1);
  13590. }
  13591. };
  13592. /** @hidden */
  13593. Engine.prototype._renderLoop = function () {
  13594. if (!this._contextWasLost) {
  13595. var shouldRender = true;
  13596. if (!this.renderEvenInBackground && this._windowIsBackground) {
  13597. shouldRender = false;
  13598. }
  13599. if (shouldRender) {
  13600. // Start new frame
  13601. this.beginFrame();
  13602. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  13603. var renderFunction = this._activeRenderLoops[index];
  13604. renderFunction();
  13605. }
  13606. // Present
  13607. this.endFrame();
  13608. }
  13609. }
  13610. if (this._activeRenderLoops.length > 0) {
  13611. // Register new frame
  13612. if (this.customAnimationFrameRequester) {
  13613. this.customAnimationFrameRequester.requestID = BABYLON.Tools.QueueNewFrame(this.customAnimationFrameRequester.renderFunction || this._bindedRenderFunction, this.customAnimationFrameRequester);
  13614. this._frameHandler = this.customAnimationFrameRequester.requestID;
  13615. }
  13616. else if (this._vrDisplay && this._vrDisplay.isPresenting) {
  13617. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, this._vrDisplay);
  13618. }
  13619. else {
  13620. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  13621. }
  13622. }
  13623. else {
  13624. this._renderingQueueLaunched = false;
  13625. }
  13626. };
  13627. /**
  13628. * Register and execute a render loop. The engine can have more than one render function
  13629. * @param renderFunction defines the function to continuously execute
  13630. */
  13631. Engine.prototype.runRenderLoop = function (renderFunction) {
  13632. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  13633. return;
  13634. }
  13635. this._activeRenderLoops.push(renderFunction);
  13636. if (!this._renderingQueueLaunched) {
  13637. this._renderingQueueLaunched = true;
  13638. this._bindedRenderFunction = this._renderLoop.bind(this);
  13639. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  13640. }
  13641. };
  13642. /**
  13643. * Toggle full screen mode
  13644. * @param requestPointerLock defines if a pointer lock should be requested from the user
  13645. */
  13646. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  13647. if (this.isFullscreen) {
  13648. BABYLON.Tools.ExitFullscreen();
  13649. }
  13650. else {
  13651. this._pointerLockRequested = requestPointerLock;
  13652. if (this._renderingCanvas) {
  13653. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  13654. }
  13655. }
  13656. };
  13657. /**
  13658. * Clear the current render buffer or the current render target (if any is set up)
  13659. * @param color defines the color to use
  13660. * @param backBuffer defines if the back buffer must be cleared
  13661. * @param depth defines if the depth buffer must be cleared
  13662. * @param stencil defines if the stencil buffer must be cleared
  13663. */
  13664. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  13665. if (stencil === void 0) { stencil = false; }
  13666. this.applyStates();
  13667. var mode = 0;
  13668. if (backBuffer && color) {
  13669. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  13670. mode |= this._gl.COLOR_BUFFER_BIT;
  13671. }
  13672. if (depth) {
  13673. this._gl.clearDepth(1.0);
  13674. mode |= this._gl.DEPTH_BUFFER_BIT;
  13675. }
  13676. if (stencil) {
  13677. this._gl.clearStencil(0);
  13678. mode |= this._gl.STENCIL_BUFFER_BIT;
  13679. }
  13680. this._gl.clear(mode);
  13681. };
  13682. /**
  13683. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  13684. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  13685. * @param y defines the y-coordinate of the corner of the clear rectangle
  13686. * @param width defines the width of the clear rectangle
  13687. * @param height defines the height of the clear rectangle
  13688. * @param clearColor defines the clear color
  13689. */
  13690. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  13691. var gl = this._gl;
  13692. // Save state
  13693. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  13694. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  13695. // Change state
  13696. gl.enable(gl.SCISSOR_TEST);
  13697. gl.scissor(x, y, width, height);
  13698. // Clear
  13699. this.clear(clearColor, true, true, true);
  13700. // Restore state
  13701. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  13702. if (curScissor === true) {
  13703. gl.enable(gl.SCISSOR_TEST);
  13704. }
  13705. else {
  13706. gl.disable(gl.SCISSOR_TEST);
  13707. }
  13708. };
  13709. /** @hidden */
  13710. Engine.prototype._viewport = function (x, y, width, height) {
  13711. if (x !== this._viewportCached.x ||
  13712. y !== this._viewportCached.y ||
  13713. width !== this._viewportCached.z ||
  13714. height !== this._viewportCached.w) {
  13715. this._viewportCached.x = x;
  13716. this._viewportCached.y = y;
  13717. this._viewportCached.z = width;
  13718. this._viewportCached.w = height;
  13719. this._gl.viewport(x, y, width, height);
  13720. }
  13721. };
  13722. /**
  13723. * Set the WebGL's viewport
  13724. * @param viewport defines the viewport element to be used
  13725. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  13726. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  13727. */
  13728. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  13729. var width = requiredWidth || this.getRenderWidth();
  13730. var height = requiredHeight || this.getRenderHeight();
  13731. var x = viewport.x || 0;
  13732. var y = viewport.y || 0;
  13733. this._cachedViewport = viewport;
  13734. this._viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  13735. };
  13736. /**
  13737. * Directly set the WebGL Viewport
  13738. * @param x defines the x coordinate of the viewport (in screen space)
  13739. * @param y defines the y coordinate of the viewport (in screen space)
  13740. * @param width defines the width of the viewport (in screen space)
  13741. * @param height defines the height of the viewport (in screen space)
  13742. * @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
  13743. */
  13744. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  13745. var currentViewport = this._cachedViewport;
  13746. this._cachedViewport = null;
  13747. this._viewport(x, y, width, height);
  13748. return currentViewport;
  13749. };
  13750. /**
  13751. * Begin a new frame
  13752. */
  13753. Engine.prototype.beginFrame = function () {
  13754. this.onBeginFrameObservable.notifyObservers(this);
  13755. this._measureFps();
  13756. };
  13757. /**
  13758. * Enf the current frame
  13759. */
  13760. Engine.prototype.endFrame = function () {
  13761. // Force a flush in case we are using a bad OS.
  13762. if (this._badOS) {
  13763. this.flushFramebuffer();
  13764. }
  13765. // Submit frame to the vr device, if enabled
  13766. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  13767. // TODO: We should only submit the frame if we read frameData successfully.
  13768. this._vrDisplay.submitFrame();
  13769. }
  13770. this.onEndFrameObservable.notifyObservers(this);
  13771. };
  13772. /**
  13773. * Resize the view according to the canvas' size
  13774. */
  13775. Engine.prototype.resize = function () {
  13776. // We're not resizing the size of the canvas while in VR mode & presenting
  13777. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  13778. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  13779. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  13780. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  13781. }
  13782. };
  13783. /**
  13784. * Force a specific size of the canvas
  13785. * @param width defines the new canvas' width
  13786. * @param height defines the new canvas' height
  13787. */
  13788. Engine.prototype.setSize = function (width, height) {
  13789. if (!this._renderingCanvas) {
  13790. return;
  13791. }
  13792. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  13793. return;
  13794. }
  13795. this._renderingCanvas.width = width;
  13796. this._renderingCanvas.height = height;
  13797. for (var index = 0; index < this.scenes.length; index++) {
  13798. var scene = this.scenes[index];
  13799. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  13800. var cam = scene.cameras[camIndex];
  13801. cam._currentRenderId = 0;
  13802. }
  13803. }
  13804. if (this.onResizeObservable.hasObservers) {
  13805. this.onResizeObservable.notifyObservers(this);
  13806. }
  13807. };
  13808. // WebVR functions
  13809. /**
  13810. * Gets a boolean indicating if a webVR device was detected
  13811. * @returns true if a webVR device was detected
  13812. */
  13813. Engine.prototype.isVRDevicePresent = function () {
  13814. return !!this._vrDisplay;
  13815. };
  13816. /**
  13817. * Gets the current webVR device
  13818. * @returns the current webVR device (or null)
  13819. */
  13820. Engine.prototype.getVRDevice = function () {
  13821. return this._vrDisplay;
  13822. };
  13823. /**
  13824. * Initializes a webVR display and starts listening to display change events
  13825. * The onVRDisplayChangedObservable will be notified upon these changes
  13826. * @returns The onVRDisplayChangedObservable
  13827. */
  13828. Engine.prototype.initWebVR = function () {
  13829. this.initWebVRAsync();
  13830. return this.onVRDisplayChangedObservable;
  13831. };
  13832. /**
  13833. * Initializes a webVR display and starts listening to display change events
  13834. * The onVRDisplayChangedObservable will be notified upon these changes
  13835. * @returns A promise containing a VRDisplay and if vr is supported
  13836. */
  13837. Engine.prototype.initWebVRAsync = function () {
  13838. var _this = this;
  13839. var notifyObservers = function () {
  13840. var eventArgs = {
  13841. vrDisplay: _this._vrDisplay,
  13842. vrSupported: _this._vrSupported
  13843. };
  13844. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  13845. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  13846. };
  13847. if (!this._onVrDisplayConnect) {
  13848. this._onVrDisplayConnect = function (event) {
  13849. _this._vrDisplay = event.display;
  13850. notifyObservers();
  13851. };
  13852. this._onVrDisplayDisconnect = function () {
  13853. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  13854. _this._vrDisplay = undefined;
  13855. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  13856. notifyObservers();
  13857. };
  13858. this._onVrDisplayPresentChange = function () {
  13859. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  13860. };
  13861. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  13862. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  13863. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  13864. }
  13865. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  13866. this._webVRInitPromise.then(notifyObservers);
  13867. return this._webVRInitPromise;
  13868. };
  13869. /**
  13870. * Call this function to switch to webVR mode
  13871. * Will do nothing if webVR is not supported or if there is no webVR device
  13872. * @see http://doc.babylonjs.com/how_to/webvr_camera
  13873. */
  13874. Engine.prototype.enableVR = function () {
  13875. var _this = this;
  13876. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  13877. var onResolved = function () {
  13878. _this.onVRRequestPresentComplete.notifyObservers(true);
  13879. _this._onVRFullScreenTriggered();
  13880. };
  13881. var onRejected = function () {
  13882. _this.onVRRequestPresentComplete.notifyObservers(false);
  13883. };
  13884. this.onVRRequestPresentStart.notifyObservers(this);
  13885. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  13886. }
  13887. };
  13888. /**
  13889. * Call this function to leave webVR mode
  13890. * Will do nothing if webVR is not supported or if there is no webVR device
  13891. * @see http://doc.babylonjs.com/how_to/webvr_camera
  13892. */
  13893. Engine.prototype.disableVR = function () {
  13894. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  13895. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  13896. }
  13897. };
  13898. Engine.prototype._getVRDisplaysAsync = function () {
  13899. var _this = this;
  13900. return new Promise(function (res, rej) {
  13901. if (navigator.getVRDisplays) {
  13902. navigator.getVRDisplays().then(function (devices) {
  13903. _this._vrSupported = true;
  13904. // note that devices may actually be an empty array. This is fine;
  13905. // we expect this._vrDisplay to be undefined in this case.
  13906. _this._vrDisplay = devices[0];
  13907. res({
  13908. vrDisplay: _this._vrDisplay,
  13909. vrSupported: _this._vrSupported
  13910. });
  13911. });
  13912. }
  13913. else {
  13914. _this._vrDisplay = undefined;
  13915. _this._vrSupported = false;
  13916. res({
  13917. vrDisplay: _this._vrDisplay,
  13918. vrSupported: _this._vrSupported
  13919. });
  13920. }
  13921. });
  13922. };
  13923. /**
  13924. * Binds the frame buffer to the specified texture.
  13925. * @param texture The texture to render to or null for the default canvas
  13926. * @param faceIndex The face of the texture to render to in case of cube texture
  13927. * @param requiredWidth The width of the target to render to
  13928. * @param requiredHeight The height of the target to render to
  13929. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  13930. * @param depthStencilTexture The depth stencil texture to use to render
  13931. * @param lodLevel defines le lod level to bind to the frame buffer
  13932. */
  13933. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture, lodLevel) {
  13934. if (lodLevel === void 0) { lodLevel = 0; }
  13935. if (this._currentRenderTarget) {
  13936. this.unBindFramebuffer(this._currentRenderTarget);
  13937. }
  13938. this._currentRenderTarget = texture;
  13939. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  13940. var gl = this._gl;
  13941. if (texture.isCube) {
  13942. if (faceIndex === undefined) {
  13943. faceIndex = 0;
  13944. }
  13945. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, lodLevel);
  13946. if (depthStencilTexture) {
  13947. if (depthStencilTexture._generateStencilBuffer) {
  13948. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  13949. }
  13950. else {
  13951. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  13952. }
  13953. }
  13954. }
  13955. if (this._cachedViewport && !forceFullscreenViewport) {
  13956. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  13957. }
  13958. else {
  13959. if (!requiredWidth) {
  13960. requiredWidth = texture.width;
  13961. if (lodLevel) {
  13962. requiredWidth = requiredWidth / Math.pow(2, lodLevel);
  13963. }
  13964. }
  13965. if (!requiredHeight) {
  13966. requiredHeight = texture.height;
  13967. if (lodLevel) {
  13968. requiredHeight = requiredHeight / Math.pow(2, lodLevel);
  13969. }
  13970. }
  13971. this._viewport(0, 0, requiredWidth, requiredHeight);
  13972. }
  13973. this.wipeCaches();
  13974. };
  13975. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  13976. if (this._currentFramebuffer !== framebuffer) {
  13977. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  13978. this._currentFramebuffer = framebuffer;
  13979. }
  13980. };
  13981. /**
  13982. * Unbind the current render target texture from the webGL context
  13983. * @param texture defines the render target texture to unbind
  13984. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13985. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13986. */
  13987. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  13988. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13989. this._currentRenderTarget = null;
  13990. // If MSAA, we need to bitblt back to main texture
  13991. var gl = this._gl;
  13992. if (texture._MSAAFramebuffer) {
  13993. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  13994. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  13995. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13996. }
  13997. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13998. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13999. gl.generateMipmap(gl.TEXTURE_2D);
  14000. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  14001. }
  14002. if (onBeforeUnbind) {
  14003. if (texture._MSAAFramebuffer) {
  14004. // Bind the correct framebuffer
  14005. this.bindUnboundFramebuffer(texture._framebuffer);
  14006. }
  14007. onBeforeUnbind();
  14008. }
  14009. this.bindUnboundFramebuffer(null);
  14010. };
  14011. /**
  14012. * Unbind a list of render target textures from the webGL context
  14013. * This is used only when drawBuffer extension or webGL2 are active
  14014. * @param textures defines the render target textures to unbind
  14015. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  14016. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  14017. */
  14018. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  14019. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  14020. this._currentRenderTarget = null;
  14021. // If MSAA, we need to bitblt back to main texture
  14022. var gl = this._gl;
  14023. if (textures[0]._MSAAFramebuffer) {
  14024. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  14025. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  14026. var attachments = textures[0]._attachments;
  14027. if (!attachments) {
  14028. attachments = new Array(textures.length);
  14029. textures[0]._attachments = attachments;
  14030. }
  14031. for (var i = 0; i < textures.length; i++) {
  14032. var texture = textures[i];
  14033. for (var j = 0; j < attachments.length; j++) {
  14034. attachments[j] = gl.NONE;
  14035. }
  14036. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  14037. gl.readBuffer(attachments[i]);
  14038. gl.drawBuffers(attachments);
  14039. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  14040. }
  14041. for (var i = 0; i < attachments.length; i++) {
  14042. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  14043. }
  14044. gl.drawBuffers(attachments);
  14045. }
  14046. for (var i = 0; i < textures.length; i++) {
  14047. var texture = textures[i];
  14048. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  14049. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  14050. gl.generateMipmap(gl.TEXTURE_2D);
  14051. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  14052. }
  14053. }
  14054. if (onBeforeUnbind) {
  14055. if (textures[0]._MSAAFramebuffer) {
  14056. // Bind the correct framebuffer
  14057. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  14058. }
  14059. onBeforeUnbind();
  14060. }
  14061. this.bindUnboundFramebuffer(null);
  14062. };
  14063. /**
  14064. * Force the mipmap generation for the given render target texture
  14065. * @param texture defines the render target texture to use
  14066. */
  14067. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  14068. if (texture.generateMipMaps) {
  14069. var gl = this._gl;
  14070. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14071. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  14072. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14073. }
  14074. };
  14075. /**
  14076. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  14077. */
  14078. Engine.prototype.flushFramebuffer = function () {
  14079. this._gl.flush();
  14080. };
  14081. /**
  14082. * Unbind the current render target and bind the default framebuffer
  14083. */
  14084. Engine.prototype.restoreDefaultFramebuffer = function () {
  14085. if (this._currentRenderTarget) {
  14086. this.unBindFramebuffer(this._currentRenderTarget);
  14087. }
  14088. else {
  14089. this.bindUnboundFramebuffer(null);
  14090. }
  14091. if (this._cachedViewport) {
  14092. this.setViewport(this._cachedViewport);
  14093. }
  14094. this.wipeCaches();
  14095. };
  14096. // UBOs
  14097. /**
  14098. * Create an uniform buffer
  14099. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  14100. * @param elements defines the content of the uniform buffer
  14101. * @returns the webGL uniform buffer
  14102. */
  14103. Engine.prototype.createUniformBuffer = function (elements) {
  14104. var ubo = this._gl.createBuffer();
  14105. if (!ubo) {
  14106. throw new Error("Unable to create uniform buffer");
  14107. }
  14108. this.bindUniformBuffer(ubo);
  14109. if (elements instanceof Float32Array) {
  14110. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  14111. }
  14112. else {
  14113. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  14114. }
  14115. this.bindUniformBuffer(null);
  14116. ubo.references = 1;
  14117. return ubo;
  14118. };
  14119. /**
  14120. * Create a dynamic uniform buffer
  14121. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  14122. * @param elements defines the content of the uniform buffer
  14123. * @returns the webGL uniform buffer
  14124. */
  14125. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  14126. var ubo = this._gl.createBuffer();
  14127. if (!ubo) {
  14128. throw new Error("Unable to create dynamic uniform buffer");
  14129. }
  14130. this.bindUniformBuffer(ubo);
  14131. if (elements instanceof Float32Array) {
  14132. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  14133. }
  14134. else {
  14135. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  14136. }
  14137. this.bindUniformBuffer(null);
  14138. ubo.references = 1;
  14139. return ubo;
  14140. };
  14141. /**
  14142. * Update an existing uniform buffer
  14143. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  14144. * @param uniformBuffer defines the target uniform buffer
  14145. * @param elements defines the content to update
  14146. * @param offset defines the offset in the uniform buffer where update should start
  14147. * @param count defines the size of the data to update
  14148. */
  14149. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  14150. this.bindUniformBuffer(uniformBuffer);
  14151. if (offset === undefined) {
  14152. offset = 0;
  14153. }
  14154. if (count === undefined) {
  14155. if (elements instanceof Float32Array) {
  14156. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  14157. }
  14158. else {
  14159. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  14160. }
  14161. }
  14162. else {
  14163. if (elements instanceof Float32Array) {
  14164. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  14165. }
  14166. else {
  14167. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  14168. }
  14169. }
  14170. this.bindUniformBuffer(null);
  14171. };
  14172. // VBOs
  14173. Engine.prototype._resetVertexBufferBinding = function () {
  14174. this.bindArrayBuffer(null);
  14175. this._cachedVertexBuffers = null;
  14176. };
  14177. /**
  14178. * Creates a vertex buffer
  14179. * @param data the data for the vertex buffer
  14180. * @returns the new WebGL static buffer
  14181. */
  14182. Engine.prototype.createVertexBuffer = function (data) {
  14183. var vbo = this._gl.createBuffer();
  14184. if (!vbo) {
  14185. throw new Error("Unable to create vertex buffer");
  14186. }
  14187. this.bindArrayBuffer(vbo);
  14188. if (data instanceof Array) {
  14189. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  14190. }
  14191. else {
  14192. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  14193. }
  14194. this._resetVertexBufferBinding();
  14195. vbo.references = 1;
  14196. return vbo;
  14197. };
  14198. /**
  14199. * Creates a dynamic vertex buffer
  14200. * @param data the data for the dynamic vertex buffer
  14201. * @returns the new WebGL dynamic buffer
  14202. */
  14203. Engine.prototype.createDynamicVertexBuffer = function (data) {
  14204. var vbo = this._gl.createBuffer();
  14205. if (!vbo) {
  14206. throw new Error("Unable to create dynamic vertex buffer");
  14207. }
  14208. this.bindArrayBuffer(vbo);
  14209. if (data instanceof Array) {
  14210. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  14211. }
  14212. else {
  14213. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  14214. }
  14215. this._resetVertexBufferBinding();
  14216. vbo.references = 1;
  14217. return vbo;
  14218. };
  14219. /**
  14220. * Update a dynamic index buffer
  14221. * @param indexBuffer defines the target index buffer
  14222. * @param indices defines the data to update
  14223. * @param offset defines the offset in the target index buffer where update should start
  14224. */
  14225. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  14226. if (offset === void 0) { offset = 0; }
  14227. // Force cache update
  14228. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  14229. this.bindIndexBuffer(indexBuffer);
  14230. var arrayBuffer;
  14231. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  14232. arrayBuffer = indices;
  14233. }
  14234. else {
  14235. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  14236. }
  14237. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  14238. this._resetIndexBufferBinding();
  14239. };
  14240. /**
  14241. * Updates a dynamic vertex buffer.
  14242. * @param vertexBuffer the vertex buffer to update
  14243. * @param data the data used to update the vertex buffer
  14244. * @param byteOffset the byte offset of the data
  14245. * @param byteLength the byte length of the data
  14246. */
  14247. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  14248. this.bindArrayBuffer(vertexBuffer);
  14249. if (byteOffset === undefined) {
  14250. byteOffset = 0;
  14251. }
  14252. if (byteLength === undefined) {
  14253. if (data instanceof Array) {
  14254. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  14255. }
  14256. else {
  14257. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  14258. }
  14259. }
  14260. else {
  14261. if (data instanceof Array) {
  14262. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  14263. }
  14264. else {
  14265. if (data instanceof ArrayBuffer) {
  14266. data = new Uint8Array(data, byteOffset, byteLength);
  14267. }
  14268. else {
  14269. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  14270. }
  14271. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  14272. }
  14273. }
  14274. this._resetVertexBufferBinding();
  14275. };
  14276. Engine.prototype._resetIndexBufferBinding = function () {
  14277. this.bindIndexBuffer(null);
  14278. this._cachedIndexBuffer = null;
  14279. };
  14280. /**
  14281. * Creates a new index buffer
  14282. * @param indices defines the content of the index buffer
  14283. * @param updatable defines if the index buffer must be updatable
  14284. * @returns a new webGL buffer
  14285. */
  14286. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  14287. var vbo = this._gl.createBuffer();
  14288. if (!vbo) {
  14289. throw new Error("Unable to create index buffer");
  14290. }
  14291. this.bindIndexBuffer(vbo);
  14292. // Check for 32 bits indices
  14293. var arrayBuffer;
  14294. var need32Bits = false;
  14295. if (indices instanceof Uint16Array) {
  14296. arrayBuffer = indices;
  14297. }
  14298. else {
  14299. //check 32 bit support
  14300. if (this._caps.uintIndices) {
  14301. if (indices instanceof Uint32Array) {
  14302. arrayBuffer = indices;
  14303. need32Bits = true;
  14304. }
  14305. else {
  14306. //number[] or Int32Array, check if 32 bit is necessary
  14307. for (var index = 0; index < indices.length; index++) {
  14308. if (indices[index] > 65535) {
  14309. need32Bits = true;
  14310. break;
  14311. }
  14312. }
  14313. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  14314. }
  14315. }
  14316. else {
  14317. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  14318. arrayBuffer = new Uint16Array(indices);
  14319. }
  14320. }
  14321. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  14322. this._resetIndexBufferBinding();
  14323. vbo.references = 1;
  14324. vbo.is32Bits = need32Bits;
  14325. return vbo;
  14326. };
  14327. /**
  14328. * Bind a webGL buffer to the webGL context
  14329. * @param buffer defines the buffer to bind
  14330. */
  14331. Engine.prototype.bindArrayBuffer = function (buffer) {
  14332. if (!this._vaoRecordInProgress) {
  14333. this._unbindVertexArrayObject();
  14334. }
  14335. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  14336. };
  14337. /**
  14338. * Bind an uniform buffer to the current webGL context
  14339. * @param buffer defines the buffer to bind
  14340. */
  14341. Engine.prototype.bindUniformBuffer = function (buffer) {
  14342. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  14343. };
  14344. /**
  14345. * Bind a buffer to the current webGL context at a given location
  14346. * @param buffer defines the buffer to bind
  14347. * @param location defines the index where to bind the buffer
  14348. */
  14349. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  14350. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  14351. };
  14352. /**
  14353. * Bind a specific block at a given index in a specific shader program
  14354. * @param shaderProgram defines the shader program
  14355. * @param blockName defines the block name
  14356. * @param index defines the index where to bind the block
  14357. */
  14358. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  14359. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  14360. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  14361. };
  14362. Engine.prototype.bindIndexBuffer = function (buffer) {
  14363. if (!this._vaoRecordInProgress) {
  14364. this._unbindVertexArrayObject();
  14365. }
  14366. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  14367. };
  14368. Engine.prototype.bindBuffer = function (buffer, target) {
  14369. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  14370. this._gl.bindBuffer(target, buffer);
  14371. this._currentBoundBuffer[target] = buffer;
  14372. }
  14373. };
  14374. /**
  14375. * update the bound buffer with the given data
  14376. * @param data defines the data to update
  14377. */
  14378. Engine.prototype.updateArrayBuffer = function (data) {
  14379. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  14380. };
  14381. Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  14382. var pointer = this._currentBufferPointers[indx];
  14383. var changed = false;
  14384. if (!pointer.active) {
  14385. changed = true;
  14386. pointer.active = true;
  14387. pointer.index = indx;
  14388. pointer.size = size;
  14389. pointer.type = type;
  14390. pointer.normalized = normalized;
  14391. pointer.stride = stride;
  14392. pointer.offset = offset;
  14393. pointer.buffer = buffer;
  14394. }
  14395. else {
  14396. if (pointer.buffer !== buffer) {
  14397. pointer.buffer = buffer;
  14398. changed = true;
  14399. }
  14400. if (pointer.size !== size) {
  14401. pointer.size = size;
  14402. changed = true;
  14403. }
  14404. if (pointer.type !== type) {
  14405. pointer.type = type;
  14406. changed = true;
  14407. }
  14408. if (pointer.normalized !== normalized) {
  14409. pointer.normalized = normalized;
  14410. changed = true;
  14411. }
  14412. if (pointer.stride !== stride) {
  14413. pointer.stride = stride;
  14414. changed = true;
  14415. }
  14416. if (pointer.offset !== offset) {
  14417. pointer.offset = offset;
  14418. changed = true;
  14419. }
  14420. }
  14421. if (changed || this._vaoRecordInProgress) {
  14422. this.bindArrayBuffer(buffer);
  14423. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  14424. }
  14425. };
  14426. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  14427. if (indexBuffer == null) {
  14428. return;
  14429. }
  14430. if (this._cachedIndexBuffer !== indexBuffer) {
  14431. this._cachedIndexBuffer = indexBuffer;
  14432. this.bindIndexBuffer(indexBuffer);
  14433. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  14434. }
  14435. };
  14436. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  14437. var attributes = effect.getAttributesNames();
  14438. if (!this._vaoRecordInProgress) {
  14439. this._unbindVertexArrayObject();
  14440. }
  14441. this.unbindAllAttributes();
  14442. for (var index = 0; index < attributes.length; index++) {
  14443. var order = effect.getAttributeLocation(index);
  14444. if (order >= 0) {
  14445. var vertexBuffer = vertexBuffers[attributes[index]];
  14446. if (!vertexBuffer) {
  14447. continue;
  14448. }
  14449. this._gl.enableVertexAttribArray(order);
  14450. if (!this._vaoRecordInProgress) {
  14451. this._vertexAttribArraysEnabled[order] = true;
  14452. }
  14453. var buffer = vertexBuffer.getBuffer();
  14454. if (buffer) {
  14455. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  14456. if (vertexBuffer.getIsInstanced()) {
  14457. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  14458. if (!this._vaoRecordInProgress) {
  14459. this._currentInstanceLocations.push(order);
  14460. this._currentInstanceBuffers.push(buffer);
  14461. }
  14462. }
  14463. }
  14464. }
  14465. }
  14466. };
  14467. /**
  14468. * Records a vertex array object
  14469. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  14470. * @param vertexBuffers defines the list of vertex buffers to store
  14471. * @param indexBuffer defines the index buffer to store
  14472. * @param effect defines the effect to store
  14473. * @returns the new vertex array object
  14474. */
  14475. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  14476. var vao = this._gl.createVertexArray();
  14477. this._vaoRecordInProgress = true;
  14478. this._gl.bindVertexArray(vao);
  14479. this._mustWipeVertexAttributes = true;
  14480. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  14481. this.bindIndexBuffer(indexBuffer);
  14482. this._vaoRecordInProgress = false;
  14483. this._gl.bindVertexArray(null);
  14484. return vao;
  14485. };
  14486. /**
  14487. * Bind a specific vertex array object
  14488. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  14489. * @param vertexArrayObject defines the vertex array object to bind
  14490. * @param indexBuffer defines the index buffer to bind
  14491. */
  14492. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  14493. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  14494. this._cachedVertexArrayObject = vertexArrayObject;
  14495. this._gl.bindVertexArray(vertexArrayObject);
  14496. this._cachedVertexBuffers = null;
  14497. this._cachedIndexBuffer = null;
  14498. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  14499. this._mustWipeVertexAttributes = true;
  14500. }
  14501. };
  14502. /**
  14503. * Bind webGl buffers directly to the webGL context
  14504. * @param vertexBuffer defines the vertex buffer to bind
  14505. * @param indexBuffer defines the index buffer to bind
  14506. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  14507. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  14508. * @param effect defines the effect associated with the vertex buffer
  14509. */
  14510. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  14511. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  14512. this._cachedVertexBuffers = vertexBuffer;
  14513. this._cachedEffectForVertexBuffers = effect;
  14514. var attributesCount = effect.getAttributesCount();
  14515. this._unbindVertexArrayObject();
  14516. this.unbindAllAttributes();
  14517. var offset = 0;
  14518. for (var index = 0; index < attributesCount; index++) {
  14519. if (index < vertexDeclaration.length) {
  14520. var order = effect.getAttributeLocation(index);
  14521. if (order >= 0) {
  14522. this._gl.enableVertexAttribArray(order);
  14523. this._vertexAttribArraysEnabled[order] = true;
  14524. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  14525. }
  14526. offset += vertexDeclaration[index] * 4;
  14527. }
  14528. }
  14529. }
  14530. this._bindIndexBufferWithCache(indexBuffer);
  14531. };
  14532. Engine.prototype._unbindVertexArrayObject = function () {
  14533. if (!this._cachedVertexArrayObject) {
  14534. return;
  14535. }
  14536. this._cachedVertexArrayObject = null;
  14537. this._gl.bindVertexArray(null);
  14538. };
  14539. /**
  14540. * Bind a list of vertex buffers to the webGL context
  14541. * @param vertexBuffers defines the list of vertex buffers to bind
  14542. * @param indexBuffer defines the index buffer to bind
  14543. * @param effect defines the effect associated with the vertex buffers
  14544. */
  14545. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  14546. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  14547. this._cachedVertexBuffers = vertexBuffers;
  14548. this._cachedEffectForVertexBuffers = effect;
  14549. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  14550. }
  14551. this._bindIndexBufferWithCache(indexBuffer);
  14552. };
  14553. /**
  14554. * Unbind all instance attributes
  14555. */
  14556. Engine.prototype.unbindInstanceAttributes = function () {
  14557. var boundBuffer;
  14558. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  14559. var instancesBuffer = this._currentInstanceBuffers[i];
  14560. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  14561. boundBuffer = instancesBuffer;
  14562. this.bindArrayBuffer(instancesBuffer);
  14563. }
  14564. var offsetLocation = this._currentInstanceLocations[i];
  14565. this._gl.vertexAttribDivisor(offsetLocation, 0);
  14566. }
  14567. this._currentInstanceBuffers.length = 0;
  14568. this._currentInstanceLocations.length = 0;
  14569. };
  14570. /**
  14571. * Release and free the memory of a vertex array object
  14572. * @param vao defines the vertex array object to delete
  14573. */
  14574. Engine.prototype.releaseVertexArrayObject = function (vao) {
  14575. this._gl.deleteVertexArray(vao);
  14576. };
  14577. /** @hidden */
  14578. Engine.prototype._releaseBuffer = function (buffer) {
  14579. buffer.references--;
  14580. if (buffer.references === 0) {
  14581. this._gl.deleteBuffer(buffer);
  14582. return true;
  14583. }
  14584. return false;
  14585. };
  14586. /**
  14587. * Creates a webGL buffer to use with instanciation
  14588. * @param capacity defines the size of the buffer
  14589. * @returns the webGL buffer
  14590. */
  14591. Engine.prototype.createInstancesBuffer = function (capacity) {
  14592. var buffer = this._gl.createBuffer();
  14593. if (!buffer) {
  14594. throw new Error("Unable to create instance buffer");
  14595. }
  14596. buffer.capacity = capacity;
  14597. this.bindArrayBuffer(buffer);
  14598. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  14599. return buffer;
  14600. };
  14601. /**
  14602. * Delete a webGL buffer used with instanciation
  14603. * @param buffer defines the webGL buffer to delete
  14604. */
  14605. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  14606. this._gl.deleteBuffer(buffer);
  14607. };
  14608. /**
  14609. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  14610. * @param instancesBuffer defines the webGL buffer to update and bind
  14611. * @param data defines the data to store in the buffer
  14612. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  14613. */
  14614. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  14615. this.bindArrayBuffer(instancesBuffer);
  14616. if (data) {
  14617. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  14618. }
  14619. if (offsetLocations[0].index !== undefined) {
  14620. var stride = 0;
  14621. for (var i = 0; i < offsetLocations.length; i++) {
  14622. var ai = offsetLocations[i];
  14623. stride += ai.attributeSize * 4;
  14624. }
  14625. for (var i = 0; i < offsetLocations.length; i++) {
  14626. var ai = offsetLocations[i];
  14627. if (!this._vertexAttribArraysEnabled[ai.index]) {
  14628. this._gl.enableVertexAttribArray(ai.index);
  14629. this._vertexAttribArraysEnabled[ai.index] = true;
  14630. }
  14631. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  14632. this._gl.vertexAttribDivisor(ai.index, 1);
  14633. this._currentInstanceLocations.push(ai.index);
  14634. this._currentInstanceBuffers.push(instancesBuffer);
  14635. }
  14636. }
  14637. else {
  14638. for (var index = 0; index < 4; index++) {
  14639. var offsetLocation = offsetLocations[index];
  14640. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  14641. this._gl.enableVertexAttribArray(offsetLocation);
  14642. this._vertexAttribArraysEnabled[offsetLocation] = true;
  14643. }
  14644. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  14645. this._gl.vertexAttribDivisor(offsetLocation, 1);
  14646. this._currentInstanceLocations.push(offsetLocation);
  14647. this._currentInstanceBuffers.push(instancesBuffer);
  14648. }
  14649. }
  14650. };
  14651. /**
  14652. * Apply all cached states (depth, culling, stencil and alpha)
  14653. */
  14654. Engine.prototype.applyStates = function () {
  14655. this._depthCullingState.apply(this._gl);
  14656. this._stencilState.apply(this._gl);
  14657. this._alphaState.apply(this._gl);
  14658. };
  14659. /**
  14660. * Send a draw order
  14661. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  14662. * @param indexStart defines the starting index
  14663. * @param indexCount defines the number of index to draw
  14664. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  14665. */
  14666. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  14667. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  14668. };
  14669. /**
  14670. * Draw a list of points
  14671. * @param verticesStart defines the index of first vertex to draw
  14672. * @param verticesCount defines the count of vertices to draw
  14673. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  14674. */
  14675. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  14676. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  14677. };
  14678. /**
  14679. * Draw a list of unindexed primitives
  14680. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  14681. * @param verticesStart defines the index of first vertex to draw
  14682. * @param verticesCount defines the count of vertices to draw
  14683. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  14684. */
  14685. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  14686. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  14687. };
  14688. /**
  14689. * Draw a list of indexed primitives
  14690. * @param fillMode defines the primitive to use
  14691. * @param indexStart defines the starting index
  14692. * @param indexCount defines the number of index to draw
  14693. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  14694. */
  14695. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  14696. // Apply states
  14697. this.applyStates();
  14698. this._drawCalls.addCount(1, false);
  14699. // Render
  14700. var drawMode = this._drawMode(fillMode);
  14701. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  14702. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  14703. if (instancesCount) {
  14704. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  14705. }
  14706. else {
  14707. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  14708. }
  14709. };
  14710. /**
  14711. * Draw a list of unindexed primitives
  14712. * @param fillMode defines the primitive to use
  14713. * @param verticesStart defines the index of first vertex to draw
  14714. * @param verticesCount defines the count of vertices to draw
  14715. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  14716. */
  14717. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  14718. // Apply states
  14719. this.applyStates();
  14720. this._drawCalls.addCount(1, false);
  14721. var drawMode = this._drawMode(fillMode);
  14722. if (instancesCount) {
  14723. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  14724. }
  14725. else {
  14726. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  14727. }
  14728. };
  14729. Engine.prototype._drawMode = function (fillMode) {
  14730. switch (fillMode) {
  14731. // Triangle views
  14732. case BABYLON.Material.TriangleFillMode:
  14733. return this._gl.TRIANGLES;
  14734. case BABYLON.Material.PointFillMode:
  14735. return this._gl.POINTS;
  14736. case BABYLON.Material.WireFrameFillMode:
  14737. return this._gl.LINES;
  14738. // Draw modes
  14739. case BABYLON.Material.PointListDrawMode:
  14740. return this._gl.POINTS;
  14741. case BABYLON.Material.LineListDrawMode:
  14742. return this._gl.LINES;
  14743. case BABYLON.Material.LineLoopDrawMode:
  14744. return this._gl.LINE_LOOP;
  14745. case BABYLON.Material.LineStripDrawMode:
  14746. return this._gl.LINE_STRIP;
  14747. case BABYLON.Material.TriangleStripDrawMode:
  14748. return this._gl.TRIANGLE_STRIP;
  14749. case BABYLON.Material.TriangleFanDrawMode:
  14750. return this._gl.TRIANGLE_FAN;
  14751. default:
  14752. return this._gl.TRIANGLES;
  14753. }
  14754. };
  14755. // Shaders
  14756. /** @hidden */
  14757. Engine.prototype._releaseEffect = function (effect) {
  14758. if (this._compiledEffects[effect._key]) {
  14759. delete this._compiledEffects[effect._key];
  14760. this._deleteProgram(effect.getProgram());
  14761. }
  14762. };
  14763. /** @hidden */
  14764. Engine.prototype._deleteProgram = function (program) {
  14765. if (program) {
  14766. program.__SPECTOR_rebuildProgram = null;
  14767. if (program.transformFeedback) {
  14768. this.deleteTransformFeedback(program.transformFeedback);
  14769. program.transformFeedback = null;
  14770. }
  14771. this._gl.deleteProgram(program);
  14772. }
  14773. };
  14774. /**
  14775. * Create a new effect (used to store vertex/fragment shaders)
  14776. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  14777. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  14778. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  14779. * @param samplers defines an array of string used to represent textures
  14780. * @param defines defines the string containing the defines to use to compile the shaders
  14781. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  14782. * @param onCompiled defines a function to call when the effect creation is successful
  14783. * @param onError defines a function to call when the effect creation has failed
  14784. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  14785. * @returns the new Effect
  14786. */
  14787. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  14788. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  14789. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  14790. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  14791. if (this._compiledEffects[name]) {
  14792. var compiledEffect = this._compiledEffects[name];
  14793. if (onCompiled && compiledEffect.isReady()) {
  14794. onCompiled(compiledEffect);
  14795. }
  14796. return compiledEffect;
  14797. }
  14798. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  14799. effect._key = name;
  14800. this._compiledEffects[name] = effect;
  14801. return effect;
  14802. };
  14803. Engine.prototype._compileShader = function (source, type, defines, shaderVersion) {
  14804. return this._compileRawShader(shaderVersion + (defines ? defines + "\n" : "") + source, type);
  14805. };
  14806. Engine.prototype._compileRawShader = function (source, type) {
  14807. var gl = this._gl;
  14808. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  14809. if (!shader) {
  14810. throw new Error("Something went wrong while compile the shader.");
  14811. }
  14812. gl.shaderSource(shader, source);
  14813. gl.compileShader(shader);
  14814. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  14815. var log = gl.getShaderInfoLog(shader);
  14816. if (log) {
  14817. throw new Error(log);
  14818. }
  14819. }
  14820. return shader;
  14821. };
  14822. /**
  14823. * Directly creates a webGL program
  14824. * @param vertexCode defines the vertex shader code to use
  14825. * @param fragmentCode defines the fragment shader code to use
  14826. * @param context defines the webGL context to use (if not set, the current one will be used)
  14827. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  14828. * @returns the new webGL program
  14829. */
  14830. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  14831. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14832. context = context || this._gl;
  14833. var vertexShader = this._compileRawShader(vertexCode, "vertex");
  14834. var fragmentShader = this._compileRawShader(fragmentCode, "fragment");
  14835. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  14836. };
  14837. /**
  14838. * Creates a webGL program
  14839. * @param vertexCode defines the vertex shader code to use
  14840. * @param fragmentCode defines the fragment shader code to use
  14841. * @param defines defines the string containing the defines to use to compile the shaders
  14842. * @param context defines the webGL context to use (if not set, the current one will be used)
  14843. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  14844. * @returns the new webGL program
  14845. */
  14846. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  14847. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14848. context = context || this._gl;
  14849. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  14850. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  14851. var vertexShader = this._compileShader(vertexCode, "vertex", defines, shaderVersion);
  14852. var fragmentShader = this._compileShader(fragmentCode, "fragment", defines, shaderVersion);
  14853. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  14854. this.onAfterShaderCompilationObservable.notifyObservers(this);
  14855. return program;
  14856. };
  14857. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  14858. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14859. var shaderProgram = context.createProgram();
  14860. if (!shaderProgram) {
  14861. throw new Error("Unable to create program");
  14862. }
  14863. context.attachShader(shaderProgram, vertexShader);
  14864. context.attachShader(shaderProgram, fragmentShader);
  14865. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  14866. var transformFeedback = this.createTransformFeedback();
  14867. this.bindTransformFeedback(transformFeedback);
  14868. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  14869. shaderProgram.transformFeedback = transformFeedback;
  14870. }
  14871. context.linkProgram(shaderProgram);
  14872. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  14873. this.bindTransformFeedback(null);
  14874. }
  14875. shaderProgram.context = context;
  14876. shaderProgram.vertexShader = vertexShader;
  14877. shaderProgram.fragmentShader = fragmentShader;
  14878. if (!this._caps.parallelShaderCompile) {
  14879. this._finalizeProgram(shaderProgram);
  14880. }
  14881. else {
  14882. shaderProgram.isParallelCompiled = true;
  14883. }
  14884. return shaderProgram;
  14885. };
  14886. Engine.prototype._finalizeProgram = function (shaderProgram) {
  14887. var context = shaderProgram.context;
  14888. var vertexShader = shaderProgram.vertexShader;
  14889. var fragmentShader = shaderProgram.fragmentShader;
  14890. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  14891. if (!linked) {
  14892. var error = context.getProgramInfoLog(shaderProgram);
  14893. if (error) {
  14894. throw new Error(error);
  14895. }
  14896. }
  14897. if (this.validateShaderPrograms) {
  14898. context.validateProgram(shaderProgram);
  14899. var validated = context.getProgramParameter(shaderProgram, context.VALIDATE_STATUS);
  14900. if (!validated) {
  14901. var error = context.getProgramInfoLog(shaderProgram);
  14902. if (error) {
  14903. throw new Error(error);
  14904. }
  14905. }
  14906. }
  14907. context.deleteShader(vertexShader);
  14908. context.deleteShader(fragmentShader);
  14909. shaderProgram.context = undefined;
  14910. shaderProgram.vertexShader = undefined;
  14911. shaderProgram.fragmentShader = undefined;
  14912. if (shaderProgram.onCompiled) {
  14913. shaderProgram.onCompiled();
  14914. shaderProgram.onCompiled = undefined;
  14915. }
  14916. };
  14917. /** @hidden */
  14918. Engine.prototype._isProgramCompiled = function (shaderProgram) {
  14919. if (!shaderProgram.isParallelCompiled) {
  14920. return true;
  14921. }
  14922. if (this._gl.getProgramParameter(shaderProgram, this._caps.parallelShaderCompile.COMPLETION_STATUS_KHR)) {
  14923. this._finalizeProgram(shaderProgram);
  14924. return true;
  14925. }
  14926. return false;
  14927. };
  14928. /** @hidden */
  14929. Engine.prototype._executeWhenProgramIsCompiled = function (shaderProgram, action) {
  14930. if (!shaderProgram.isParallelCompiled) {
  14931. action();
  14932. return;
  14933. }
  14934. shaderProgram.onCompiled = action;
  14935. };
  14936. /**
  14937. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  14938. * @param shaderProgram defines the webGL program to use
  14939. * @param uniformsNames defines the list of uniform names
  14940. * @returns an array of webGL uniform locations
  14941. */
  14942. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  14943. var results = new Array();
  14944. for (var index = 0; index < uniformsNames.length; index++) {
  14945. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  14946. }
  14947. return results;
  14948. };
  14949. /**
  14950. * Gets the lsit of active attributes for a given webGL program
  14951. * @param shaderProgram defines the webGL program to use
  14952. * @param attributesNames defines the list of attribute names to get
  14953. * @returns an array of indices indicating the offset of each attribute
  14954. */
  14955. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  14956. var results = [];
  14957. for (var index = 0; index < attributesNames.length; index++) {
  14958. try {
  14959. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  14960. }
  14961. catch (e) {
  14962. results.push(-1);
  14963. }
  14964. }
  14965. return results;
  14966. };
  14967. /**
  14968. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  14969. * @param effect defines the effect to activate
  14970. */
  14971. Engine.prototype.enableEffect = function (effect) {
  14972. if (!effect || effect === this._currentEffect) {
  14973. return;
  14974. }
  14975. // Use program
  14976. this.bindSamplers(effect);
  14977. this._currentEffect = effect;
  14978. if (effect.onBind) {
  14979. effect.onBind(effect);
  14980. }
  14981. if (effect._onBindObservable) {
  14982. effect._onBindObservable.notifyObservers(effect);
  14983. }
  14984. };
  14985. /**
  14986. * Set the value of an uniform to an array of int32
  14987. * @param uniform defines the webGL uniform location where to store the value
  14988. * @param array defines the array of int32 to store
  14989. */
  14990. Engine.prototype.setIntArray = function (uniform, array) {
  14991. if (!uniform) {
  14992. return;
  14993. }
  14994. this._gl.uniform1iv(uniform, array);
  14995. };
  14996. /**
  14997. * Set the value of an uniform to an array of int32 (stored as vec2)
  14998. * @param uniform defines the webGL uniform location where to store the value
  14999. * @param array defines the array of int32 to store
  15000. */
  15001. Engine.prototype.setIntArray2 = function (uniform, array) {
  15002. if (!uniform || array.length % 2 !== 0) {
  15003. return;
  15004. }
  15005. this._gl.uniform2iv(uniform, array);
  15006. };
  15007. /**
  15008. * Set the value of an uniform to an array of int32 (stored as vec3)
  15009. * @param uniform defines the webGL uniform location where to store the value
  15010. * @param array defines the array of int32 to store
  15011. */
  15012. Engine.prototype.setIntArray3 = function (uniform, array) {
  15013. if (!uniform || array.length % 3 !== 0) {
  15014. return;
  15015. }
  15016. this._gl.uniform3iv(uniform, array);
  15017. };
  15018. /**
  15019. * Set the value of an uniform to an array of int32 (stored as vec4)
  15020. * @param uniform defines the webGL uniform location where to store the value
  15021. * @param array defines the array of int32 to store
  15022. */
  15023. Engine.prototype.setIntArray4 = function (uniform, array) {
  15024. if (!uniform || array.length % 4 !== 0) {
  15025. return;
  15026. }
  15027. this._gl.uniform4iv(uniform, array);
  15028. };
  15029. /**
  15030. * Set the value of an uniform to an array of float32
  15031. * @param uniform defines the webGL uniform location where to store the value
  15032. * @param array defines the array of float32 to store
  15033. */
  15034. Engine.prototype.setFloatArray = function (uniform, array) {
  15035. if (!uniform) {
  15036. return;
  15037. }
  15038. this._gl.uniform1fv(uniform, array);
  15039. };
  15040. /**
  15041. * Set the value of an uniform to an array of float32 (stored as vec2)
  15042. * @param uniform defines the webGL uniform location where to store the value
  15043. * @param array defines the array of float32 to store
  15044. */
  15045. Engine.prototype.setFloatArray2 = function (uniform, array) {
  15046. if (!uniform || array.length % 2 !== 0) {
  15047. return;
  15048. }
  15049. this._gl.uniform2fv(uniform, array);
  15050. };
  15051. /**
  15052. * Set the value of an uniform to an array of float32 (stored as vec3)
  15053. * @param uniform defines the webGL uniform location where to store the value
  15054. * @param array defines the array of float32 to store
  15055. */
  15056. Engine.prototype.setFloatArray3 = function (uniform, array) {
  15057. if (!uniform || array.length % 3 !== 0) {
  15058. return;
  15059. }
  15060. this._gl.uniform3fv(uniform, array);
  15061. };
  15062. /**
  15063. * Set the value of an uniform to an array of float32 (stored as vec4)
  15064. * @param uniform defines the webGL uniform location where to store the value
  15065. * @param array defines the array of float32 to store
  15066. */
  15067. Engine.prototype.setFloatArray4 = function (uniform, array) {
  15068. if (!uniform || array.length % 4 !== 0) {
  15069. return;
  15070. }
  15071. this._gl.uniform4fv(uniform, array);
  15072. };
  15073. /**
  15074. * Set the value of an uniform to an array of number
  15075. * @param uniform defines the webGL uniform location where to store the value
  15076. * @param array defines the array of number to store
  15077. */
  15078. Engine.prototype.setArray = function (uniform, array) {
  15079. if (!uniform) {
  15080. return;
  15081. }
  15082. this._gl.uniform1fv(uniform, array);
  15083. };
  15084. /**
  15085. * Set the value of an uniform to an array of number (stored as vec2)
  15086. * @param uniform defines the webGL uniform location where to store the value
  15087. * @param array defines the array of number to store
  15088. */
  15089. Engine.prototype.setArray2 = function (uniform, array) {
  15090. if (!uniform || array.length % 2 !== 0) {
  15091. return;
  15092. }
  15093. this._gl.uniform2fv(uniform, array);
  15094. };
  15095. /**
  15096. * Set the value of an uniform to an array of number (stored as vec3)
  15097. * @param uniform defines the webGL uniform location where to store the value
  15098. * @param array defines the array of number to store
  15099. */
  15100. Engine.prototype.setArray3 = function (uniform, array) {
  15101. if (!uniform || array.length % 3 !== 0) {
  15102. return;
  15103. }
  15104. this._gl.uniform3fv(uniform, array);
  15105. };
  15106. /**
  15107. * Set the value of an uniform to an array of number (stored as vec4)
  15108. * @param uniform defines the webGL uniform location where to store the value
  15109. * @param array defines the array of number to store
  15110. */
  15111. Engine.prototype.setArray4 = function (uniform, array) {
  15112. if (!uniform || array.length % 4 !== 0) {
  15113. return;
  15114. }
  15115. this._gl.uniform4fv(uniform, array);
  15116. };
  15117. /**
  15118. * Set the value of an uniform to an array of float32 (stored as matrices)
  15119. * @param uniform defines the webGL uniform location where to store the value
  15120. * @param matrices defines the array of float32 to store
  15121. */
  15122. Engine.prototype.setMatrices = function (uniform, matrices) {
  15123. if (!uniform) {
  15124. return;
  15125. }
  15126. this._gl.uniformMatrix4fv(uniform, false, matrices);
  15127. };
  15128. /**
  15129. * Set the value of an uniform to a matrix
  15130. * @param uniform defines the webGL uniform location where to store the value
  15131. * @param matrix defines the matrix to store
  15132. */
  15133. Engine.prototype.setMatrix = function (uniform, matrix) {
  15134. if (!uniform) {
  15135. return;
  15136. }
  15137. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  15138. };
  15139. /**
  15140. * Set the value of an uniform to a matrix (3x3)
  15141. * @param uniform defines the webGL uniform location where to store the value
  15142. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  15143. */
  15144. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  15145. if (!uniform) {
  15146. return;
  15147. }
  15148. this._gl.uniformMatrix3fv(uniform, false, matrix);
  15149. };
  15150. /**
  15151. * Set the value of an uniform to a matrix (2x2)
  15152. * @param uniform defines the webGL uniform location where to store the value
  15153. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  15154. */
  15155. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  15156. if (!uniform) {
  15157. return;
  15158. }
  15159. this._gl.uniformMatrix2fv(uniform, false, matrix);
  15160. };
  15161. /**
  15162. * Set the value of an uniform to a number (int)
  15163. * @param uniform defines the webGL uniform location where to store the value
  15164. * @param value defines the int number to store
  15165. */
  15166. Engine.prototype.setInt = function (uniform, value) {
  15167. if (!uniform) {
  15168. return;
  15169. }
  15170. this._gl.uniform1i(uniform, value);
  15171. };
  15172. /**
  15173. * Set the value of an uniform to a number (float)
  15174. * @param uniform defines the webGL uniform location where to store the value
  15175. * @param value defines the float number to store
  15176. */
  15177. Engine.prototype.setFloat = function (uniform, value) {
  15178. if (!uniform) {
  15179. return;
  15180. }
  15181. this._gl.uniform1f(uniform, value);
  15182. };
  15183. /**
  15184. * Set the value of an uniform to a vec2
  15185. * @param uniform defines the webGL uniform location where to store the value
  15186. * @param x defines the 1st component of the value
  15187. * @param y defines the 2nd component of the value
  15188. */
  15189. Engine.prototype.setFloat2 = function (uniform, x, y) {
  15190. if (!uniform) {
  15191. return;
  15192. }
  15193. this._gl.uniform2f(uniform, x, y);
  15194. };
  15195. /**
  15196. * Set the value of an uniform to a vec3
  15197. * @param uniform defines the webGL uniform location where to store the value
  15198. * @param x defines the 1st component of the value
  15199. * @param y defines the 2nd component of the value
  15200. * @param z defines the 3rd component of the value
  15201. */
  15202. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  15203. if (!uniform) {
  15204. return;
  15205. }
  15206. this._gl.uniform3f(uniform, x, y, z);
  15207. };
  15208. /**
  15209. * Set the value of an uniform to a boolean
  15210. * @param uniform defines the webGL uniform location where to store the value
  15211. * @param bool defines the boolean to store
  15212. */
  15213. Engine.prototype.setBool = function (uniform, bool) {
  15214. if (!uniform) {
  15215. return;
  15216. }
  15217. this._gl.uniform1i(uniform, bool);
  15218. };
  15219. /**
  15220. * Set the value of an uniform to a vec4
  15221. * @param uniform defines the webGL uniform location where to store the value
  15222. * @param x defines the 1st component of the value
  15223. * @param y defines the 2nd component of the value
  15224. * @param z defines the 3rd component of the value
  15225. * @param w defines the 4th component of the value
  15226. */
  15227. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  15228. if (!uniform) {
  15229. return;
  15230. }
  15231. this._gl.uniform4f(uniform, x, y, z, w);
  15232. };
  15233. /**
  15234. * Set the value of an uniform to a Color3
  15235. * @param uniform defines the webGL uniform location where to store the value
  15236. * @param color3 defines the color to store
  15237. */
  15238. Engine.prototype.setColor3 = function (uniform, color3) {
  15239. if (!uniform) {
  15240. return;
  15241. }
  15242. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  15243. };
  15244. /**
  15245. * Set the value of an uniform to a Color3 and an alpha value
  15246. * @param uniform defines the webGL uniform location where to store the value
  15247. * @param color3 defines the color to store
  15248. * @param alpha defines the alpha component to store
  15249. */
  15250. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  15251. if (!uniform) {
  15252. return;
  15253. }
  15254. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  15255. };
  15256. /**
  15257. * Sets a Color4 on a uniform variable
  15258. * @param uniform defines the uniform location
  15259. * @param color4 defines the value to be set
  15260. */
  15261. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  15262. if (!uniform) {
  15263. return;
  15264. }
  15265. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  15266. };
  15267. // States
  15268. /**
  15269. * Set various states to the webGL context
  15270. * @param culling defines backface culling state
  15271. * @param zOffset defines the value to apply to zOffset (0 by default)
  15272. * @param force defines if states must be applied even if cache is up to date
  15273. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  15274. */
  15275. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  15276. if (zOffset === void 0) { zOffset = 0; }
  15277. if (reverseSide === void 0) { reverseSide = false; }
  15278. // Culling
  15279. if (this._depthCullingState.cull !== culling || force) {
  15280. this._depthCullingState.cull = culling;
  15281. }
  15282. // Cull face
  15283. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  15284. if (this._depthCullingState.cullFace !== cullFace || force) {
  15285. this._depthCullingState.cullFace = cullFace;
  15286. }
  15287. // Z offset
  15288. this.setZOffset(zOffset);
  15289. // Front face
  15290. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  15291. if (this._depthCullingState.frontFace !== frontFace || force) {
  15292. this._depthCullingState.frontFace = frontFace;
  15293. }
  15294. };
  15295. /**
  15296. * Set the z offset to apply to current rendering
  15297. * @param value defines the offset to apply
  15298. */
  15299. Engine.prototype.setZOffset = function (value) {
  15300. this._depthCullingState.zOffset = value;
  15301. };
  15302. /**
  15303. * Gets the current value of the zOffset
  15304. * @returns the current zOffset state
  15305. */
  15306. Engine.prototype.getZOffset = function () {
  15307. return this._depthCullingState.zOffset;
  15308. };
  15309. /**
  15310. * Enable or disable depth buffering
  15311. * @param enable defines the state to set
  15312. */
  15313. Engine.prototype.setDepthBuffer = function (enable) {
  15314. this._depthCullingState.depthTest = enable;
  15315. };
  15316. /**
  15317. * Gets a boolean indicating if depth writing is enabled
  15318. * @returns the current depth writing state
  15319. */
  15320. Engine.prototype.getDepthWrite = function () {
  15321. return this._depthCullingState.depthMask;
  15322. };
  15323. /**
  15324. * Enable or disable depth writing
  15325. * @param enable defines the state to set
  15326. */
  15327. Engine.prototype.setDepthWrite = function (enable) {
  15328. this._depthCullingState.depthMask = enable;
  15329. };
  15330. /**
  15331. * Enable or disable color writing
  15332. * @param enable defines the state to set
  15333. */
  15334. Engine.prototype.setColorWrite = function (enable) {
  15335. this._gl.colorMask(enable, enable, enable, enable);
  15336. this._colorWrite = enable;
  15337. };
  15338. /**
  15339. * Gets a boolean indicating if color writing is enabled
  15340. * @returns the current color writing state
  15341. */
  15342. Engine.prototype.getColorWrite = function () {
  15343. return this._colorWrite;
  15344. };
  15345. /**
  15346. * Sets alpha constants used by some alpha blending modes
  15347. * @param r defines the red component
  15348. * @param g defines the green component
  15349. * @param b defines the blue component
  15350. * @param a defines the alpha component
  15351. */
  15352. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  15353. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  15354. };
  15355. /**
  15356. * Sets the current alpha mode
  15357. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  15358. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  15359. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  15360. */
  15361. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  15362. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  15363. if (this._alphaMode === mode) {
  15364. return;
  15365. }
  15366. switch (mode) {
  15367. case Engine.ALPHA_DISABLE:
  15368. this._alphaState.alphaBlend = false;
  15369. break;
  15370. case Engine.ALPHA_PREMULTIPLIED:
  15371. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  15372. this._alphaState.alphaBlend = true;
  15373. break;
  15374. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  15375. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  15376. this._alphaState.alphaBlend = true;
  15377. break;
  15378. case Engine.ALPHA_COMBINE:
  15379. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  15380. this._alphaState.alphaBlend = true;
  15381. break;
  15382. case Engine.ALPHA_ONEONE:
  15383. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  15384. this._alphaState.alphaBlend = true;
  15385. break;
  15386. case Engine.ALPHA_ADD:
  15387. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  15388. this._alphaState.alphaBlend = true;
  15389. break;
  15390. case Engine.ALPHA_SUBTRACT:
  15391. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  15392. this._alphaState.alphaBlend = true;
  15393. break;
  15394. case Engine.ALPHA_MULTIPLY:
  15395. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  15396. this._alphaState.alphaBlend = true;
  15397. break;
  15398. case Engine.ALPHA_MAXIMIZED:
  15399. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  15400. this._alphaState.alphaBlend = true;
  15401. break;
  15402. case Engine.ALPHA_INTERPOLATE:
  15403. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  15404. this._alphaState.alphaBlend = true;
  15405. break;
  15406. case Engine.ALPHA_SCREENMODE:
  15407. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  15408. this._alphaState.alphaBlend = true;
  15409. break;
  15410. }
  15411. if (!noDepthWriteChange) {
  15412. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  15413. }
  15414. this._alphaMode = mode;
  15415. };
  15416. /**
  15417. * Gets the current alpha mode
  15418. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  15419. * @returns the current alpha mode
  15420. */
  15421. Engine.prototype.getAlphaMode = function () {
  15422. return this._alphaMode;
  15423. };
  15424. // Textures
  15425. /**
  15426. * Clears the list of texture accessible through engine.
  15427. * This can help preventing texture load conflict due to name collision.
  15428. */
  15429. Engine.prototype.clearInternalTexturesCache = function () {
  15430. this._internalTexturesCache = [];
  15431. };
  15432. /**
  15433. * Force the entire cache to be cleared
  15434. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  15435. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  15436. */
  15437. Engine.prototype.wipeCaches = function (bruteForce) {
  15438. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  15439. return;
  15440. }
  15441. this._currentEffect = null;
  15442. this._viewportCached.x = 0;
  15443. this._viewportCached.y = 0;
  15444. this._viewportCached.z = 0;
  15445. this._viewportCached.w = 0;
  15446. if (bruteForce) {
  15447. this.resetTextureCache();
  15448. this._currentProgram = null;
  15449. this._stencilState.reset();
  15450. this._depthCullingState.reset();
  15451. this.setDepthFunctionToLessOrEqual();
  15452. this._alphaState.reset();
  15453. this._unpackFlipYCached = null;
  15454. }
  15455. this._resetVertexBufferBinding();
  15456. this._cachedIndexBuffer = null;
  15457. this._cachedEffectForVertexBuffers = null;
  15458. this._unbindVertexArrayObject();
  15459. this.bindIndexBuffer(null);
  15460. };
  15461. /**
  15462. * Set the compressed texture format to use, based on the formats you have, and the formats
  15463. * supported by the hardware / browser.
  15464. *
  15465. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  15466. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  15467. * to API arguments needed to compressed textures. This puts the burden on the container
  15468. * generator to house the arcane code for determining these for current & future formats.
  15469. *
  15470. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  15471. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  15472. *
  15473. * Note: The result of this call is not taken into account when a texture is base64.
  15474. *
  15475. * @param formatsAvailable defines the list of those format families you have created
  15476. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  15477. *
  15478. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  15479. * @returns The extension selected.
  15480. */
  15481. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  15482. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  15483. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  15484. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  15485. return this._textureFormatInUse = this._texturesSupported[i];
  15486. }
  15487. }
  15488. }
  15489. // actively set format to nothing, to allow this to be called more than once
  15490. // and possibly fail the 2nd time
  15491. this._textureFormatInUse = null;
  15492. return null;
  15493. };
  15494. Engine.prototype._getSamplingParameters = function (samplingMode, generateMipMaps) {
  15495. var gl = this._gl;
  15496. var magFilter = gl.NEAREST;
  15497. var minFilter = gl.NEAREST;
  15498. switch (samplingMode) {
  15499. case Engine.TEXTURE_BILINEAR_SAMPLINGMODE:
  15500. magFilter = gl.LINEAR;
  15501. if (generateMipMaps) {
  15502. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  15503. }
  15504. else {
  15505. minFilter = gl.LINEAR;
  15506. }
  15507. break;
  15508. case Engine.TEXTURE_TRILINEAR_SAMPLINGMODE:
  15509. magFilter = gl.LINEAR;
  15510. if (generateMipMaps) {
  15511. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  15512. }
  15513. else {
  15514. minFilter = gl.LINEAR;
  15515. }
  15516. break;
  15517. case Engine.TEXTURE_NEAREST_SAMPLINGMODE:
  15518. magFilter = gl.NEAREST;
  15519. if (generateMipMaps) {
  15520. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  15521. }
  15522. else {
  15523. minFilter = gl.NEAREST;
  15524. }
  15525. break;
  15526. case Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST:
  15527. magFilter = gl.NEAREST;
  15528. if (generateMipMaps) {
  15529. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  15530. }
  15531. else {
  15532. minFilter = gl.NEAREST;
  15533. }
  15534. break;
  15535. case Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST:
  15536. magFilter = gl.NEAREST;
  15537. if (generateMipMaps) {
  15538. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  15539. }
  15540. else {
  15541. minFilter = gl.LINEAR;
  15542. }
  15543. break;
  15544. case Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR:
  15545. magFilter = gl.NEAREST;
  15546. if (generateMipMaps) {
  15547. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  15548. }
  15549. else {
  15550. minFilter = gl.LINEAR;
  15551. }
  15552. break;
  15553. case Engine.TEXTURE_NEAREST_LINEAR:
  15554. magFilter = gl.NEAREST;
  15555. minFilter = gl.LINEAR;
  15556. break;
  15557. case Engine.TEXTURE_NEAREST_NEAREST:
  15558. magFilter = gl.NEAREST;
  15559. minFilter = gl.NEAREST;
  15560. break;
  15561. case Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST:
  15562. magFilter = gl.LINEAR;
  15563. if (generateMipMaps) {
  15564. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  15565. }
  15566. else {
  15567. minFilter = gl.NEAREST;
  15568. }
  15569. break;
  15570. case Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR:
  15571. magFilter = gl.LINEAR;
  15572. if (generateMipMaps) {
  15573. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  15574. }
  15575. else {
  15576. minFilter = gl.NEAREST;
  15577. }
  15578. break;
  15579. case Engine.TEXTURE_LINEAR_LINEAR:
  15580. magFilter = gl.LINEAR;
  15581. minFilter = gl.LINEAR;
  15582. break;
  15583. case Engine.TEXTURE_LINEAR_NEAREST:
  15584. magFilter = gl.LINEAR;
  15585. minFilter = gl.NEAREST;
  15586. break;
  15587. }
  15588. return {
  15589. min: minFilter,
  15590. mag: magFilter
  15591. };
  15592. };
  15593. Engine.prototype._partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  15594. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  15595. var img;
  15596. var onload = function () {
  15597. loadedImages[index] = img;
  15598. loadedImages._internalCount++;
  15599. if (scene) {
  15600. scene._removePendingData(img);
  15601. }
  15602. if (loadedImages._internalCount === 6) {
  15603. onfinish(loadedImages);
  15604. }
  15605. };
  15606. var onerror = function (message, exception) {
  15607. if (scene) {
  15608. scene._removePendingData(img);
  15609. }
  15610. if (onErrorCallBack) {
  15611. onErrorCallBack(message, exception);
  15612. }
  15613. };
  15614. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.offlineProvider : null);
  15615. if (scene) {
  15616. scene._addPendingData(img);
  15617. }
  15618. };
  15619. Engine.prototype._cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  15620. if (onError === void 0) { onError = null; }
  15621. var loadedImages = [];
  15622. loadedImages._internalCount = 0;
  15623. for (var index = 0; index < 6; index++) {
  15624. this._partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  15625. }
  15626. };
  15627. /** @hidden */
  15628. Engine.prototype._createTexture = function () {
  15629. var texture = this._gl.createTexture();
  15630. if (!texture) {
  15631. throw new Error("Unable to create texture");
  15632. }
  15633. return texture;
  15634. };
  15635. /**
  15636. * Usually called from BABYLON.Texture.ts.
  15637. * Passed information to create a WebGLTexture
  15638. * @param urlArg defines a value which contains one of the following:
  15639. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  15640. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  15641. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  15642. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  15643. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  15644. * @param scene needed for loading to the correct scene
  15645. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  15646. * @param onLoad optional callback to be called upon successful completion
  15647. * @param onError optional callback to be called upon failure
  15648. * @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
  15649. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  15650. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  15651. * @param forcedExtension defines the extension to use to pick the right loader
  15652. * @returns a InternalTexture for assignment back into BABYLON.Texture
  15653. */
  15654. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format, forcedExtension) {
  15655. var _this = this;
  15656. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  15657. if (onLoad === void 0) { onLoad = null; }
  15658. if (onError === void 0) { onError = null; }
  15659. if (buffer === void 0) { buffer = null; }
  15660. if (fallback === void 0) { fallback = null; }
  15661. if (format === void 0) { format = null; }
  15662. if (forcedExtension === void 0) { forcedExtension = null; }
  15663. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  15664. var fromData = url.substr(0, 5) === "data:";
  15665. var fromBlob = url.substr(0, 5) === "blob:";
  15666. var isBase64 = fromData && url.indexOf(";base64,") !== -1;
  15667. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  15668. // establish the file extension, if possible
  15669. var lastDot = url.lastIndexOf('.');
  15670. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? url.substring(lastDot).toLowerCase() : "");
  15671. var loader = null;
  15672. for (var _i = 0, _a = Engine._TextureLoaders; _i < _a.length; _i++) {
  15673. var availableLoader = _a[_i];
  15674. if (availableLoader.canLoad(extension, this._textureFormatInUse, fallback, isBase64, buffer ? true : false)) {
  15675. loader = availableLoader;
  15676. break;
  15677. }
  15678. }
  15679. if (loader) {
  15680. url = loader.transformUrl(url, this._textureFormatInUse);
  15681. }
  15682. if (scene) {
  15683. scene._addPendingData(texture);
  15684. }
  15685. texture.url = url;
  15686. texture.generateMipMaps = !noMipmap;
  15687. texture.samplingMode = samplingMode;
  15688. texture.invertY = invertY;
  15689. if (!this._doNotHandleContextLost) {
  15690. // Keep a link to the buffer only if we plan to handle context lost
  15691. texture._buffer = buffer;
  15692. }
  15693. var onLoadObserver = null;
  15694. if (onLoad && !fallback) {
  15695. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  15696. }
  15697. if (!fallback) {
  15698. this._internalTexturesCache.push(texture);
  15699. }
  15700. var onInternalError = function (message, exception) {
  15701. if (scene) {
  15702. scene._removePendingData(texture);
  15703. }
  15704. var customFallback = false;
  15705. if (loader) {
  15706. var fallbackUrl = loader.getFallbackTextureUrl(url, _this._textureFormatInUse);
  15707. if (fallbackUrl) {
  15708. // Add Back
  15709. customFallback = true;
  15710. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  15711. }
  15712. }
  15713. if (!customFallback) {
  15714. if (onLoadObserver) {
  15715. texture.onLoadedObservable.remove(onLoadObserver);
  15716. }
  15717. if (BABYLON.Tools.UseFallbackTexture) {
  15718. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  15719. }
  15720. }
  15721. if (onError) {
  15722. onError(message || "Unknown error", exception);
  15723. }
  15724. };
  15725. // processing for non-image formats
  15726. if (loader) {
  15727. var callback = function (data) {
  15728. loader.loadData(data, texture, function (width, height, loadMipmap, isCompressed, done) {
  15729. _this._prepareWebGLTexture(texture, scene, width, height, invertY, !loadMipmap, isCompressed, function () {
  15730. done();
  15731. return false;
  15732. }, samplingMode);
  15733. });
  15734. };
  15735. if (!buffer) {
  15736. this._loadFile(url, callback, undefined, scene ? scene.offlineProvider : undefined, true, function (request, exception) {
  15737. onInternalError("Unable to load " + (request ? request.responseURL : url, exception));
  15738. });
  15739. }
  15740. else {
  15741. callback(buffer);
  15742. }
  15743. }
  15744. else {
  15745. var onload = function (img) {
  15746. if (fromBlob && !_this._doNotHandleContextLost) {
  15747. // We need to store the image if we need to rebuild the texture
  15748. // in case of a webgl context lost
  15749. texture._buffer = img;
  15750. }
  15751. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  15752. var gl = _this._gl;
  15753. var isPot = (img.width === potWidth && img.height === potHeight);
  15754. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  15755. if (isPot) {
  15756. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  15757. return false;
  15758. }
  15759. var maxTextureSize = _this._caps.maxTextureSize;
  15760. if (img.width > maxTextureSize || img.height > maxTextureSize) {
  15761. _this._prepareWorkingCanvas();
  15762. if (!_this._workingCanvas || !_this._workingContext) {
  15763. return false;
  15764. }
  15765. _this._workingCanvas.width = potWidth;
  15766. _this._workingCanvas.height = potHeight;
  15767. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  15768. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  15769. texture.width = potWidth;
  15770. texture.height = potHeight;
  15771. return false;
  15772. }
  15773. else {
  15774. // Using shaders when possible to rescale because canvas.drawImage is lossy
  15775. var source_1 = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  15776. _this._bindTextureDirectly(gl.TEXTURE_2D, source_1, true);
  15777. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  15778. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15779. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  15780. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15781. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15782. _this._rescaleTexture(source_1, texture, scene, internalFormat, function () {
  15783. _this._releaseTexture(source_1);
  15784. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15785. continuationCallback();
  15786. });
  15787. }
  15788. return true;
  15789. }, samplingMode);
  15790. };
  15791. if (!fromData || isBase64) {
  15792. if (buffer instanceof HTMLImageElement) {
  15793. onload(buffer);
  15794. }
  15795. else {
  15796. BABYLON.Tools.LoadImage(url, onload, onInternalError, scene ? scene.offlineProvider : null);
  15797. }
  15798. }
  15799. else if (typeof buffer === "string" || buffer instanceof ArrayBuffer || buffer instanceof Blob) {
  15800. BABYLON.Tools.LoadImage(buffer, onload, onInternalError, scene ? scene.offlineProvider : null);
  15801. }
  15802. else {
  15803. onload(buffer);
  15804. }
  15805. }
  15806. return texture;
  15807. };
  15808. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  15809. var _this = this;
  15810. var rtt = this.createRenderTargetTexture({
  15811. width: destination.width,
  15812. height: destination.height,
  15813. }, {
  15814. generateMipMaps: false,
  15815. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  15816. samplingMode: Engine.TEXTURE_BILINEAR_SAMPLINGMODE,
  15817. generateDepthBuffer: false,
  15818. generateStencilBuffer: false
  15819. });
  15820. if (!this._rescalePostProcess) {
  15821. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, Engine.TEXTURE_BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  15822. }
  15823. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  15824. _this._rescalePostProcess.onApply = function (effect) {
  15825. effect._bindTexture("textureSampler", source);
  15826. };
  15827. var hostingScene = scene;
  15828. if (!hostingScene) {
  15829. hostingScene = _this.scenes[_this.scenes.length - 1];
  15830. }
  15831. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  15832. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  15833. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  15834. _this.unBindFramebuffer(rtt);
  15835. _this._releaseTexture(rtt);
  15836. if (onComplete) {
  15837. onComplete();
  15838. }
  15839. });
  15840. };
  15841. /**
  15842. * Update a raw texture
  15843. * @param texture defines the texture to update
  15844. * @param data defines the data to store in the texture
  15845. * @param format defines the format of the data
  15846. * @param invertY defines if data must be stored with Y axis inverted
  15847. * @param compression defines the compression used (null by default)
  15848. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15849. */
  15850. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  15851. if (compression === void 0) { compression = null; }
  15852. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  15853. if (!texture) {
  15854. return;
  15855. }
  15856. // babylon's internalSizedFomat but gl's texImage2D internalFormat
  15857. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  15858. // babylon's internalFormat but gl's texImage2D format
  15859. var internalFormat = this._getInternalFormat(format);
  15860. var textureType = this._getWebGLTextureType(type);
  15861. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15862. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  15863. if (!this._doNotHandleContextLost) {
  15864. texture._bufferView = data;
  15865. texture.format = format;
  15866. texture.type = type;
  15867. texture.invertY = invertY;
  15868. texture._compression = compression;
  15869. }
  15870. if (texture.width % 4 !== 0) {
  15871. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  15872. }
  15873. if (compression && data) {
  15874. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  15875. }
  15876. else {
  15877. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  15878. }
  15879. if (texture.generateMipMaps) {
  15880. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15881. }
  15882. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15883. // this.resetTextureCache();
  15884. texture.isReady = true;
  15885. };
  15886. /**
  15887. * Creates a raw texture
  15888. * @param data defines the data to store in the texture
  15889. * @param width defines the width of the texture
  15890. * @param height defines the height of the texture
  15891. * @param format defines the format of the data
  15892. * @param generateMipMaps defines if the engine should generate the mip levels
  15893. * @param invertY defines if data must be stored with Y axis inverted
  15894. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  15895. * @param compression defines the compression used (null by default)
  15896. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15897. * @returns the raw texture inside an InternalTexture
  15898. */
  15899. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  15900. if (compression === void 0) { compression = null; }
  15901. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  15902. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  15903. texture.baseWidth = width;
  15904. texture.baseHeight = height;
  15905. texture.width = width;
  15906. texture.height = height;
  15907. texture.format = format;
  15908. texture.generateMipMaps = generateMipMaps;
  15909. texture.samplingMode = samplingMode;
  15910. texture.invertY = invertY;
  15911. texture._compression = compression;
  15912. texture.type = type;
  15913. if (!this._doNotHandleContextLost) {
  15914. texture._bufferView = data;
  15915. }
  15916. this.updateRawTexture(texture, data, format, invertY, compression, type);
  15917. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15918. // Filters
  15919. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  15920. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  15921. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15922. if (generateMipMaps) {
  15923. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15924. }
  15925. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15926. this._internalTexturesCache.push(texture);
  15927. return texture;
  15928. };
  15929. /** @hidden */
  15930. Engine.prototype._unpackFlipY = function (value) {
  15931. if (this._unpackFlipYCached !== value) {
  15932. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, value ? 1 : 0);
  15933. if (this.enableUnpackFlipYCached) {
  15934. this._unpackFlipYCached = value;
  15935. }
  15936. }
  15937. };
  15938. /** @hidden */
  15939. Engine.prototype._getUnpackAlignement = function () {
  15940. return this._gl.getParameter(this._gl.UNPACK_ALIGNMENT);
  15941. };
  15942. /**
  15943. * Creates a dynamic texture
  15944. * @param width defines the width of the texture
  15945. * @param height defines the height of the texture
  15946. * @param generateMipMaps defines if the engine should generate the mip levels
  15947. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  15948. * @returns the dynamic texture inside an InternalTexture
  15949. */
  15950. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  15951. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  15952. texture.baseWidth = width;
  15953. texture.baseHeight = height;
  15954. if (generateMipMaps) {
  15955. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  15956. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  15957. }
  15958. // this.resetTextureCache();
  15959. texture.width = width;
  15960. texture.height = height;
  15961. texture.isReady = false;
  15962. texture.generateMipMaps = generateMipMaps;
  15963. texture.samplingMode = samplingMode;
  15964. this.updateTextureSamplingMode(samplingMode, texture);
  15965. this._internalTexturesCache.push(texture);
  15966. return texture;
  15967. };
  15968. /**
  15969. * Update the sampling mode of a given texture
  15970. * @param samplingMode defines the required sampling mode
  15971. * @param texture defines the texture to update
  15972. */
  15973. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  15974. var filters = this._getSamplingParameters(samplingMode, texture.generateMipMaps);
  15975. if (texture.isCube) {
  15976. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  15977. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15978. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15979. }
  15980. else if (texture.is3D) {
  15981. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  15982. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15983. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15984. }
  15985. else {
  15986. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  15987. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15988. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15989. }
  15990. texture.samplingMode = samplingMode;
  15991. };
  15992. /**
  15993. * Update the content of a dynamic texture
  15994. * @param texture defines the texture to update
  15995. * @param canvas defines the canvas containing the source
  15996. * @param invertY defines if data must be stored with Y axis inverted
  15997. * @param premulAlpha defines if alpha is stored as premultiplied
  15998. * @param format defines the format of the data
  15999. * @param forceBindTexture if the texture should be forced to be bound eg. after a graphics context loss (Default: false)
  16000. */
  16001. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format, forceBindTexture) {
  16002. if (premulAlpha === void 0) { premulAlpha = false; }
  16003. if (forceBindTexture === void 0) { forceBindTexture = false; }
  16004. if (!texture) {
  16005. return;
  16006. }
  16007. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true, forceBindTexture);
  16008. this._unpackFlipY(invertY);
  16009. if (premulAlpha) {
  16010. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  16011. }
  16012. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  16013. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  16014. if (texture.generateMipMaps) {
  16015. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  16016. }
  16017. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16018. if (premulAlpha) {
  16019. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  16020. }
  16021. texture.isReady = true;
  16022. };
  16023. /**
  16024. * Update a video texture
  16025. * @param texture defines the texture to update
  16026. * @param video defines the video element to use
  16027. * @param invertY defines if data must be stored with Y axis inverted
  16028. */
  16029. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  16030. if (!texture || texture._isDisabled) {
  16031. return;
  16032. }
  16033. var wasPreviouslyBound = this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  16034. this._unpackFlipY(!invertY); // Video are upside down by default
  16035. try {
  16036. // Testing video texture support
  16037. if (this._videoTextureSupported === undefined) {
  16038. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  16039. if (this._gl.getError() !== 0) {
  16040. this._videoTextureSupported = false;
  16041. }
  16042. else {
  16043. this._videoTextureSupported = true;
  16044. }
  16045. }
  16046. // Copy video through the current working canvas if video texture is not supported
  16047. if (!this._videoTextureSupported) {
  16048. if (!texture._workingCanvas) {
  16049. texture._workingCanvas = document.createElement("canvas");
  16050. var context = texture._workingCanvas.getContext("2d");
  16051. if (!context) {
  16052. throw new Error("Unable to get 2d context");
  16053. }
  16054. texture._workingContext = context;
  16055. texture._workingCanvas.width = texture.width;
  16056. texture._workingCanvas.height = texture.height;
  16057. }
  16058. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  16059. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  16060. }
  16061. else {
  16062. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  16063. }
  16064. if (texture.generateMipMaps) {
  16065. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  16066. }
  16067. if (!wasPreviouslyBound) {
  16068. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16069. }
  16070. // this.resetTextureCache();
  16071. texture.isReady = true;
  16072. }
  16073. catch (ex) {
  16074. // Something unexpected
  16075. // Let's disable the texture
  16076. texture._isDisabled = true;
  16077. }
  16078. };
  16079. /**
  16080. * Updates a depth texture Comparison Mode and Function.
  16081. * If the comparison Function is equal to 0, the mode will be set to none.
  16082. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  16083. * @param texture The texture to set the comparison function for
  16084. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  16085. */
  16086. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  16087. if (this.webGLVersion === 1) {
  16088. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  16089. return;
  16090. }
  16091. var gl = this._gl;
  16092. if (texture.isCube) {
  16093. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  16094. if (comparisonFunction === 0) {
  16095. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  16096. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  16097. }
  16098. else {
  16099. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  16100. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  16101. }
  16102. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16103. }
  16104. else {
  16105. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  16106. if (comparisonFunction === 0) {
  16107. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  16108. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  16109. }
  16110. else {
  16111. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  16112. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  16113. }
  16114. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16115. }
  16116. texture._comparisonFunction = comparisonFunction;
  16117. };
  16118. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  16119. var width = size.width || size;
  16120. var height = size.height || size;
  16121. internalTexture.baseWidth = width;
  16122. internalTexture.baseHeight = height;
  16123. internalTexture.width = width;
  16124. internalTexture.height = height;
  16125. internalTexture.isReady = true;
  16126. internalTexture.samples = 1;
  16127. internalTexture.generateMipMaps = false;
  16128. internalTexture._generateDepthBuffer = true;
  16129. internalTexture._generateStencilBuffer = generateStencil;
  16130. internalTexture.samplingMode = bilinearFiltering ? Engine.TEXTURE_BILINEAR_SAMPLINGMODE : Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16131. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  16132. internalTexture._comparisonFunction = comparisonFunction;
  16133. var gl = this._gl;
  16134. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  16135. var samplingParameters = this._getSamplingParameters(internalTexture.samplingMode, false);
  16136. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  16137. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  16138. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16139. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16140. if (comparisonFunction === 0) {
  16141. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  16142. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  16143. }
  16144. else {
  16145. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  16146. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  16147. }
  16148. };
  16149. /**
  16150. * Creates a depth stencil texture.
  16151. * This is only available in WebGL 2 or with the depth texture extension available.
  16152. * @param size The size of face edge in the texture.
  16153. * @param options The options defining the texture.
  16154. * @returns The texture
  16155. */
  16156. Engine.prototype.createDepthStencilTexture = function (size, options) {
  16157. if (options.isCube) {
  16158. var width = size.width || size;
  16159. return this._createDepthStencilCubeTexture(width, options);
  16160. }
  16161. else {
  16162. return this._createDepthStencilTexture(size, options);
  16163. }
  16164. };
  16165. /**
  16166. * Creates a depth stencil texture.
  16167. * This is only available in WebGL 2 or with the depth texture extension available.
  16168. * @param size The size of face edge in the texture.
  16169. * @param options The options defining the texture.
  16170. * @returns The texture
  16171. */
  16172. Engine.prototype._createDepthStencilTexture = function (size, options) {
  16173. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  16174. if (!this._caps.depthTextureExtension) {
  16175. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  16176. return internalTexture;
  16177. }
  16178. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  16179. var gl = this._gl;
  16180. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  16181. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  16182. if (this.webGLVersion > 1) {
  16183. if (internalOptions.generateStencil) {
  16184. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  16185. }
  16186. else {
  16187. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  16188. }
  16189. }
  16190. else {
  16191. if (internalOptions.generateStencil) {
  16192. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  16193. }
  16194. else {
  16195. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  16196. }
  16197. }
  16198. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  16199. return internalTexture;
  16200. };
  16201. /**
  16202. * Creates a depth stencil cube texture.
  16203. * This is only available in WebGL 2.
  16204. * @param size The size of face edge in the cube texture.
  16205. * @param options The options defining the cube texture.
  16206. * @returns The cube texture
  16207. */
  16208. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  16209. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  16210. internalTexture.isCube = true;
  16211. if (this.webGLVersion === 1) {
  16212. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  16213. return internalTexture;
  16214. }
  16215. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  16216. var gl = this._gl;
  16217. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  16218. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  16219. // Create the depth/stencil buffer
  16220. for (var face = 0; face < 6; face++) {
  16221. if (internalOptions.generateStencil) {
  16222. 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);
  16223. }
  16224. else {
  16225. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  16226. }
  16227. }
  16228. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16229. return internalTexture;
  16230. };
  16231. /**
  16232. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  16233. * @param renderTarget The render target to set the frame buffer for
  16234. */
  16235. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  16236. // Create the framebuffer
  16237. var internalTexture = renderTarget.getInternalTexture();
  16238. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  16239. return;
  16240. }
  16241. var gl = this._gl;
  16242. var depthStencilTexture = renderTarget.depthStencilTexture;
  16243. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  16244. if (depthStencilTexture.isCube) {
  16245. if (depthStencilTexture._generateStencilBuffer) {
  16246. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  16247. }
  16248. else {
  16249. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  16250. }
  16251. }
  16252. else {
  16253. if (depthStencilTexture._generateStencilBuffer) {
  16254. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  16255. }
  16256. else {
  16257. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  16258. }
  16259. }
  16260. this.bindUnboundFramebuffer(null);
  16261. };
  16262. /**
  16263. * Creates a new render target texture
  16264. * @param size defines the size of the texture
  16265. * @param options defines the options used to create the texture
  16266. * @returns a new render target texture stored in an InternalTexture
  16267. */
  16268. Engine.prototype.createRenderTargetTexture = function (size, options) {
  16269. var fullOptions = new RenderTargetCreationOptions();
  16270. if (options !== undefined && typeof options === "object") {
  16271. fullOptions.generateMipMaps = options.generateMipMaps;
  16272. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  16273. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  16274. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  16275. fullOptions.samplingMode = options.samplingMode === undefined ? Engine.TEXTURE_TRILINEAR_SAMPLINGMODE : options.samplingMode;
  16276. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  16277. }
  16278. else {
  16279. fullOptions.generateMipMaps = options;
  16280. fullOptions.generateDepthBuffer = true;
  16281. fullOptions.generateStencilBuffer = false;
  16282. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  16283. fullOptions.samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  16284. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  16285. }
  16286. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  16287. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  16288. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16289. }
  16290. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  16291. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  16292. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16293. }
  16294. var gl = this._gl;
  16295. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  16296. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  16297. var width = size.width || size;
  16298. var height = size.height || size;
  16299. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false);
  16300. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  16301. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  16302. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  16303. }
  16304. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  16305. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  16306. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16307. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16308. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  16309. // Create the framebuffer
  16310. var currentFrameBuffer = this._currentFramebuffer;
  16311. var framebuffer = gl.createFramebuffer();
  16312. this.bindUnboundFramebuffer(framebuffer);
  16313. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  16314. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  16315. if (fullOptions.generateMipMaps) {
  16316. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  16317. }
  16318. // Unbind
  16319. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  16320. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  16321. this.bindUnboundFramebuffer(currentFrameBuffer);
  16322. texture._framebuffer = framebuffer;
  16323. texture.baseWidth = width;
  16324. texture.baseHeight = height;
  16325. texture.width = width;
  16326. texture.height = height;
  16327. texture.isReady = true;
  16328. texture.samples = 1;
  16329. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  16330. texture.samplingMode = fullOptions.samplingMode;
  16331. texture.type = fullOptions.type;
  16332. texture.format = fullOptions.format;
  16333. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  16334. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  16335. // this.resetTextureCache();
  16336. this._internalTexturesCache.push(texture);
  16337. return texture;
  16338. };
  16339. /**
  16340. * Create a multi render target texture
  16341. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  16342. * @param size defines the size of the texture
  16343. * @param options defines the creation options
  16344. * @returns the cube texture as an InternalTexture
  16345. */
  16346. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  16347. var generateMipMaps = false;
  16348. var generateDepthBuffer = true;
  16349. var generateStencilBuffer = false;
  16350. var generateDepthTexture = false;
  16351. var textureCount = 1;
  16352. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  16353. var defaultSamplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  16354. var types = new Array();
  16355. var samplingModes = new Array();
  16356. if (options !== undefined) {
  16357. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  16358. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  16359. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  16360. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  16361. textureCount = options.textureCount || 1;
  16362. if (options.types) {
  16363. types = options.types;
  16364. }
  16365. if (options.samplingModes) {
  16366. samplingModes = options.samplingModes;
  16367. }
  16368. }
  16369. var gl = this._gl;
  16370. // Create the framebuffer
  16371. var framebuffer = gl.createFramebuffer();
  16372. this.bindUnboundFramebuffer(framebuffer);
  16373. var width = size.width || size;
  16374. var height = size.height || size;
  16375. var textures = [];
  16376. var attachments = [];
  16377. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  16378. for (var i = 0; i < textureCount; i++) {
  16379. var samplingMode = samplingModes[i] || defaultSamplingMode;
  16380. var type = types[i] || defaultType;
  16381. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  16382. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  16383. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16384. }
  16385. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  16386. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  16387. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16388. }
  16389. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  16390. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  16391. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  16392. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  16393. }
  16394. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  16395. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  16396. textures.push(texture);
  16397. attachments.push(attachment);
  16398. gl.activeTexture(gl["TEXTURE" + i]);
  16399. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  16400. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  16401. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  16402. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16403. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16404. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  16405. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  16406. if (generateMipMaps) {
  16407. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  16408. }
  16409. // Unbind
  16410. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  16411. texture._framebuffer = framebuffer;
  16412. texture._depthStencilBuffer = depthStencilBuffer;
  16413. texture.baseWidth = width;
  16414. texture.baseHeight = height;
  16415. texture.width = width;
  16416. texture.height = height;
  16417. texture.isReady = true;
  16418. texture.samples = 1;
  16419. texture.generateMipMaps = generateMipMaps;
  16420. texture.samplingMode = samplingMode;
  16421. texture.type = type;
  16422. texture._generateDepthBuffer = generateDepthBuffer;
  16423. texture._generateStencilBuffer = generateStencilBuffer;
  16424. texture._attachments = attachments;
  16425. this._internalTexturesCache.push(texture);
  16426. }
  16427. if (generateDepthTexture && this._caps.depthTextureExtension) {
  16428. // Depth texture
  16429. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  16430. gl.activeTexture(gl.TEXTURE0);
  16431. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  16432. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  16433. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  16434. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16435. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16436. 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);
  16437. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  16438. depthTexture._framebuffer = framebuffer;
  16439. depthTexture.baseWidth = width;
  16440. depthTexture.baseHeight = height;
  16441. depthTexture.width = width;
  16442. depthTexture.height = height;
  16443. depthTexture.isReady = true;
  16444. depthTexture.samples = 1;
  16445. depthTexture.generateMipMaps = generateMipMaps;
  16446. depthTexture.samplingMode = gl.NEAREST;
  16447. depthTexture._generateDepthBuffer = generateDepthBuffer;
  16448. depthTexture._generateStencilBuffer = generateStencilBuffer;
  16449. textures.push(depthTexture);
  16450. this._internalTexturesCache.push(depthTexture);
  16451. }
  16452. gl.drawBuffers(attachments);
  16453. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  16454. this.bindUnboundFramebuffer(null);
  16455. this.resetTextureCache();
  16456. return textures;
  16457. };
  16458. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  16459. if (samples === void 0) { samples = 1; }
  16460. var depthStencilBuffer = null;
  16461. var gl = this._gl;
  16462. // Create the depth/stencil buffer
  16463. if (generateStencilBuffer) {
  16464. depthStencilBuffer = gl.createRenderbuffer();
  16465. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  16466. if (samples > 1) {
  16467. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  16468. }
  16469. else {
  16470. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  16471. }
  16472. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  16473. }
  16474. else if (generateDepthBuffer) {
  16475. depthStencilBuffer = gl.createRenderbuffer();
  16476. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  16477. if (samples > 1) {
  16478. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  16479. }
  16480. else {
  16481. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  16482. }
  16483. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  16484. }
  16485. return depthStencilBuffer;
  16486. };
  16487. /**
  16488. * Updates the sample count of a render target texture
  16489. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  16490. * @param texture defines the texture to update
  16491. * @param samples defines the sample count to set
  16492. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  16493. */
  16494. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  16495. if (this.webGLVersion < 2 || !texture) {
  16496. return 1;
  16497. }
  16498. if (texture.samples === samples) {
  16499. return samples;
  16500. }
  16501. var gl = this._gl;
  16502. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  16503. // Dispose previous render buffers
  16504. if (texture._depthStencilBuffer) {
  16505. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  16506. texture._depthStencilBuffer = null;
  16507. }
  16508. if (texture._MSAAFramebuffer) {
  16509. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  16510. texture._MSAAFramebuffer = null;
  16511. }
  16512. if (texture._MSAARenderBuffer) {
  16513. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  16514. texture._MSAARenderBuffer = null;
  16515. }
  16516. if (samples > 1) {
  16517. var framebuffer = gl.createFramebuffer();
  16518. if (!framebuffer) {
  16519. throw new Error("Unable to create multi sampled framebuffer");
  16520. }
  16521. texture._MSAAFramebuffer = framebuffer;
  16522. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  16523. var colorRenderbuffer = gl.createRenderbuffer();
  16524. if (!colorRenderbuffer) {
  16525. throw new Error("Unable to create multi sampled framebuffer");
  16526. }
  16527. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  16528. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  16529. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  16530. texture._MSAARenderBuffer = colorRenderbuffer;
  16531. }
  16532. else {
  16533. this.bindUnboundFramebuffer(texture._framebuffer);
  16534. }
  16535. texture.samples = samples;
  16536. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  16537. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  16538. this.bindUnboundFramebuffer(null);
  16539. return samples;
  16540. };
  16541. /**
  16542. * Update the sample count for a given multiple render target texture
  16543. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  16544. * @param textures defines the textures to update
  16545. * @param samples defines the sample count to set
  16546. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  16547. */
  16548. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  16549. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  16550. return 1;
  16551. }
  16552. if (textures[0].samples === samples) {
  16553. return samples;
  16554. }
  16555. var gl = this._gl;
  16556. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  16557. // Dispose previous render buffers
  16558. if (textures[0]._depthStencilBuffer) {
  16559. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  16560. textures[0]._depthStencilBuffer = null;
  16561. }
  16562. if (textures[0]._MSAAFramebuffer) {
  16563. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  16564. textures[0]._MSAAFramebuffer = null;
  16565. }
  16566. for (var i = 0; i < textures.length; i++) {
  16567. if (textures[i]._MSAARenderBuffer) {
  16568. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  16569. textures[i]._MSAARenderBuffer = null;
  16570. }
  16571. }
  16572. if (samples > 1) {
  16573. var framebuffer = gl.createFramebuffer();
  16574. if (!framebuffer) {
  16575. throw new Error("Unable to create multi sampled framebuffer");
  16576. }
  16577. this.bindUnboundFramebuffer(framebuffer);
  16578. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  16579. var attachments = [];
  16580. for (var i = 0; i < textures.length; i++) {
  16581. var texture = textures[i];
  16582. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  16583. var colorRenderbuffer = gl.createRenderbuffer();
  16584. if (!colorRenderbuffer) {
  16585. throw new Error("Unable to create multi sampled framebuffer");
  16586. }
  16587. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  16588. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  16589. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  16590. texture._MSAAFramebuffer = framebuffer;
  16591. texture._MSAARenderBuffer = colorRenderbuffer;
  16592. texture.samples = samples;
  16593. texture._depthStencilBuffer = depthStencilBuffer;
  16594. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  16595. attachments.push(attachment);
  16596. }
  16597. gl.drawBuffers(attachments);
  16598. }
  16599. else {
  16600. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  16601. }
  16602. this.bindUnboundFramebuffer(null);
  16603. return samples;
  16604. };
  16605. /** @hidden */
  16606. Engine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
  16607. if (faceIndex === void 0) { faceIndex = 0; }
  16608. if (lod === void 0) { lod = 0; }
  16609. var gl = this._gl;
  16610. var target = gl.TEXTURE_2D;
  16611. if (texture.isCube) {
  16612. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  16613. }
  16614. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  16615. };
  16616. /** @hidden */
  16617. Engine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {
  16618. if (faceIndex === void 0) { faceIndex = 0; }
  16619. if (lod === void 0) { lod = 0; }
  16620. var gl = this._gl;
  16621. var textureType = this._getWebGLTextureType(texture.type);
  16622. var format = this._getInternalFormat(texture.format);
  16623. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  16624. this._unpackFlipY(texture.invertY);
  16625. var target = gl.TEXTURE_2D;
  16626. if (texture.isCube) {
  16627. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  16628. }
  16629. var lodMaxWidth = Math.round(BABYLON.Scalar.Log2(texture.width));
  16630. var lodMaxHeight = Math.round(BABYLON.Scalar.Log2(texture.height));
  16631. var width = Math.pow(2, Math.max(lodMaxWidth - lod, 0));
  16632. var height = Math.pow(2, Math.max(lodMaxHeight - lod, 0));
  16633. gl.texImage2D(target, lod, internalFormat, width, height, 0, format, textureType, imageData);
  16634. };
  16635. /** @hidden */
  16636. Engine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
  16637. if (faceIndex === void 0) { faceIndex = 0; }
  16638. if (lod === void 0) { lod = 0; }
  16639. var gl = this._gl;
  16640. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  16641. this._bindTextureDirectly(bindTarget, texture, true);
  16642. this._uploadDataToTextureDirectly(texture, imageData, faceIndex, lod);
  16643. this._bindTextureDirectly(bindTarget, null, true);
  16644. };
  16645. /** @hidden */
  16646. Engine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
  16647. if (faceIndex === void 0) { faceIndex = 0; }
  16648. if (lod === void 0) { lod = 0; }
  16649. var gl = this._gl;
  16650. var textureType = this._getWebGLTextureType(texture.type);
  16651. var format = this._getInternalFormat(texture.format);
  16652. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  16653. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  16654. this._bindTextureDirectly(bindTarget, texture, true);
  16655. this._unpackFlipY(texture.invertY);
  16656. var target = gl.TEXTURE_2D;
  16657. if (texture.isCube) {
  16658. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  16659. }
  16660. gl.texImage2D(target, lod, internalFormat, format, textureType, image);
  16661. this._bindTextureDirectly(bindTarget, null, true);
  16662. };
  16663. /**
  16664. * Creates a new render target cube texture
  16665. * @param size defines the size of the texture
  16666. * @param options defines the options used to create the texture
  16667. * @returns a new render target cube texture stored in an InternalTexture
  16668. */
  16669. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  16670. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: Engine.TEXTURE_TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  16671. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  16672. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  16673. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  16674. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16675. }
  16676. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  16677. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  16678. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16679. }
  16680. var gl = this._gl;
  16681. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  16682. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16683. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps);
  16684. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  16685. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  16686. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  16687. }
  16688. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  16689. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  16690. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16691. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16692. for (var face = 0; face < 6; face++) {
  16693. 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);
  16694. }
  16695. // Create the framebuffer
  16696. var framebuffer = gl.createFramebuffer();
  16697. this.bindUnboundFramebuffer(framebuffer);
  16698. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  16699. // MipMaps
  16700. if (fullOptions.generateMipMaps) {
  16701. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  16702. }
  16703. // Unbind
  16704. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16705. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  16706. this.bindUnboundFramebuffer(null);
  16707. texture._framebuffer = framebuffer;
  16708. texture.width = size;
  16709. texture.height = size;
  16710. texture.isReady = true;
  16711. texture.isCube = true;
  16712. texture.samples = 1;
  16713. texture.generateMipMaps = fullOptions.generateMipMaps;
  16714. texture.samplingMode = fullOptions.samplingMode;
  16715. texture.type = fullOptions.type;
  16716. texture.format = fullOptions.format;
  16717. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  16718. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  16719. this._internalTexturesCache.push(texture);
  16720. return texture;
  16721. };
  16722. /**
  16723. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  16724. * @param rootUrl defines the url where the file to load is located
  16725. * @param scene defines the current scene
  16726. * @param lodScale defines scale to apply to the mip map selection
  16727. * @param lodOffset defines offset to apply to the mip map selection
  16728. * @param onLoad defines an optional callback raised when the texture is loaded
  16729. * @param onError defines an optional callback raised if there is an issue to load the texture
  16730. * @param format defines the format of the data
  16731. * @param forcedExtension defines the extension to use to pick the right loader
  16732. * @param createPolynomials defines wheter or not to create polynomails harmonics for the texture
  16733. * @returns the cube texture as an InternalTexture
  16734. */
  16735. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, createPolynomials) {
  16736. var _this = this;
  16737. if (onLoad === void 0) { onLoad = null; }
  16738. if (onError === void 0) { onError = null; }
  16739. if (forcedExtension === void 0) { forcedExtension = null; }
  16740. if (createPolynomials === void 0) { createPolynomials = true; }
  16741. var callback = function (loadData) {
  16742. if (!loadData) {
  16743. if (onLoad) {
  16744. onLoad(null);
  16745. }
  16746. return;
  16747. }
  16748. var texture = loadData.texture;
  16749. if (!createPolynomials) {
  16750. texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();
  16751. }
  16752. else if (loadData.info.sphericalPolynomial) {
  16753. texture._sphericalPolynomial = loadData.info.sphericalPolynomial;
  16754. }
  16755. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  16756. if (_this._caps.textureLOD) {
  16757. // Do not add extra process if texture lod is supported.
  16758. if (onLoad) {
  16759. onLoad(texture);
  16760. }
  16761. return;
  16762. }
  16763. var mipSlices = 3;
  16764. var gl = _this._gl;
  16765. var width = loadData.width;
  16766. if (!width) {
  16767. return;
  16768. }
  16769. var textures = [];
  16770. for (var i = 0; i < mipSlices; i++) {
  16771. //compute LOD from even spacing in smoothness (matching shader calculation)
  16772. var smoothness = i / (mipSlices - 1);
  16773. var roughness = 1 - smoothness;
  16774. var minLODIndex = lodOffset; // roughness = 0
  16775. var maxLODIndex = BABYLON.Scalar.Log2(width) * lodScale + lodOffset; // roughness = 1
  16776. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  16777. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  16778. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  16779. glTextureFromLod.type = texture.type;
  16780. glTextureFromLod.format = texture.format;
  16781. glTextureFromLod.width = Math.pow(2, Math.max(BABYLON.Scalar.Log2(width) - mipmapIndex, 0));
  16782. glTextureFromLod.height = glTextureFromLod.width;
  16783. glTextureFromLod.isCube = true;
  16784. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  16785. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  16786. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  16787. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16788. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16789. if (loadData.isDDS) {
  16790. var info = loadData.info;
  16791. var data = loadData.data;
  16792. _this._unpackFlipY(info.isCompressed);
  16793. BABYLON.DDSTools.UploadDDSLevels(_this, glTextureFromLod, data, info, true, 6, mipmapIndex);
  16794. }
  16795. else {
  16796. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  16797. }
  16798. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16799. // Wrap in a base texture for easy binding.
  16800. var lodTexture = new BABYLON.BaseTexture(scene);
  16801. lodTexture.isCube = true;
  16802. lodTexture._texture = glTextureFromLod;
  16803. glTextureFromLod.isReady = true;
  16804. textures.push(lodTexture);
  16805. }
  16806. texture._lodTextureHigh = textures[2];
  16807. texture._lodTextureMid = textures[1];
  16808. texture._lodTextureLow = textures[0];
  16809. if (onLoad) {
  16810. onLoad(texture);
  16811. }
  16812. };
  16813. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset);
  16814. };
  16815. /**
  16816. * Creates a cube texture
  16817. * @param rootUrl defines the url where the files to load is located
  16818. * @param scene defines the current scene
  16819. * @param files defines the list of files to load (1 per face)
  16820. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  16821. * @param onLoad defines an optional callback raised when the texture is loaded
  16822. * @param onError defines an optional callback raised if there is an issue to load the texture
  16823. * @param format defines the format of the data
  16824. * @param forcedExtension defines the extension to use to pick the right loader
  16825. * @param createPolynomials if a polynomial sphere should be created for the cube texture
  16826. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  16827. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  16828. * @param fallback defines texture to use while falling back when (compressed) texture file not found.
  16829. * @returns the cube texture as an InternalTexture
  16830. */
  16831. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset, fallback) {
  16832. var _this = this;
  16833. if (onLoad === void 0) { onLoad = null; }
  16834. if (onError === void 0) { onError = null; }
  16835. if (forcedExtension === void 0) { forcedExtension = null; }
  16836. if (createPolynomials === void 0) { createPolynomials = false; }
  16837. if (lodScale === void 0) { lodScale = 0; }
  16838. if (lodOffset === void 0) { lodOffset = 0; }
  16839. if (fallback === void 0) { fallback = null; }
  16840. var gl = this._gl;
  16841. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  16842. texture.isCube = true;
  16843. texture.url = rootUrl;
  16844. texture.generateMipMaps = !noMipmap;
  16845. texture._lodGenerationScale = lodScale;
  16846. texture._lodGenerationOffset = lodOffset;
  16847. if (!this._doNotHandleContextLost) {
  16848. texture._extension = forcedExtension;
  16849. texture._files = files;
  16850. }
  16851. var lastDot = rootUrl.lastIndexOf('.');
  16852. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  16853. var loader = null;
  16854. for (var _i = 0, _a = Engine._TextureLoaders; _i < _a.length; _i++) {
  16855. var availableLoader = _a[_i];
  16856. if (availableLoader.canLoad(extension, this._textureFormatInUse, fallback, false, false)) {
  16857. loader = availableLoader;
  16858. break;
  16859. }
  16860. }
  16861. var onInternalError = function (request, exception) {
  16862. if (loader) {
  16863. var fallbackUrl = loader.getFallbackTextureUrl(rootUrl, _this._textureFormatInUse);
  16864. if (fallbackUrl) {
  16865. _this.createCubeTexture(fallbackUrl, scene, files, noMipmap, onLoad, onError, format, extension, createPolynomials, lodScale, lodOffset, texture);
  16866. }
  16867. }
  16868. if (onError && request) {
  16869. onError(request.status + " " + request.statusText, exception);
  16870. }
  16871. };
  16872. if (loader) {
  16873. rootUrl = loader.transformUrl(rootUrl, this._textureFormatInUse);
  16874. var onloaddata = function (data) {
  16875. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16876. loader.loadCubeData(data, texture, createPolynomials, onLoad, onError);
  16877. };
  16878. if (files && files.length === 6) {
  16879. if (loader.supportCascades) {
  16880. this._cascadeLoadFiles(scene, onloaddata, files, onError);
  16881. }
  16882. else if (onError) {
  16883. onError("Textures type does not support cascades.");
  16884. }
  16885. }
  16886. else {
  16887. this._loadFile(rootUrl, onloaddata, undefined, undefined, true, onInternalError);
  16888. }
  16889. }
  16890. else {
  16891. if (!files) {
  16892. throw new Error("Cannot load cubemap because files were not defined");
  16893. }
  16894. this._cascadeLoadImgs(rootUrl, scene, function (imgs) {
  16895. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  16896. var height = width;
  16897. _this._prepareWorkingCanvas();
  16898. if (!_this._workingCanvas || !_this._workingContext) {
  16899. return;
  16900. }
  16901. _this._workingCanvas.width = width;
  16902. _this._workingCanvas.height = height;
  16903. var faces = [
  16904. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  16905. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  16906. ];
  16907. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16908. _this._unpackFlipY(false);
  16909. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  16910. for (var index = 0; index < faces.length; index++) {
  16911. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  16912. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  16913. }
  16914. if (!noMipmap) {
  16915. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  16916. }
  16917. _this._setCubeMapTextureParams(!noMipmap);
  16918. texture.width = width;
  16919. texture.height = height;
  16920. texture.isReady = true;
  16921. if (format) {
  16922. texture.format = format;
  16923. }
  16924. texture.onLoadedObservable.notifyObservers(texture);
  16925. texture.onLoadedObservable.clear();
  16926. if (onLoad) {
  16927. onLoad();
  16928. }
  16929. }, files, onError);
  16930. }
  16931. this._internalTexturesCache.push(texture);
  16932. return texture;
  16933. };
  16934. /**
  16935. * @hidden
  16936. */
  16937. Engine.prototype._setCubeMapTextureParams = function (loadMipmap) {
  16938. var gl = this._gl;
  16939. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  16940. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  16941. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16942. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16943. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16944. // this.resetTextureCache();
  16945. };
  16946. /**
  16947. * Update a raw cube texture
  16948. * @param texture defines the texture to udpdate
  16949. * @param data defines the data to store
  16950. * @param format defines the data format
  16951. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  16952. * @param invertY defines if data must be stored with Y axis inverted
  16953. * @param compression defines the compression used (null by default)
  16954. * @param level defines which level of the texture to update
  16955. */
  16956. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  16957. if (compression === void 0) { compression = null; }
  16958. if (level === void 0) { level = 0; }
  16959. texture._bufferViewArray = data;
  16960. texture.format = format;
  16961. texture.type = type;
  16962. texture.invertY = invertY;
  16963. texture._compression = compression;
  16964. var gl = this._gl;
  16965. var textureType = this._getWebGLTextureType(type);
  16966. var internalFormat = this._getInternalFormat(format);
  16967. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  16968. var needConversion = false;
  16969. if (internalFormat === gl.RGB) {
  16970. internalFormat = gl.RGBA;
  16971. needConversion = true;
  16972. }
  16973. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16974. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16975. if (texture.width % 4 !== 0) {
  16976. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  16977. }
  16978. // Data are known to be in +X +Y +Z -X -Y -Z
  16979. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  16980. var faceData = data[faceIndex];
  16981. if (compression) {
  16982. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  16983. }
  16984. else {
  16985. if (needConversion) {
  16986. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  16987. }
  16988. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  16989. }
  16990. }
  16991. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  16992. if (isPot && texture.generateMipMaps && level === 0) {
  16993. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  16994. }
  16995. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16996. // this.resetTextureCache();
  16997. texture.isReady = true;
  16998. };
  16999. /**
  17000. * Creates a new raw cube texture
  17001. * @param data defines the array of data to use to create each face
  17002. * @param size defines the size of the textures
  17003. * @param format defines the format of the data
  17004. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  17005. * @param generateMipMaps defines if the engine should generate the mip levels
  17006. * @param invertY defines if data must be stored with Y axis inverted
  17007. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  17008. * @param compression defines the compression used (null by default)
  17009. * @returns the cube texture as an InternalTexture
  17010. */
  17011. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  17012. if (compression === void 0) { compression = null; }
  17013. var gl = this._gl;
  17014. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  17015. texture.isCube = true;
  17016. texture.format = format;
  17017. texture.type = type;
  17018. if (!this._doNotHandleContextLost) {
  17019. texture._bufferViewArray = data;
  17020. }
  17021. var textureType = this._getWebGLTextureType(type);
  17022. var internalFormat = this._getInternalFormat(format);
  17023. if (internalFormat === gl.RGB) {
  17024. internalFormat = gl.RGBA;
  17025. }
  17026. // Mipmap generation needs a sized internal format that is both color-renderable and texture-filterable
  17027. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  17028. generateMipMaps = false;
  17029. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  17030. BABYLON.Tools.Warn("Float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
  17031. }
  17032. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  17033. generateMipMaps = false;
  17034. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  17035. BABYLON.Tools.Warn("Half float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
  17036. }
  17037. else if (textureType === gl.FLOAT && !this._caps.textureFloatRender) {
  17038. generateMipMaps = false;
  17039. BABYLON.Tools.Warn("Render to float textures is not supported. Mipmap generation forced to false.");
  17040. }
  17041. else if (textureType === gl.HALF_FLOAT && !this._caps.colorBufferFloat) {
  17042. generateMipMaps = false;
  17043. BABYLON.Tools.Warn("Render to half float textures is not supported. Mipmap generation forced to false.");
  17044. }
  17045. var width = size;
  17046. var height = width;
  17047. texture.width = width;
  17048. texture.height = height;
  17049. // Double check on POT to generate Mips.
  17050. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  17051. if (!isPot) {
  17052. generateMipMaps = false;
  17053. }
  17054. // Upload data if needed. The texture won't be ready until then.
  17055. if (data) {
  17056. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  17057. }
  17058. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  17059. // Filters
  17060. if (data && generateMipMaps) {
  17061. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  17062. }
  17063. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  17064. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  17065. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  17066. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  17067. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  17068. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  17069. texture.generateMipMaps = generateMipMaps;
  17070. return texture;
  17071. };
  17072. /**
  17073. * Creates a new raw cube texture from a specified url
  17074. * @param url defines the url where the data is located
  17075. * @param scene defines the current scene
  17076. * @param size defines the size of the textures
  17077. * @param format defines the format of the data
  17078. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  17079. * @param noMipmap defines if the engine should avoid generating the mip levels
  17080. * @param callback defines a callback used to extract texture data from loaded data
  17081. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  17082. * @param onLoad defines a callback called when texture is loaded
  17083. * @param onError defines a callback called if there is an error
  17084. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  17085. * @param invertY defines if data must be stored with Y axis inverted
  17086. * @returns the cube texture as an InternalTexture
  17087. */
  17088. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  17089. var _this = this;
  17090. if (onLoad === void 0) { onLoad = null; }
  17091. if (onError === void 0) { onError = null; }
  17092. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  17093. if (invertY === void 0) { invertY = false; }
  17094. var gl = this._gl;
  17095. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  17096. scene._addPendingData(texture);
  17097. texture.url = url;
  17098. this._internalTexturesCache.push(texture);
  17099. var onerror = function (request, exception) {
  17100. scene._removePendingData(texture);
  17101. if (onError && request) {
  17102. onError(request.status + " " + request.statusText, exception);
  17103. }
  17104. };
  17105. var internalCallback = function (data) {
  17106. var width = texture.width;
  17107. var faceDataArrays = callback(data);
  17108. if (!faceDataArrays) {
  17109. return;
  17110. }
  17111. if (mipmapGenerator) {
  17112. var textureType = _this._getWebGLTextureType(type);
  17113. var internalFormat = _this._getInternalFormat(format);
  17114. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  17115. var needConversion = false;
  17116. if (internalFormat === gl.RGB) {
  17117. internalFormat = gl.RGBA;
  17118. needConversion = true;
  17119. }
  17120. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  17121. _this._unpackFlipY(false);
  17122. var mipData = mipmapGenerator(faceDataArrays);
  17123. for (var level = 0; level < mipData.length; level++) {
  17124. var mipSize = width >> level;
  17125. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  17126. var mipFaceData = mipData[level][faceIndex];
  17127. if (needConversion) {
  17128. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  17129. }
  17130. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  17131. }
  17132. }
  17133. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  17134. }
  17135. else {
  17136. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  17137. }
  17138. texture.isReady = true;
  17139. // this.resetTextureCache();
  17140. scene._removePendingData(texture);
  17141. if (onLoad) {
  17142. onLoad();
  17143. }
  17144. };
  17145. this._loadFile(url, function (data) {
  17146. internalCallback(data);
  17147. }, undefined, scene.offlineProvider, true, onerror);
  17148. return texture;
  17149. };
  17150. /**
  17151. * Update a raw 3D texture
  17152. * @param texture defines the texture to update
  17153. * @param data defines the data to store
  17154. * @param format defines the data format
  17155. * @param invertY defines if data must be stored with Y axis inverted
  17156. * @param compression defines the used compression (can be null)
  17157. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  17158. */
  17159. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression, textureType) {
  17160. if (compression === void 0) { compression = null; }
  17161. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  17162. var internalType = this._getWebGLTextureType(textureType);
  17163. var internalFormat = this._getInternalFormat(format);
  17164. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(textureType, format);
  17165. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  17166. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  17167. if (!this._doNotHandleContextLost) {
  17168. texture._bufferView = data;
  17169. texture.format = format;
  17170. texture.invertY = invertY;
  17171. texture._compression = compression;
  17172. }
  17173. if (texture.width % 4 !== 0) {
  17174. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  17175. }
  17176. if (compression && data) {
  17177. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  17178. }
  17179. else {
  17180. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalSizedFomat, texture.width, texture.height, texture.depth, 0, internalFormat, internalType, data);
  17181. }
  17182. if (texture.generateMipMaps) {
  17183. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  17184. }
  17185. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  17186. // this.resetTextureCache();
  17187. texture.isReady = true;
  17188. };
  17189. /**
  17190. * Creates a new raw 3D texture
  17191. * @param data defines the data used to create the texture
  17192. * @param width defines the width of the texture
  17193. * @param height defines the height of the texture
  17194. * @param depth defines the depth of the texture
  17195. * @param format defines the format of the texture
  17196. * @param generateMipMaps defines if the engine must generate mip levels
  17197. * @param invertY defines if data must be stored with Y axis inverted
  17198. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  17199. * @param compression defines the compressed used (can be null)
  17200. * @param textureType defines the compressed used (can be null)
  17201. * @returns a new raw 3D texture (stored in an InternalTexture)
  17202. */
  17203. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression, textureType) {
  17204. if (compression === void 0) { compression = null; }
  17205. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  17206. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  17207. texture.baseWidth = width;
  17208. texture.baseHeight = height;
  17209. texture.baseDepth = depth;
  17210. texture.width = width;
  17211. texture.height = height;
  17212. texture.depth = depth;
  17213. texture.format = format;
  17214. texture.type = textureType;
  17215. texture.generateMipMaps = generateMipMaps;
  17216. texture.samplingMode = samplingMode;
  17217. texture.is3D = true;
  17218. if (!this._doNotHandleContextLost) {
  17219. texture._bufferView = data;
  17220. }
  17221. this.updateRawTexture3D(texture, data, format, invertY, compression, textureType);
  17222. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  17223. // Filters
  17224. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  17225. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  17226. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  17227. if (generateMipMaps) {
  17228. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  17229. }
  17230. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  17231. this._internalTexturesCache.push(texture);
  17232. return texture;
  17233. };
  17234. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  17235. var gl = this._gl;
  17236. if (!gl) {
  17237. return;
  17238. }
  17239. var filters = this._getSamplingParameters(samplingMode, !noMipmap);
  17240. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  17241. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  17242. if (!noMipmap && !isCompressed) {
  17243. gl.generateMipmap(gl.TEXTURE_2D);
  17244. }
  17245. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  17246. // this.resetTextureCache();
  17247. if (scene) {
  17248. scene._removePendingData(texture);
  17249. }
  17250. texture.onLoadedObservable.notifyObservers(texture);
  17251. texture.onLoadedObservable.clear();
  17252. };
  17253. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  17254. var _this = this;
  17255. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  17256. var maxTextureSize = this.getCaps().maxTextureSize;
  17257. var potWidth = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, maxTextureSize) : width);
  17258. var potHeight = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, maxTextureSize) : height);
  17259. var gl = this._gl;
  17260. if (!gl) {
  17261. return;
  17262. }
  17263. if (!texture._webGLTexture) {
  17264. // this.resetTextureCache();
  17265. if (scene) {
  17266. scene._removePendingData(texture);
  17267. }
  17268. return;
  17269. }
  17270. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  17271. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  17272. texture.baseWidth = width;
  17273. texture.baseHeight = height;
  17274. texture.width = potWidth;
  17275. texture.height = potHeight;
  17276. texture.isReady = true;
  17277. if (processFunction(potWidth, potHeight, function () {
  17278. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  17279. })) {
  17280. // Returning as texture needs extra async steps
  17281. return;
  17282. }
  17283. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  17284. };
  17285. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  17286. // Create new RGBA data container.
  17287. var rgbaData;
  17288. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  17289. rgbaData = new Float32Array(width * height * 4);
  17290. }
  17291. else {
  17292. rgbaData = new Uint32Array(width * height * 4);
  17293. }
  17294. // Convert each pixel.
  17295. for (var x = 0; x < width; x++) {
  17296. for (var y = 0; y < height; y++) {
  17297. var index = (y * width + x) * 3;
  17298. var newIndex = (y * width + x) * 4;
  17299. // Map Old Value to new value.
  17300. rgbaData[newIndex + 0] = rgbData[index + 0];
  17301. rgbaData[newIndex + 1] = rgbData[index + 1];
  17302. rgbaData[newIndex + 2] = rgbData[index + 2];
  17303. // Add fully opaque alpha channel.
  17304. rgbaData[newIndex + 3] = 1;
  17305. }
  17306. }
  17307. return rgbaData;
  17308. };
  17309. /** @hidden */
  17310. Engine.prototype._releaseFramebufferObjects = function (texture) {
  17311. var gl = this._gl;
  17312. if (texture._framebuffer) {
  17313. gl.deleteFramebuffer(texture._framebuffer);
  17314. texture._framebuffer = null;
  17315. }
  17316. if (texture._depthStencilBuffer) {
  17317. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  17318. texture._depthStencilBuffer = null;
  17319. }
  17320. if (texture._MSAAFramebuffer) {
  17321. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  17322. texture._MSAAFramebuffer = null;
  17323. }
  17324. if (texture._MSAARenderBuffer) {
  17325. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  17326. texture._MSAARenderBuffer = null;
  17327. }
  17328. };
  17329. /** @hidden */
  17330. Engine.prototype._releaseTexture = function (texture) {
  17331. var gl = this._gl;
  17332. this._releaseFramebufferObjects(texture);
  17333. gl.deleteTexture(texture._webGLTexture);
  17334. // Unbind channels
  17335. this.unbindAllTextures();
  17336. var index = this._internalTexturesCache.indexOf(texture);
  17337. if (index !== -1) {
  17338. this._internalTexturesCache.splice(index, 1);
  17339. }
  17340. // Integrated fixed lod samplers.
  17341. if (texture._lodTextureHigh) {
  17342. texture._lodTextureHigh.dispose();
  17343. }
  17344. if (texture._lodTextureMid) {
  17345. texture._lodTextureMid.dispose();
  17346. }
  17347. if (texture._lodTextureLow) {
  17348. texture._lodTextureLow.dispose();
  17349. }
  17350. // Set output texture of post process to null if the texture has been released/disposed
  17351. this.scenes.forEach(function (scene) {
  17352. scene.postProcesses.forEach(function (postProcess) {
  17353. if (postProcess._outputTexture == texture) {
  17354. postProcess._outputTexture = null;
  17355. }
  17356. });
  17357. scene.cameras.forEach(function (camera) {
  17358. camera._postProcesses.forEach(function (postProcess) {
  17359. if (postProcess) {
  17360. if (postProcess._outputTexture == texture) {
  17361. postProcess._outputTexture = null;
  17362. }
  17363. }
  17364. });
  17365. });
  17366. });
  17367. };
  17368. Engine.prototype.setProgram = function (program) {
  17369. if (this._currentProgram !== program) {
  17370. this._gl.useProgram(program);
  17371. this._currentProgram = program;
  17372. }
  17373. };
  17374. /**
  17375. * Binds an effect to the webGL context
  17376. * @param effect defines the effect to bind
  17377. */
  17378. Engine.prototype.bindSamplers = function (effect) {
  17379. this.setProgram(effect.getProgram());
  17380. var samplers = effect.getSamplers();
  17381. for (var index = 0; index < samplers.length; index++) {
  17382. var uniform = effect.getUniform(samplers[index]);
  17383. if (uniform) {
  17384. this._boundUniforms[index] = uniform;
  17385. }
  17386. }
  17387. this._currentEffect = null;
  17388. };
  17389. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  17390. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  17391. return;
  17392. }
  17393. // Remove
  17394. this._linkTrackers(internalTexture.previous, internalTexture.next);
  17395. // Bind last to it
  17396. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  17397. // Bind to dummy
  17398. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  17399. };
  17400. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  17401. if (!internalTexture) {
  17402. return -1;
  17403. }
  17404. internalTexture._initialSlot = channel;
  17405. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  17406. if (channel !== internalTexture._designatedSlot) {
  17407. this._textureCollisions.addCount(1, false);
  17408. }
  17409. }
  17410. else {
  17411. if (channel !== internalTexture._designatedSlot) {
  17412. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  17413. return internalTexture._designatedSlot;
  17414. }
  17415. else {
  17416. // No slot for this texture, let's pick a new one (if we find a free slot)
  17417. if (this._nextFreeTextureSlots.length) {
  17418. return this._nextFreeTextureSlots[0];
  17419. }
  17420. // We need to recycle the oldest bound texture, sorry.
  17421. this._textureCollisions.addCount(1, false);
  17422. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  17423. }
  17424. }
  17425. }
  17426. return channel;
  17427. };
  17428. Engine.prototype._linkTrackers = function (previous, next) {
  17429. previous.next = next;
  17430. next.previous = previous;
  17431. };
  17432. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  17433. var currentSlot = internalTexture._designatedSlot;
  17434. if (currentSlot === -1) {
  17435. return -1;
  17436. }
  17437. internalTexture._designatedSlot = -1;
  17438. if (this.disableTextureBindingOptimization) {
  17439. return -1;
  17440. }
  17441. // Remove from bound list
  17442. this._linkTrackers(internalTexture.previous, internalTexture.next);
  17443. // Free the slot
  17444. this._boundTexturesCache[currentSlot] = null;
  17445. this._nextFreeTextureSlots.push(currentSlot);
  17446. return currentSlot;
  17447. };
  17448. Engine.prototype._activateCurrentTexture = function () {
  17449. if (this._currentTextureChannel !== this._activeChannel) {
  17450. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  17451. this._currentTextureChannel = this._activeChannel;
  17452. }
  17453. };
  17454. /** @hidden */
  17455. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) {
  17456. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  17457. if (force === void 0) { force = false; }
  17458. var wasPreviouslyBound = false;
  17459. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  17460. this._activeChannel = texture._designatedSlot;
  17461. }
  17462. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  17463. var isTextureForRendering = texture && texture._initialSlot > -1;
  17464. if (currentTextureBound !== texture || force) {
  17465. if (currentTextureBound) {
  17466. this._removeDesignatedSlot(currentTextureBound);
  17467. }
  17468. this._activateCurrentTexture();
  17469. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  17470. this._boundTexturesCache[this._activeChannel] = texture;
  17471. if (texture) {
  17472. if (!this.disableTextureBindingOptimization) {
  17473. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  17474. if (slotIndex > -1) {
  17475. this._nextFreeTextureSlots.splice(slotIndex, 1);
  17476. }
  17477. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  17478. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  17479. }
  17480. texture._designatedSlot = this._activeChannel;
  17481. }
  17482. }
  17483. else if (forTextureDataUpdate) {
  17484. wasPreviouslyBound = true;
  17485. this._activateCurrentTexture();
  17486. }
  17487. if (isTextureForRendering && !forTextureDataUpdate) {
  17488. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  17489. }
  17490. return wasPreviouslyBound;
  17491. };
  17492. /** @hidden */
  17493. Engine.prototype._bindTexture = function (channel, texture) {
  17494. if (channel < 0) {
  17495. return;
  17496. }
  17497. if (texture) {
  17498. channel = this._getCorrectTextureChannel(channel, texture);
  17499. }
  17500. this._activeChannel = channel;
  17501. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  17502. };
  17503. /**
  17504. * Sets a texture to the webGL context from a postprocess
  17505. * @param channel defines the channel to use
  17506. * @param postProcess defines the source postprocess
  17507. */
  17508. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  17509. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  17510. };
  17511. /**
  17512. * Binds the output of the passed in post process to the texture channel specified
  17513. * @param channel The channel the texture should be bound to
  17514. * @param postProcess The post process which's output should be bound
  17515. */
  17516. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  17517. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  17518. };
  17519. /**
  17520. * Unbind all textures from the webGL context
  17521. */
  17522. Engine.prototype.unbindAllTextures = function () {
  17523. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  17524. this._activeChannel = channel;
  17525. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  17526. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  17527. if (this.webGLVersion > 1) {
  17528. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  17529. }
  17530. }
  17531. };
  17532. /**
  17533. * Sets a texture to the according uniform.
  17534. * @param channel The texture channel
  17535. * @param uniform The uniform to set
  17536. * @param texture The texture to apply
  17537. */
  17538. Engine.prototype.setTexture = function (channel, uniform, texture) {
  17539. if (channel < 0) {
  17540. return;
  17541. }
  17542. if (uniform) {
  17543. this._boundUniforms[channel] = uniform;
  17544. }
  17545. this._setTexture(channel, texture);
  17546. };
  17547. /**
  17548. * Sets a depth stencil texture from a render target to the according uniform.
  17549. * @param channel The texture channel
  17550. * @param uniform The uniform to set
  17551. * @param texture The render target texture containing the depth stencil texture to apply
  17552. */
  17553. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  17554. if (channel < 0) {
  17555. return;
  17556. }
  17557. if (uniform) {
  17558. this._boundUniforms[channel] = uniform;
  17559. }
  17560. if (!texture || !texture.depthStencilTexture) {
  17561. this._setTexture(channel, null);
  17562. }
  17563. else {
  17564. this._setTexture(channel, texture, false, true);
  17565. }
  17566. };
  17567. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  17568. var uniform = this._boundUniforms[sourceSlot];
  17569. if (uniform._currentState === destination) {
  17570. return;
  17571. }
  17572. this._gl.uniform1i(uniform, destination);
  17573. uniform._currentState = destination;
  17574. };
  17575. Engine.prototype._getTextureWrapMode = function (mode) {
  17576. switch (mode) {
  17577. case Engine.TEXTURE_WRAP_ADDRESSMODE:
  17578. return this._gl.REPEAT;
  17579. case Engine.TEXTURE_CLAMP_ADDRESSMODE:
  17580. return this._gl.CLAMP_TO_EDGE;
  17581. case Engine.TEXTURE_MIRROR_ADDRESSMODE:
  17582. return this._gl.MIRRORED_REPEAT;
  17583. }
  17584. return this._gl.REPEAT;
  17585. };
  17586. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  17587. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  17588. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  17589. // Not ready?
  17590. if (!texture) {
  17591. if (this._boundTexturesCache[channel] != null) {
  17592. this._activeChannel = channel;
  17593. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  17594. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  17595. if (this.webGLVersion > 1) {
  17596. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  17597. }
  17598. }
  17599. return false;
  17600. }
  17601. // Video
  17602. if (texture.video) {
  17603. this._activeChannel = channel;
  17604. texture.update();
  17605. }
  17606. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  17607. texture.delayLoad();
  17608. return false;
  17609. }
  17610. var internalTexture;
  17611. if (depthStencilTexture) {
  17612. internalTexture = texture.depthStencilTexture;
  17613. }
  17614. else if (texture.isReady()) {
  17615. internalTexture = texture.getInternalTexture();
  17616. }
  17617. else if (texture.isCube) {
  17618. internalTexture = this.emptyCubeTexture;
  17619. }
  17620. else if (texture.is3D) {
  17621. internalTexture = this.emptyTexture3D;
  17622. }
  17623. else {
  17624. internalTexture = this.emptyTexture;
  17625. }
  17626. if (!isPartOfTextureArray) {
  17627. channel = this._getCorrectTextureChannel(channel, internalTexture);
  17628. }
  17629. var needToBind = true;
  17630. if (this._boundTexturesCache[channel] === internalTexture) {
  17631. this._moveBoundTextureOnTop(internalTexture);
  17632. if (!isPartOfTextureArray) {
  17633. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  17634. }
  17635. needToBind = false;
  17636. }
  17637. this._activeChannel = channel;
  17638. if (internalTexture && internalTexture.is3D) {
  17639. if (needToBind) {
  17640. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  17641. }
  17642. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  17643. internalTexture._cachedWrapU = texture.wrapU;
  17644. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  17645. }
  17646. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  17647. internalTexture._cachedWrapV = texture.wrapV;
  17648. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  17649. }
  17650. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  17651. internalTexture._cachedWrapR = texture.wrapR;
  17652. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  17653. }
  17654. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  17655. }
  17656. else if (internalTexture && internalTexture.isCube) {
  17657. if (needToBind) {
  17658. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  17659. }
  17660. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  17661. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  17662. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  17663. var textureWrapMode = (texture.coordinatesMode !== Engine.TEXTURE_CUBIC_MODE && texture.coordinatesMode !== Engine.TEXTURE_SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  17664. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  17665. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  17666. }
  17667. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  17668. }
  17669. else {
  17670. if (needToBind) {
  17671. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  17672. }
  17673. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  17674. internalTexture._cachedWrapU = texture.wrapU;
  17675. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  17676. }
  17677. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  17678. internalTexture._cachedWrapV = texture.wrapV;
  17679. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  17680. }
  17681. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  17682. }
  17683. return true;
  17684. };
  17685. /**
  17686. * Sets an array of texture to the webGL context
  17687. * @param channel defines the channel where the texture array must be set
  17688. * @param uniform defines the associated uniform location
  17689. * @param textures defines the array of textures to bind
  17690. */
  17691. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  17692. if (channel < 0 || !uniform) {
  17693. return;
  17694. }
  17695. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  17696. this._textureUnits = new Int32Array(textures.length);
  17697. }
  17698. for (var i = 0; i < textures.length; i++) {
  17699. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  17700. }
  17701. this._gl.uniform1iv(uniform, this._textureUnits);
  17702. for (var index = 0; index < textures.length; index++) {
  17703. this._setTexture(this._textureUnits[index], textures[index], true);
  17704. }
  17705. };
  17706. /** @hidden */
  17707. Engine.prototype._setAnisotropicLevel = function (target, texture) {
  17708. var internalTexture = texture.getInternalTexture();
  17709. if (!internalTexture) {
  17710. return;
  17711. }
  17712. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  17713. var value = texture.anisotropicFilteringLevel;
  17714. if (internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST
  17715. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR
  17716. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR) {
  17717. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  17718. }
  17719. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  17720. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  17721. internalTexture._cachedAnisotropicFilteringLevel = value;
  17722. }
  17723. };
  17724. Engine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) {
  17725. this._bindTextureDirectly(target, texture, true, true);
  17726. this._gl.texParameterf(target, parameter, value);
  17727. };
  17728. Engine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) {
  17729. if (texture) {
  17730. this._bindTextureDirectly(target, texture, true, true);
  17731. }
  17732. this._gl.texParameteri(target, parameter, value);
  17733. };
  17734. /**
  17735. * Reads pixels from the current frame buffer. Please note that this function can be slow
  17736. * @param x defines the x coordinate of the rectangle where pixels must be read
  17737. * @param y defines the y coordinate of the rectangle where pixels must be read
  17738. * @param width defines the width of the rectangle where pixels must be read
  17739. * @param height defines the height of the rectangle where pixels must be read
  17740. * @returns a Uint8Array containing RGBA colors
  17741. */
  17742. Engine.prototype.readPixels = function (x, y, width, height) {
  17743. var data = new Uint8Array(height * width * 4);
  17744. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  17745. return data;
  17746. };
  17747. /**
  17748. * Add an externaly attached data from its key.
  17749. * This method call will fail and return false, if such key already exists.
  17750. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  17751. * @param key the unique key that identifies the data
  17752. * @param data the data object to associate to the key for this Engine instance
  17753. * @return true if no such key were already present and the data was added successfully, false otherwise
  17754. */
  17755. Engine.prototype.addExternalData = function (key, data) {
  17756. if (!this._externalData) {
  17757. this._externalData = new BABYLON.StringDictionary();
  17758. }
  17759. return this._externalData.add(key, data);
  17760. };
  17761. /**
  17762. * Get an externaly attached data from its key
  17763. * @param key the unique key that identifies the data
  17764. * @return the associated data, if present (can be null), or undefined if not present
  17765. */
  17766. Engine.prototype.getExternalData = function (key) {
  17767. if (!this._externalData) {
  17768. this._externalData = new BABYLON.StringDictionary();
  17769. }
  17770. return this._externalData.get(key);
  17771. };
  17772. /**
  17773. * Get an externaly attached data from its key, create it using a factory if it's not already present
  17774. * @param key the unique key that identifies the data
  17775. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  17776. * @return the associated data, can be null if the factory returned null.
  17777. */
  17778. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  17779. if (!this._externalData) {
  17780. this._externalData = new BABYLON.StringDictionary();
  17781. }
  17782. return this._externalData.getOrAddWithFactory(key, factory);
  17783. };
  17784. /**
  17785. * Remove an externaly attached data from the Engine instance
  17786. * @param key the unique key that identifies the data
  17787. * @return true if the data was successfully removed, false if it doesn't exist
  17788. */
  17789. Engine.prototype.removeExternalData = function (key) {
  17790. if (!this._externalData) {
  17791. this._externalData = new BABYLON.StringDictionary();
  17792. }
  17793. return this._externalData.remove(key);
  17794. };
  17795. /**
  17796. * Unbind all vertex attributes from the webGL context
  17797. */
  17798. Engine.prototype.unbindAllAttributes = function () {
  17799. if (this._mustWipeVertexAttributes) {
  17800. this._mustWipeVertexAttributes = false;
  17801. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  17802. this._gl.disableVertexAttribArray(i);
  17803. this._vertexAttribArraysEnabled[i] = false;
  17804. this._currentBufferPointers[i].active = false;
  17805. }
  17806. return;
  17807. }
  17808. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  17809. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  17810. continue;
  17811. }
  17812. this._gl.disableVertexAttribArray(i);
  17813. this._vertexAttribArraysEnabled[i] = false;
  17814. this._currentBufferPointers[i].active = false;
  17815. }
  17816. };
  17817. /**
  17818. * 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
  17819. */
  17820. Engine.prototype.releaseEffects = function () {
  17821. for (var name in this._compiledEffects) {
  17822. this._deleteProgram(this._compiledEffects[name]._program);
  17823. }
  17824. this._compiledEffects = {};
  17825. };
  17826. /**
  17827. * Dispose and release all associated resources
  17828. */
  17829. Engine.prototype.dispose = function () {
  17830. this.hideLoadingUI();
  17831. this.stopRenderLoop();
  17832. this.onNewSceneAddedObservable.clear();
  17833. // Release postProcesses
  17834. while (this.postProcesses.length) {
  17835. this.postProcesses[0].dispose();
  17836. }
  17837. // Empty texture
  17838. if (this._emptyTexture) {
  17839. this._releaseTexture(this._emptyTexture);
  17840. this._emptyTexture = null;
  17841. }
  17842. if (this._emptyCubeTexture) {
  17843. this._releaseTexture(this._emptyCubeTexture);
  17844. this._emptyCubeTexture = null;
  17845. }
  17846. // Rescale PP
  17847. if (this._rescalePostProcess) {
  17848. this._rescalePostProcess.dispose();
  17849. }
  17850. // Release scenes
  17851. while (this.scenes.length) {
  17852. this.scenes[0].dispose();
  17853. }
  17854. // Release audio engine
  17855. if (Engine.Instances.length === 1 && Engine.audioEngine) {
  17856. Engine.audioEngine.dispose();
  17857. }
  17858. // Release effects
  17859. this.releaseEffects();
  17860. // Unbind
  17861. this.unbindAllAttributes();
  17862. this._boundUniforms = [];
  17863. if (this._dummyFramebuffer) {
  17864. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  17865. }
  17866. //WebVR
  17867. this.disableVR();
  17868. // Events
  17869. if (BABYLON.Tools.IsWindowObjectExist()) {
  17870. window.removeEventListener("blur", this._onBlur);
  17871. window.removeEventListener("focus", this._onFocus);
  17872. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  17873. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  17874. if (this._renderingCanvas) {
  17875. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  17876. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  17877. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  17878. if (!this._doNotHandleContextLost) {
  17879. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  17880. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  17881. }
  17882. }
  17883. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  17884. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  17885. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  17886. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  17887. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  17888. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  17889. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  17890. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  17891. if (this._onVrDisplayConnect) {
  17892. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  17893. if (this._onVrDisplayDisconnect) {
  17894. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  17895. }
  17896. if (this._onVrDisplayPresentChange) {
  17897. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  17898. }
  17899. this._onVrDisplayConnect = null;
  17900. this._onVrDisplayDisconnect = null;
  17901. }
  17902. }
  17903. // Remove from Instances
  17904. var index = Engine.Instances.indexOf(this);
  17905. if (index >= 0) {
  17906. Engine.Instances.splice(index, 1);
  17907. }
  17908. this._workingCanvas = null;
  17909. this._workingContext = null;
  17910. this._currentBufferPointers = [];
  17911. this._renderingCanvas = null;
  17912. this._currentProgram = null;
  17913. this._bindedRenderFunction = null;
  17914. this.onResizeObservable.clear();
  17915. this.onCanvasBlurObservable.clear();
  17916. this.onCanvasFocusObservable.clear();
  17917. this.onCanvasPointerOutObservable.clear();
  17918. this.onBeginFrameObservable.clear();
  17919. this.onEndFrameObservable.clear();
  17920. BABYLON.Effect.ResetCache();
  17921. // Abort active requests
  17922. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  17923. var request = _a[_i];
  17924. request.abort();
  17925. }
  17926. };
  17927. // Loading screen
  17928. /**
  17929. * Display the loading screen
  17930. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17931. */
  17932. Engine.prototype.displayLoadingUI = function () {
  17933. if (!BABYLON.Tools.IsWindowObjectExist()) {
  17934. return;
  17935. }
  17936. var loadingScreen = this.loadingScreen;
  17937. if (loadingScreen) {
  17938. loadingScreen.displayLoadingUI();
  17939. }
  17940. };
  17941. /**
  17942. * Hide the loading screen
  17943. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17944. */
  17945. Engine.prototype.hideLoadingUI = function () {
  17946. if (!BABYLON.Tools.IsWindowObjectExist()) {
  17947. return;
  17948. }
  17949. var loadingScreen = this.loadingScreen;
  17950. if (loadingScreen) {
  17951. loadingScreen.hideLoadingUI();
  17952. }
  17953. };
  17954. Object.defineProperty(Engine.prototype, "loadingScreen", {
  17955. /**
  17956. * Gets the current loading screen object
  17957. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17958. */
  17959. get: function () {
  17960. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas) {
  17961. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  17962. }
  17963. return this._loadingScreen;
  17964. },
  17965. /**
  17966. * Sets the current loading screen object
  17967. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17968. */
  17969. set: function (loadingScreen) {
  17970. this._loadingScreen = loadingScreen;
  17971. },
  17972. enumerable: true,
  17973. configurable: true
  17974. });
  17975. Object.defineProperty(Engine.prototype, "loadingUIText", {
  17976. /**
  17977. * Sets the current loading screen text
  17978. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17979. */
  17980. set: function (text) {
  17981. this.loadingScreen.loadingUIText = text;
  17982. },
  17983. enumerable: true,
  17984. configurable: true
  17985. });
  17986. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  17987. /**
  17988. * Sets the current loading screen background color
  17989. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17990. */
  17991. set: function (color) {
  17992. this.loadingScreen.loadingUIBackgroundColor = color;
  17993. },
  17994. enumerable: true,
  17995. configurable: true
  17996. });
  17997. /**
  17998. * Attach a new callback raised when context lost event is fired
  17999. * @param callback defines the callback to call
  18000. */
  18001. Engine.prototype.attachContextLostEvent = function (callback) {
  18002. if (this._renderingCanvas) {
  18003. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  18004. }
  18005. };
  18006. /**
  18007. * Attach a new callback raised when context restored event is fired
  18008. * @param callback defines the callback to call
  18009. */
  18010. Engine.prototype.attachContextRestoredEvent = function (callback) {
  18011. if (this._renderingCanvas) {
  18012. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  18013. }
  18014. };
  18015. /**
  18016. * Gets the source code of the vertex shader associated with a specific webGL program
  18017. * @param program defines the program to use
  18018. * @returns a string containing the source code of the vertex shader associated with the program
  18019. */
  18020. Engine.prototype.getVertexShaderSource = function (program) {
  18021. var shaders = this._gl.getAttachedShaders(program);
  18022. if (!shaders) {
  18023. return null;
  18024. }
  18025. return this._gl.getShaderSource(shaders[0]);
  18026. };
  18027. /**
  18028. * Gets the source code of the fragment shader associated with a specific webGL program
  18029. * @param program defines the program to use
  18030. * @returns a string containing the source code of the fragment shader associated with the program
  18031. */
  18032. Engine.prototype.getFragmentShaderSource = function (program) {
  18033. var shaders = this._gl.getAttachedShaders(program);
  18034. if (!shaders) {
  18035. return null;
  18036. }
  18037. return this._gl.getShaderSource(shaders[1]);
  18038. };
  18039. /**
  18040. * Get the current error code of the webGL context
  18041. * @returns the error code
  18042. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  18043. */
  18044. Engine.prototype.getError = function () {
  18045. return this._gl.getError();
  18046. };
  18047. // FPS
  18048. /**
  18049. * Gets the current framerate
  18050. * @returns a number representing the framerate
  18051. */
  18052. Engine.prototype.getFps = function () {
  18053. return this._fps;
  18054. };
  18055. /**
  18056. * Gets the time spent between current and previous frame
  18057. * @returns a number representing the delta time in ms
  18058. */
  18059. Engine.prototype.getDeltaTime = function () {
  18060. return this._deltaTime;
  18061. };
  18062. Engine.prototype._measureFps = function () {
  18063. this._performanceMonitor.sampleFrame();
  18064. this._fps = this._performanceMonitor.averageFPS;
  18065. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  18066. };
  18067. /** @hidden */
  18068. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex, level, buffer) {
  18069. if (faceIndex === void 0) { faceIndex = -1; }
  18070. if (level === void 0) { level = 0; }
  18071. if (buffer === void 0) { buffer = null; }
  18072. var gl = this._gl;
  18073. if (!this._dummyFramebuffer) {
  18074. var dummy = gl.createFramebuffer();
  18075. if (!dummy) {
  18076. throw new Error("Unable to create dummy framebuffer");
  18077. }
  18078. this._dummyFramebuffer = dummy;
  18079. }
  18080. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  18081. if (faceIndex > -1) {
  18082. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, level);
  18083. }
  18084. else {
  18085. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, level);
  18086. }
  18087. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  18088. switch (readType) {
  18089. case gl.UNSIGNED_BYTE:
  18090. if (!buffer) {
  18091. buffer = new Uint8Array(4 * width * height);
  18092. }
  18093. readType = gl.UNSIGNED_BYTE;
  18094. break;
  18095. default:
  18096. if (!buffer) {
  18097. buffer = new Float32Array(4 * width * height);
  18098. }
  18099. readType = gl.FLOAT;
  18100. break;
  18101. }
  18102. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  18103. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  18104. return buffer;
  18105. };
  18106. Engine.prototype._canRenderToFloatFramebuffer = function () {
  18107. if (this._webGLVersion > 1) {
  18108. return this._caps.colorBufferFloat;
  18109. }
  18110. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  18111. };
  18112. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  18113. if (this._webGLVersion > 1) {
  18114. return this._caps.colorBufferFloat;
  18115. }
  18116. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  18117. };
  18118. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  18119. Engine.prototype._canRenderToFramebuffer = function (type) {
  18120. var gl = this._gl;
  18121. //clear existing errors
  18122. while (gl.getError() !== gl.NO_ERROR) { }
  18123. var successful = true;
  18124. var texture = gl.createTexture();
  18125. gl.bindTexture(gl.TEXTURE_2D, texture);
  18126. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  18127. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  18128. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  18129. var fb = gl.createFramebuffer();
  18130. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  18131. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  18132. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  18133. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  18134. successful = successful && (gl.getError() === gl.NO_ERROR);
  18135. //try render by clearing frame buffer's color buffer
  18136. if (successful) {
  18137. gl.clear(gl.COLOR_BUFFER_BIT);
  18138. successful = successful && (gl.getError() === gl.NO_ERROR);
  18139. }
  18140. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  18141. if (successful) {
  18142. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  18143. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  18144. var readFormat = gl.RGBA;
  18145. var readType = gl.UNSIGNED_BYTE;
  18146. var buffer = new Uint8Array(4);
  18147. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  18148. successful = successful && (gl.getError() === gl.NO_ERROR);
  18149. }
  18150. //clean up
  18151. gl.deleteTexture(texture);
  18152. gl.deleteFramebuffer(fb);
  18153. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  18154. //clear accumulated errors
  18155. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  18156. return successful;
  18157. };
  18158. /** @hidden */
  18159. Engine.prototype._getWebGLTextureType = function (type) {
  18160. if (this._webGLVersion === 1) {
  18161. switch (type) {
  18162. case Engine.TEXTURETYPE_FLOAT:
  18163. return this._gl.FLOAT;
  18164. case Engine.TEXTURETYPE_HALF_FLOAT:
  18165. return this._gl.HALF_FLOAT_OES;
  18166. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  18167. return this._gl.UNSIGNED_BYTE;
  18168. }
  18169. return this._gl.UNSIGNED_BYTE;
  18170. }
  18171. switch (type) {
  18172. case Engine.TEXTURETYPE_BYTE:
  18173. return this._gl.BYTE;
  18174. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  18175. return this._gl.UNSIGNED_BYTE;
  18176. case Engine.TEXTURETYPE_SHORT:
  18177. return this._gl.SHORT;
  18178. case Engine.TEXTURETYPE_UNSIGNED_SHORT:
  18179. return this._gl.UNSIGNED_SHORT;
  18180. case Engine.TEXTURETYPE_INT:
  18181. return this._gl.INT;
  18182. case Engine.TEXTURETYPE_UNSIGNED_INTEGER: // Refers to UNSIGNED_INT
  18183. return this._gl.UNSIGNED_INT;
  18184. case Engine.TEXTURETYPE_FLOAT:
  18185. return this._gl.FLOAT;
  18186. case Engine.TEXTURETYPE_HALF_FLOAT:
  18187. return this._gl.HALF_FLOAT;
  18188. case Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:
  18189. return this._gl.UNSIGNED_SHORT_4_4_4_4;
  18190. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:
  18191. return this._gl.UNSIGNED_SHORT_5_5_5_1;
  18192. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:
  18193. return this._gl.UNSIGNED_SHORT_5_6_5;
  18194. case Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:
  18195. return this._gl.UNSIGNED_INT_2_10_10_10_REV;
  18196. case Engine.TEXTURETYPE_UNSIGNED_INT_24_8:
  18197. return this._gl.UNSIGNED_INT_24_8;
  18198. case Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:
  18199. return this._gl.UNSIGNED_INT_10F_11F_11F_REV;
  18200. case Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:
  18201. return this._gl.UNSIGNED_INT_5_9_9_9_REV;
  18202. case Engine.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV:
  18203. return this._gl.FLOAT_32_UNSIGNED_INT_24_8_REV;
  18204. }
  18205. return this._gl.UNSIGNED_BYTE;
  18206. };
  18207. Engine.prototype._getInternalFormat = function (format) {
  18208. var internalFormat = this._gl.RGBA;
  18209. switch (format) {
  18210. case Engine.TEXTUREFORMAT_ALPHA:
  18211. internalFormat = this._gl.ALPHA;
  18212. break;
  18213. case Engine.TEXTUREFORMAT_LUMINANCE:
  18214. internalFormat = this._gl.LUMINANCE;
  18215. break;
  18216. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  18217. internalFormat = this._gl.LUMINANCE_ALPHA;
  18218. break;
  18219. case Engine.TEXTUREFORMAT_RED:
  18220. internalFormat = this._gl.RED;
  18221. break;
  18222. case Engine.TEXTUREFORMAT_RG:
  18223. internalFormat = this._gl.RG;
  18224. break;
  18225. case Engine.TEXTUREFORMAT_RGB:
  18226. internalFormat = this._gl.RGB;
  18227. break;
  18228. case Engine.TEXTUREFORMAT_RGBA:
  18229. internalFormat = this._gl.RGBA;
  18230. break;
  18231. }
  18232. if (this._webGLVersion > 1) {
  18233. switch (format) {
  18234. case Engine.TEXTUREFORMAT_RED_INTEGER:
  18235. internalFormat = this._gl.RED_INTEGER;
  18236. break;
  18237. case Engine.TEXTUREFORMAT_RG_INTEGER:
  18238. internalFormat = this._gl.RG_INTEGER;
  18239. break;
  18240. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  18241. internalFormat = this._gl.RGB_INTEGER;
  18242. break;
  18243. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  18244. internalFormat = this._gl.RGBA_INTEGER;
  18245. break;
  18246. }
  18247. }
  18248. return internalFormat;
  18249. };
  18250. /** @hidden */
  18251. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  18252. if (this._webGLVersion === 1) {
  18253. if (format !== undefined) {
  18254. switch (format) {
  18255. case Engine.TEXTUREFORMAT_ALPHA:
  18256. return this._gl.ALPHA;
  18257. case Engine.TEXTUREFORMAT_LUMINANCE:
  18258. return this._gl.LUMINANCE;
  18259. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  18260. return this._gl.LUMINANCE_ALPHA;
  18261. }
  18262. }
  18263. return this._gl.RGBA;
  18264. }
  18265. switch (type) {
  18266. case Engine.TEXTURETYPE_BYTE:
  18267. switch (format) {
  18268. case Engine.TEXTUREFORMAT_RED:
  18269. return this._gl.R8_SNORM;
  18270. case Engine.TEXTUREFORMAT_RG:
  18271. return this._gl.RG8_SNORM;
  18272. case Engine.TEXTUREFORMAT_RGB:
  18273. return this._gl.RGB8_SNORM;
  18274. case Engine.TEXTUREFORMAT_RED_INTEGER:
  18275. return this._gl.R8I;
  18276. case Engine.TEXTUREFORMAT_RG_INTEGER:
  18277. return this._gl.RG8I;
  18278. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  18279. return this._gl.RGB8I;
  18280. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  18281. return this._gl.RGBA8I;
  18282. default:
  18283. return this._gl.RGBA8_SNORM;
  18284. }
  18285. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  18286. switch (format) {
  18287. case Engine.TEXTUREFORMAT_RED:
  18288. return this._gl.R8;
  18289. case Engine.TEXTUREFORMAT_RG:
  18290. return this._gl.RG8;
  18291. case Engine.TEXTUREFORMAT_RGB:
  18292. return this._gl.RGB8; // By default. Other possibilities are RGB565, SRGB8.
  18293. case Engine.TEXTUREFORMAT_RGBA:
  18294. return this._gl.RGBA8; // By default. Other possibilities are RGB5_A1, RGBA4, SRGB8_ALPHA8.
  18295. case Engine.TEXTUREFORMAT_RED_INTEGER:
  18296. return this._gl.R8UI;
  18297. case Engine.TEXTUREFORMAT_RG_INTEGER:
  18298. return this._gl.RG8UI;
  18299. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  18300. return this._gl.RGB8UI;
  18301. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  18302. return this._gl.RGBA8UI;
  18303. default:
  18304. return this._gl.RGBA8;
  18305. }
  18306. case Engine.TEXTURETYPE_SHORT:
  18307. switch (format) {
  18308. case Engine.TEXTUREFORMAT_RED_INTEGER:
  18309. return this._gl.R16I;
  18310. case Engine.TEXTUREFORMAT_RG_INTEGER:
  18311. return this._gl.RG16I;
  18312. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  18313. return this._gl.RGB16I;
  18314. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  18315. return this._gl.RGBA16I;
  18316. default:
  18317. return this._gl.RGBA16I;
  18318. }
  18319. case Engine.TEXTURETYPE_UNSIGNED_SHORT:
  18320. switch (format) {
  18321. case Engine.TEXTUREFORMAT_RED_INTEGER:
  18322. return this._gl.R16UI;
  18323. case Engine.TEXTUREFORMAT_RG_INTEGER:
  18324. return this._gl.RG16UI;
  18325. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  18326. return this._gl.RGB16UI;
  18327. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  18328. return this._gl.RGBA16UI;
  18329. default:
  18330. return this._gl.RGBA16UI;
  18331. }
  18332. case Engine.TEXTURETYPE_INT:
  18333. switch (format) {
  18334. case Engine.TEXTUREFORMAT_RED_INTEGER:
  18335. return this._gl.R32I;
  18336. case Engine.TEXTUREFORMAT_RG_INTEGER:
  18337. return this._gl.RG32I;
  18338. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  18339. return this._gl.RGB32I;
  18340. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  18341. return this._gl.RGBA32I;
  18342. default:
  18343. return this._gl.RGBA32I;
  18344. }
  18345. case Engine.TEXTURETYPE_UNSIGNED_INTEGER: // Refers to UNSIGNED_INT
  18346. switch (format) {
  18347. case Engine.TEXTUREFORMAT_RED_INTEGER:
  18348. return this._gl.R32UI;
  18349. case Engine.TEXTUREFORMAT_RG_INTEGER:
  18350. return this._gl.RG32UI;
  18351. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  18352. return this._gl.RGB32UI;
  18353. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  18354. return this._gl.RGBA32UI;
  18355. default:
  18356. return this._gl.RGBA32UI;
  18357. }
  18358. case Engine.TEXTURETYPE_FLOAT:
  18359. switch (format) {
  18360. case Engine.TEXTUREFORMAT_RED:
  18361. return this._gl.R32F; // By default. Other possibility is R16F.
  18362. case Engine.TEXTUREFORMAT_RG:
  18363. return this._gl.RG32F; // By default. Other possibility is RG16F.
  18364. case Engine.TEXTUREFORMAT_RGB:
  18365. return this._gl.RGB32F; // By default. Other possibilities are RGB16F, R11F_G11F_B10F, RGB9_E5.
  18366. case Engine.TEXTUREFORMAT_RGBA:
  18367. return this._gl.RGBA32F; // By default. Other possibility is RGBA16F.
  18368. default:
  18369. return this._gl.RGBA32F;
  18370. }
  18371. case Engine.TEXTURETYPE_HALF_FLOAT:
  18372. switch (format) {
  18373. case Engine.TEXTUREFORMAT_RED:
  18374. return this._gl.R16F;
  18375. case Engine.TEXTUREFORMAT_RG:
  18376. return this._gl.RG16F;
  18377. case Engine.TEXTUREFORMAT_RGB:
  18378. return this._gl.RGB16F; // By default. Other possibilities are R11F_G11F_B10F, RGB9_E5.
  18379. case Engine.TEXTUREFORMAT_RGBA:
  18380. return this._gl.RGBA16F;
  18381. default:
  18382. return this._gl.RGBA16F;
  18383. }
  18384. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:
  18385. return this._gl.RGB565;
  18386. case Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:
  18387. return this._gl.R11F_G11F_B10F;
  18388. case Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:
  18389. return this._gl.RGB9_E5;
  18390. case Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:
  18391. return this._gl.RGBA4;
  18392. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:
  18393. return this._gl.RGB5_A1;
  18394. case Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:
  18395. switch (format) {
  18396. case Engine.TEXTUREFORMAT_RGBA:
  18397. return this._gl.RGB10_A2; // By default. Other possibility is RGB5_A1.
  18398. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  18399. return this._gl.RGB10_A2UI;
  18400. default:
  18401. return this._gl.RGB10_A2;
  18402. }
  18403. }
  18404. return this._gl.RGBA8;
  18405. };
  18406. /** @hidden */
  18407. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  18408. if (type === Engine.TEXTURETYPE_FLOAT) {
  18409. return this._gl.RGBA32F;
  18410. }
  18411. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  18412. return this._gl.RGBA16F;
  18413. }
  18414. return this._gl.RGBA8;
  18415. };
  18416. /** @hidden */
  18417. Engine.prototype._loadFile = function (url, onSuccess, onProgress, offlineProvider, useArrayBuffer, onError) {
  18418. var _this = this;
  18419. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, offlineProvider, useArrayBuffer, onError);
  18420. this._activeRequests.push(request);
  18421. request.onCompleteObservable.add(function (request) {
  18422. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  18423. });
  18424. return request;
  18425. };
  18426. /** @hidden */
  18427. Engine.prototype._loadFileAsync = function (url, offlineProvider, useArrayBuffer) {
  18428. var _this = this;
  18429. return new Promise(function (resolve, reject) {
  18430. _this._loadFile(url, function (data) {
  18431. resolve(data);
  18432. }, undefined, offlineProvider, useArrayBuffer, function (request, exception) {
  18433. reject(exception);
  18434. });
  18435. });
  18436. };
  18437. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  18438. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  18439. var onload = function (data) {
  18440. loadedFiles[index] = data;
  18441. loadedFiles._internalCount++;
  18442. if (loadedFiles._internalCount === 6) {
  18443. onfinish(loadedFiles);
  18444. }
  18445. };
  18446. var onerror = function (request, exception) {
  18447. if (onErrorCallBack && request) {
  18448. onErrorCallBack(request.status + " " + request.statusText, exception);
  18449. }
  18450. };
  18451. this._loadFile(url, onload, undefined, undefined, true, onerror);
  18452. };
  18453. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  18454. if (onError === void 0) { onError = null; }
  18455. var loadedFiles = [];
  18456. loadedFiles._internalCount = 0;
  18457. for (var index = 0; index < 6; index++) {
  18458. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  18459. }
  18460. };
  18461. // Statics
  18462. /**
  18463. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  18464. * @returns true if the engine can be created
  18465. * @ignorenaming
  18466. */
  18467. Engine.isSupported = function () {
  18468. try {
  18469. var tempcanvas = document.createElement("canvas");
  18470. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  18471. return gl != null && !!window.WebGLRenderingContext;
  18472. }
  18473. catch (e) {
  18474. return false;
  18475. }
  18476. };
  18477. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  18478. Engine.ExceptionList = [
  18479. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  18480. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  18481. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  18482. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  18483. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  18484. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  18485. ];
  18486. /** Gets the list of created engines */
  18487. Engine.Instances = new Array();
  18488. /**
  18489. * Hidden
  18490. */
  18491. Engine._TextureLoaders = [];
  18492. // Const statics
  18493. /** Defines that alpha blending is disabled */
  18494. Engine.ALPHA_DISABLE = 0;
  18495. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  18496. Engine.ALPHA_ADD = 1;
  18497. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  18498. Engine.ALPHA_COMBINE = 2;
  18499. /** Defines that alpha blending to DEST - SRC * DEST */
  18500. Engine.ALPHA_SUBTRACT = 3;
  18501. /** Defines that alpha blending to SRC * DEST */
  18502. Engine.ALPHA_MULTIPLY = 4;
  18503. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  18504. Engine.ALPHA_MAXIMIZED = 5;
  18505. /** Defines that alpha blending to SRC + DEST */
  18506. Engine.ALPHA_ONEONE = 6;
  18507. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  18508. Engine.ALPHA_PREMULTIPLIED = 7;
  18509. /**
  18510. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  18511. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  18512. */
  18513. Engine.ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  18514. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  18515. Engine.ALPHA_INTERPOLATE = 9;
  18516. /**
  18517. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  18518. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  18519. */
  18520. Engine.ALPHA_SCREENMODE = 10;
  18521. /** Defines that the ressource is not delayed*/
  18522. Engine.DELAYLOADSTATE_NONE = 0;
  18523. /** Defines that the ressource was successfully delay loaded */
  18524. Engine.DELAYLOADSTATE_LOADED = 1;
  18525. /** Defines that the ressource is currently delay loading */
  18526. Engine.DELAYLOADSTATE_LOADING = 2;
  18527. /** Defines that the ressource is delayed and has not started loading */
  18528. Engine.DELAYLOADSTATE_NOTLOADED = 4;
  18529. // Depht or Stencil test Constants.
  18530. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  18531. Engine.NEVER = 0x0200;
  18532. /** 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 */
  18533. Engine.ALWAYS = 0x0207;
  18534. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  18535. Engine.LESS = 0x0201;
  18536. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  18537. Engine.EQUAL = 0x0202;
  18538. /** 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 */
  18539. Engine.LEQUAL = 0x0203;
  18540. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  18541. Engine.GREATER = 0x0204;
  18542. /** 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 */
  18543. Engine.GEQUAL = 0x0206;
  18544. /** 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 */
  18545. Engine.NOTEQUAL = 0x0205;
  18546. // Stencil Actions Constants.
  18547. /** Passed to stencilOperation to specify that stencil value must be kept */
  18548. Engine.KEEP = 0x1E00;
  18549. /** Passed to stencilOperation to specify that stencil value must be replaced */
  18550. Engine.REPLACE = 0x1E01;
  18551. /** Passed to stencilOperation to specify that stencil value must be incremented */
  18552. Engine.INCR = 0x1E02;
  18553. /** Passed to stencilOperation to specify that stencil value must be decremented */
  18554. Engine.DECR = 0x1E03;
  18555. /** Passed to stencilOperation to specify that stencil value must be inverted */
  18556. Engine.INVERT = 0x150A;
  18557. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  18558. Engine.INCR_WRAP = 0x8507;
  18559. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  18560. Engine.DECR_WRAP = 0x8508;
  18561. /** Texture is not repeating outside of 0..1 UVs */
  18562. Engine.TEXTURE_CLAMP_ADDRESSMODE = 0;
  18563. /** Texture is repeating outside of 0..1 UVs */
  18564. Engine.TEXTURE_WRAP_ADDRESSMODE = 1;
  18565. /** Texture is repeating and mirrored */
  18566. Engine.TEXTURE_MIRROR_ADDRESSMODE = 2;
  18567. /** ALPHA */
  18568. Engine.TEXTUREFORMAT_ALPHA = 0;
  18569. /** LUMINANCE */
  18570. Engine.TEXTUREFORMAT_LUMINANCE = 1;
  18571. /** LUMINANCE_ALPHA */
  18572. Engine.TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  18573. /** RGB */
  18574. Engine.TEXTUREFORMAT_RGB = 4;
  18575. /** RGBA */
  18576. Engine.TEXTUREFORMAT_RGBA = 5;
  18577. /** RED */
  18578. Engine.TEXTUREFORMAT_RED = 6;
  18579. /** RED (2nd reference) */
  18580. Engine.TEXTUREFORMAT_R = 6;
  18581. /** RG */
  18582. Engine.TEXTUREFORMAT_RG = 7;
  18583. /** RED_INTEGER */
  18584. Engine.TEXTUREFORMAT_RED_INTEGER = 8;
  18585. /** RED_INTEGER (2nd reference) */
  18586. Engine.TEXTUREFORMAT_R_INTEGER = 8;
  18587. /** RG_INTEGER */
  18588. Engine.TEXTUREFORMAT_RG_INTEGER = 9;
  18589. /** RGB_INTEGER */
  18590. Engine.TEXTUREFORMAT_RGB_INTEGER = 10;
  18591. /** RGBA_INTEGER */
  18592. Engine.TEXTUREFORMAT_RGBA_INTEGER = 11;
  18593. /** UNSIGNED_BYTE */
  18594. Engine.TEXTURETYPE_UNSIGNED_BYTE = 0;
  18595. /** UNSIGNED_BYTE (2nd reference) */
  18596. Engine.TEXTURETYPE_UNSIGNED_INT = 0;
  18597. /** FLOAT */
  18598. Engine.TEXTURETYPE_FLOAT = 1;
  18599. /** HALF_FLOAT */
  18600. Engine.TEXTURETYPE_HALF_FLOAT = 2;
  18601. /** BYTE */
  18602. Engine.TEXTURETYPE_BYTE = 3;
  18603. /** SHORT */
  18604. Engine.TEXTURETYPE_SHORT = 4;
  18605. /** UNSIGNED_SHORT */
  18606. Engine.TEXTURETYPE_UNSIGNED_SHORT = 5;
  18607. /** INT */
  18608. Engine.TEXTURETYPE_INT = 6;
  18609. /** UNSIGNED_INT */
  18610. Engine.TEXTURETYPE_UNSIGNED_INTEGER = 7;
  18611. /** UNSIGNED_SHORT_4_4_4_4 */
  18612. Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4 = 8;
  18613. /** UNSIGNED_SHORT_5_5_5_1 */
  18614. Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1 = 9;
  18615. /** UNSIGNED_SHORT_5_6_5 */
  18616. Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5 = 10;
  18617. /** UNSIGNED_INT_2_10_10_10_REV */
  18618. Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV = 11;
  18619. /** UNSIGNED_INT_24_8 */
  18620. Engine.TEXTURETYPE_UNSIGNED_INT_24_8 = 12;
  18621. /** UNSIGNED_INT_10F_11F_11F_REV */
  18622. Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV = 13;
  18623. /** UNSIGNED_INT_5_9_9_9_REV */
  18624. Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV = 14;
  18625. /** FLOAT_32_UNSIGNED_INT_24_8_REV */
  18626. Engine.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV = 15;
  18627. /** nearest is mag = nearest and min = nearest and mip = linear */
  18628. Engine.TEXTURE_NEAREST_SAMPLINGMODE = 1;
  18629. /** Bilinear is mag = linear and min = linear and mip = nearest */
  18630. Engine.TEXTURE_BILINEAR_SAMPLINGMODE = 2;
  18631. /** Trilinear is mag = linear and min = linear and mip = linear */
  18632. Engine.TEXTURE_TRILINEAR_SAMPLINGMODE = 3;
  18633. /** nearest is mag = nearest and min = nearest and mip = linear */
  18634. Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR = 1;
  18635. /** Bilinear is mag = linear and min = linear and mip = nearest */
  18636. Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST = 2;
  18637. /** Trilinear is mag = linear and min = linear and mip = linear */
  18638. Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR = 3;
  18639. /** mag = nearest and min = nearest and mip = nearest */
  18640. Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST = 4;
  18641. /** mag = nearest and min = linear and mip = nearest */
  18642. Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST = 5;
  18643. /** mag = nearest and min = linear and mip = linear */
  18644. Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR = 6;
  18645. /** mag = nearest and min = linear and mip = none */
  18646. Engine.TEXTURE_NEAREST_LINEAR = 7;
  18647. /** mag = nearest and min = nearest and mip = none */
  18648. Engine.TEXTURE_NEAREST_NEAREST = 8;
  18649. /** mag = linear and min = nearest and mip = nearest */
  18650. Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST = 9;
  18651. /** mag = linear and min = nearest and mip = linear */
  18652. Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR = 10;
  18653. /** mag = linear and min = linear and mip = none */
  18654. Engine.TEXTURE_LINEAR_LINEAR = 11;
  18655. /** mag = linear and min = nearest and mip = none */
  18656. Engine.TEXTURE_LINEAR_NEAREST = 12;
  18657. /** Explicit coordinates mode */
  18658. Engine.TEXTURE_EXPLICIT_MODE = 0;
  18659. /** Spherical coordinates mode */
  18660. Engine.TEXTURE_SPHERICAL_MODE = 1;
  18661. /** Planar coordinates mode */
  18662. Engine.TEXTURE_PLANAR_MODE = 2;
  18663. /** Cubic coordinates mode */
  18664. Engine.TEXTURE_CUBIC_MODE = 3;
  18665. /** Projection coordinates mode */
  18666. Engine.TEXTURE_PROJECTION_MODE = 4;
  18667. /** Skybox coordinates mode */
  18668. Engine.TEXTURE_SKYBOX_MODE = 5;
  18669. /** Inverse Cubic coordinates mode */
  18670. Engine.TEXTURE_INVCUBIC_MODE = 6;
  18671. /** Equirectangular coordinates mode */
  18672. Engine.TEXTURE_EQUIRECTANGULAR_MODE = 7;
  18673. /** Equirectangular Fixed coordinates mode */
  18674. Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE = 8;
  18675. /** Equirectangular Fixed Mirrored coordinates mode */
  18676. Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  18677. // Texture rescaling mode
  18678. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  18679. Engine.SCALEMODE_FLOOR = 1;
  18680. /** Defines that texture rescaling will look for the nearest power of 2 size */
  18681. Engine.SCALEMODE_NEAREST = 2;
  18682. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  18683. Engine.SCALEMODE_CEILING = 3;
  18684. // Updatable statics so stick with vars here
  18685. /**
  18686. * Gets or sets the epsilon value used by collision engine
  18687. */
  18688. Engine.CollisionsEpsilon = 0.001;
  18689. /**
  18690. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  18691. */
  18692. Engine.CodeRepository = "src/";
  18693. /**
  18694. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  18695. */
  18696. Engine.ShadersRepository = "src/Shaders/";
  18697. return Engine;
  18698. }());
  18699. BABYLON.Engine = Engine;
  18700. })(BABYLON || (BABYLON = {}));
  18701. //# sourceMappingURL=babylon.engine.js.map
  18702. var BABYLON;
  18703. (function (BABYLON) {
  18704. /**
  18705. * Node is the basic class for all scene objects (Mesh, Light, Camera.)
  18706. */
  18707. var Node = /** @class */ (function () {
  18708. /**
  18709. * Creates a new Node
  18710. * @param name the name and id to be given to this node
  18711. * @param scene the scene this node will be added to
  18712. * @param addToRootNodes the node will be added to scene.rootNodes
  18713. */
  18714. function Node(name, scene, addToRootNodes) {
  18715. if (scene === void 0) { scene = null; }
  18716. if (addToRootNodes === void 0) { addToRootNodes = true; }
  18717. /**
  18718. * Gets or sets a string used to store user defined state for the node
  18719. */
  18720. this.state = "";
  18721. /**
  18722. * Gets or sets an object used to store user defined information for the node
  18723. */
  18724. this.metadata = null;
  18725. /**
  18726. * Gets or sets a boolean used to define if the node must be serialized
  18727. */
  18728. this.doNotSerialize = false;
  18729. /** @hidden */
  18730. this._isDisposed = false;
  18731. /**
  18732. * Gets a list of Animations associated with the node
  18733. */
  18734. this.animations = new Array();
  18735. this._ranges = {};
  18736. this._isEnabled = true;
  18737. this._isParentEnabled = true;
  18738. this._isReady = true;
  18739. /** @hidden */
  18740. this._currentRenderId = -1;
  18741. this._parentRenderId = -1;
  18742. this._childRenderId = -1;
  18743. /** @hidden */
  18744. this._worldMatrix = BABYLON.Matrix.Identity();
  18745. /** @hidden */
  18746. this._worldMatrixDeterminant = 0;
  18747. /** @hidden */
  18748. this._sceneRootNodesIndex = -1;
  18749. this._animationPropertiesOverride = null;
  18750. /**
  18751. * An event triggered when the mesh is disposed
  18752. */
  18753. this.onDisposeObservable = new BABYLON.Observable();
  18754. // Behaviors
  18755. this._behaviors = new Array();
  18756. this.name = name;
  18757. this.id = name;
  18758. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  18759. this.uniqueId = this._scene.getUniqueId();
  18760. this._initCache();
  18761. if (addToRootNodes) {
  18762. this.addToSceneRootNodes();
  18763. }
  18764. }
  18765. /**
  18766. * Add a new node constructor
  18767. * @param type defines the type name of the node to construct
  18768. * @param constructorFunc defines the constructor function
  18769. */
  18770. Node.AddNodeConstructor = function (type, constructorFunc) {
  18771. this._NodeConstructors[type] = constructorFunc;
  18772. };
  18773. /**
  18774. * Returns a node constructor based on type name
  18775. * @param type defines the type name
  18776. * @param name defines the new node name
  18777. * @param scene defines the hosting scene
  18778. * @param options defines optional options to transmit to constructors
  18779. * @returns the new constructor or null
  18780. */
  18781. Node.Construct = function (type, name, scene, options) {
  18782. var constructorFunc = this._NodeConstructors[type];
  18783. if (!constructorFunc) {
  18784. return null;
  18785. }
  18786. return constructorFunc(name, scene, options);
  18787. };
  18788. /**
  18789. * Gets a boolean indicating if the node has been disposed
  18790. * @returns true if the node was disposed
  18791. */
  18792. Node.prototype.isDisposed = function () {
  18793. return this._isDisposed;
  18794. };
  18795. Object.defineProperty(Node.prototype, "parent", {
  18796. get: function () {
  18797. return this._parentNode;
  18798. },
  18799. /**
  18800. * Gets or sets the parent of the node
  18801. */
  18802. set: function (parent) {
  18803. if (this._parentNode === parent) {
  18804. return;
  18805. }
  18806. var previousParentNode = this._parentNode;
  18807. // Remove self from list of children of parent
  18808. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  18809. var index = this._parentNode._children.indexOf(this);
  18810. if (index !== -1) {
  18811. this._parentNode._children.splice(index, 1);
  18812. }
  18813. if (!parent) {
  18814. this.addToSceneRootNodes();
  18815. }
  18816. }
  18817. // Store new parent
  18818. this._parentNode = parent;
  18819. // Add as child to new parent
  18820. if (this._parentNode) {
  18821. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  18822. this._parentNode._children = new Array();
  18823. }
  18824. this._parentNode._children.push(this);
  18825. if (!previousParentNode) {
  18826. this.removeFromSceneRootNodes();
  18827. }
  18828. }
  18829. // Enabled state
  18830. this._syncParentEnabledState();
  18831. },
  18832. enumerable: true,
  18833. configurable: true
  18834. });
  18835. Node.prototype.addToSceneRootNodes = function () {
  18836. if (this._sceneRootNodesIndex === -1) {
  18837. this._sceneRootNodesIndex = this._scene.rootNodes.length;
  18838. this._scene.rootNodes.push(this);
  18839. }
  18840. };
  18841. Node.prototype.removeFromSceneRootNodes = function () {
  18842. if (this._sceneRootNodesIndex !== -1) {
  18843. var rootNodes = this._scene.rootNodes;
  18844. var lastIdx = rootNodes.length - 1;
  18845. rootNodes[this._sceneRootNodesIndex] = rootNodes[lastIdx];
  18846. rootNodes[this._sceneRootNodesIndex]._sceneRootNodesIndex = this._sceneRootNodesIndex;
  18847. this._scene.rootNodes.pop();
  18848. this._sceneRootNodesIndex = -1;
  18849. }
  18850. };
  18851. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  18852. /**
  18853. * Gets or sets the animation properties override
  18854. */
  18855. get: function () {
  18856. if (!this._animationPropertiesOverride) {
  18857. return this._scene.animationPropertiesOverride;
  18858. }
  18859. return this._animationPropertiesOverride;
  18860. },
  18861. set: function (value) {
  18862. this._animationPropertiesOverride = value;
  18863. },
  18864. enumerable: true,
  18865. configurable: true
  18866. });
  18867. /**
  18868. * Gets a string idenfifying the name of the class
  18869. * @returns "Node" string
  18870. */
  18871. Node.prototype.getClassName = function () {
  18872. return "Node";
  18873. };
  18874. Object.defineProperty(Node.prototype, "onDispose", {
  18875. /**
  18876. * Sets a callback that will be raised when the node will be disposed
  18877. */
  18878. set: function (callback) {
  18879. if (this._onDisposeObserver) {
  18880. this.onDisposeObservable.remove(this._onDisposeObserver);
  18881. }
  18882. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  18883. },
  18884. enumerable: true,
  18885. configurable: true
  18886. });
  18887. /**
  18888. * Gets the scene of the node
  18889. * @returns a scene
  18890. */
  18891. Node.prototype.getScene = function () {
  18892. return this._scene;
  18893. };
  18894. /**
  18895. * Gets the engine of the node
  18896. * @returns a Engine
  18897. */
  18898. Node.prototype.getEngine = function () {
  18899. return this._scene.getEngine();
  18900. };
  18901. /**
  18902. * Attach a behavior to the node
  18903. * @see http://doc.babylonjs.com/features/behaviour
  18904. * @param behavior defines the behavior to attach
  18905. * @param attachImmediately defines that the behavior must be attached even if the scene is still loading
  18906. * @returns the current Node
  18907. */
  18908. Node.prototype.addBehavior = function (behavior, attachImmediately) {
  18909. var _this = this;
  18910. if (attachImmediately === void 0) { attachImmediately = false; }
  18911. var index = this._behaviors.indexOf(behavior);
  18912. if (index !== -1) {
  18913. return this;
  18914. }
  18915. behavior.init();
  18916. if (this._scene.isLoading && !attachImmediately) {
  18917. // We defer the attach when the scene will be loaded
  18918. this._scene.onDataLoadedObservable.addOnce(function () {
  18919. behavior.attach(_this);
  18920. });
  18921. }
  18922. else {
  18923. behavior.attach(this);
  18924. }
  18925. this._behaviors.push(behavior);
  18926. return this;
  18927. };
  18928. /**
  18929. * Remove an attached behavior
  18930. * @see http://doc.babylonjs.com/features/behaviour
  18931. * @param behavior defines the behavior to attach
  18932. * @returns the current Node
  18933. */
  18934. Node.prototype.removeBehavior = function (behavior) {
  18935. var index = this._behaviors.indexOf(behavior);
  18936. if (index === -1) {
  18937. return this;
  18938. }
  18939. this._behaviors[index].detach();
  18940. this._behaviors.splice(index, 1);
  18941. return this;
  18942. };
  18943. Object.defineProperty(Node.prototype, "behaviors", {
  18944. /**
  18945. * Gets the list of attached behaviors
  18946. * @see http://doc.babylonjs.com/features/behaviour
  18947. */
  18948. get: function () {
  18949. return this._behaviors;
  18950. },
  18951. enumerable: true,
  18952. configurable: true
  18953. });
  18954. /**
  18955. * Gets an attached behavior by name
  18956. * @param name defines the name of the behavior to look for
  18957. * @see http://doc.babylonjs.com/features/behaviour
  18958. * @returns null if behavior was not found else the requested behavior
  18959. */
  18960. Node.prototype.getBehaviorByName = function (name) {
  18961. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  18962. var behavior = _a[_i];
  18963. if (behavior.name === name) {
  18964. return behavior;
  18965. }
  18966. }
  18967. return null;
  18968. };
  18969. /**
  18970. * Returns the latest update of the World matrix
  18971. * @returns a Matrix
  18972. */
  18973. Node.prototype.getWorldMatrix = function () {
  18974. if (this._currentRenderId !== this._scene.getRenderId()) {
  18975. this.computeWorldMatrix();
  18976. }
  18977. return this._worldMatrix;
  18978. };
  18979. /** @hidden */
  18980. Node.prototype._getWorldMatrixDeterminant = function () {
  18981. return this._worldMatrixDeterminant;
  18982. };
  18983. Object.defineProperty(Node.prototype, "worldMatrixFromCache", {
  18984. /**
  18985. * Returns directly the latest state of the mesh World matrix.
  18986. * A Matrix is returned.
  18987. */
  18988. get: function () {
  18989. return this._worldMatrix;
  18990. },
  18991. enumerable: true,
  18992. configurable: true
  18993. });
  18994. // override it in derived class if you add new variables to the cache
  18995. // and call the parent class method
  18996. /** @hidden */
  18997. Node.prototype._initCache = function () {
  18998. this._cache = {};
  18999. this._cache.parent = undefined;
  19000. };
  19001. /** @hidden */
  19002. Node.prototype.updateCache = function (force) {
  19003. if (!force && this.isSynchronized()) {
  19004. return;
  19005. }
  19006. this._cache.parent = this.parent;
  19007. this._updateCache();
  19008. };
  19009. // override it in derived class if you add new variables to the cache
  19010. // and call the parent class method if !ignoreParentClass
  19011. /** @hidden */
  19012. Node.prototype._updateCache = function (ignoreParentClass) {
  19013. };
  19014. // override it in derived class if you add new variables to the cache
  19015. /** @hidden */
  19016. Node.prototype._isSynchronized = function () {
  19017. return true;
  19018. };
  19019. /** @hidden */
  19020. Node.prototype._markSyncedWithParent = function () {
  19021. if (this._parentNode) {
  19022. this._parentRenderId = this._parentNode._childRenderId;
  19023. }
  19024. };
  19025. /** @hidden */
  19026. Node.prototype.isSynchronizedWithParent = function () {
  19027. if (!this._parentNode) {
  19028. return true;
  19029. }
  19030. if (this._parentRenderId !== this._parentNode._childRenderId) {
  19031. return false;
  19032. }
  19033. return this._parentNode.isSynchronized();
  19034. };
  19035. /** @hidden */
  19036. Node.prototype.isSynchronized = function () {
  19037. if (this._cache.parent != this._parentNode) {
  19038. this._cache.parent = this._parentNode;
  19039. return false;
  19040. }
  19041. if (this._parentNode && !this.isSynchronizedWithParent()) {
  19042. return false;
  19043. }
  19044. return this._isSynchronized();
  19045. };
  19046. /**
  19047. * Is this node ready to be used/rendered
  19048. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  19049. * @return true if the node is ready
  19050. */
  19051. Node.prototype.isReady = function (completeCheck) {
  19052. if (completeCheck === void 0) { completeCheck = false; }
  19053. return this._isReady;
  19054. };
  19055. /**
  19056. * Is this node enabled?
  19057. * 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
  19058. * @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
  19059. * @return whether this node (and its parent) is enabled
  19060. */
  19061. Node.prototype.isEnabled = function (checkAncestors) {
  19062. if (checkAncestors === void 0) { checkAncestors = true; }
  19063. if (checkAncestors === false) {
  19064. return this._isEnabled;
  19065. }
  19066. if (!this._isEnabled) {
  19067. return false;
  19068. }
  19069. return this._isParentEnabled;
  19070. };
  19071. /** @hidden */
  19072. Node.prototype._syncParentEnabledState = function () {
  19073. this._isParentEnabled = this._parentNode ? this._parentNode.isEnabled() : true;
  19074. if (this._children) {
  19075. this._children.forEach(function (c) {
  19076. c._syncParentEnabledState(); // Force children to update accordingly
  19077. });
  19078. }
  19079. };
  19080. /**
  19081. * Set the enabled state of this node
  19082. * @param value defines the new enabled state
  19083. */
  19084. Node.prototype.setEnabled = function (value) {
  19085. this._isEnabled = value;
  19086. this._syncParentEnabledState();
  19087. };
  19088. /**
  19089. * Is this node a descendant of the given node?
  19090. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  19091. * @param ancestor defines the parent node to inspect
  19092. * @returns a boolean indicating if this node is a descendant of the given node
  19093. */
  19094. Node.prototype.isDescendantOf = function (ancestor) {
  19095. if (this.parent) {
  19096. if (this.parent === ancestor) {
  19097. return true;
  19098. }
  19099. return this.parent.isDescendantOf(ancestor);
  19100. }
  19101. return false;
  19102. };
  19103. /** @hidden */
  19104. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  19105. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  19106. if (!this._children) {
  19107. return;
  19108. }
  19109. for (var index = 0; index < this._children.length; index++) {
  19110. var item = this._children[index];
  19111. if (!predicate || predicate(item)) {
  19112. results.push(item);
  19113. }
  19114. if (!directDescendantsOnly) {
  19115. item._getDescendants(results, false, predicate);
  19116. }
  19117. }
  19118. };
  19119. /**
  19120. * Will return all nodes that have this node as ascendant
  19121. * @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
  19122. * @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
  19123. * @return all children nodes of all types
  19124. */
  19125. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  19126. var results = new Array();
  19127. this._getDescendants(results, directDescendantsOnly, predicate);
  19128. return results;
  19129. };
  19130. /**
  19131. * Get all child-meshes of this node
  19132. * @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
  19133. * @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
  19134. * @returns an array of AbstractMesh
  19135. */
  19136. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  19137. var results = [];
  19138. this._getDescendants(results, directDescendantsOnly, function (node) {
  19139. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  19140. });
  19141. return results;
  19142. };
  19143. /**
  19144. * Get all child-transformNodes of this node
  19145. * @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
  19146. * @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
  19147. * @returns an array of TransformNode
  19148. */
  19149. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  19150. var results = [];
  19151. this._getDescendants(results, directDescendantsOnly, function (node) {
  19152. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  19153. });
  19154. return results;
  19155. };
  19156. /**
  19157. * Get all direct children of this node
  19158. * @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
  19159. * @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 (Default: true)
  19160. * @returns an array of Node
  19161. */
  19162. Node.prototype.getChildren = function (predicate, directDescendantsOnly) {
  19163. if (directDescendantsOnly === void 0) { directDescendantsOnly = true; }
  19164. return this.getDescendants(directDescendantsOnly, predicate);
  19165. };
  19166. /** @hidden */
  19167. Node.prototype._setReady = function (state) {
  19168. if (state === this._isReady) {
  19169. return;
  19170. }
  19171. if (!state) {
  19172. this._isReady = false;
  19173. return;
  19174. }
  19175. if (this.onReady) {
  19176. this.onReady(this);
  19177. }
  19178. this._isReady = true;
  19179. };
  19180. /**
  19181. * Get an animation by name
  19182. * @param name defines the name of the animation to look for
  19183. * @returns null if not found else the requested animation
  19184. */
  19185. Node.prototype.getAnimationByName = function (name) {
  19186. for (var i = 0; i < this.animations.length; i++) {
  19187. var animation = this.animations[i];
  19188. if (animation.name === name) {
  19189. return animation;
  19190. }
  19191. }
  19192. return null;
  19193. };
  19194. /**
  19195. * Creates an animation range for this node
  19196. * @param name defines the name of the range
  19197. * @param from defines the starting key
  19198. * @param to defines the end key
  19199. */
  19200. Node.prototype.createAnimationRange = function (name, from, to) {
  19201. // check name not already in use
  19202. if (!this._ranges[name]) {
  19203. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  19204. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  19205. if (this.animations[i]) {
  19206. this.animations[i].createRange(name, from, to);
  19207. }
  19208. }
  19209. }
  19210. };
  19211. /**
  19212. * Delete a specific animation range
  19213. * @param name defines the name of the range to delete
  19214. * @param deleteFrames defines if animation frames from the range must be deleted as well
  19215. */
  19216. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  19217. if (deleteFrames === void 0) { deleteFrames = true; }
  19218. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  19219. if (this.animations[i]) {
  19220. this.animations[i].deleteRange(name, deleteFrames);
  19221. }
  19222. }
  19223. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  19224. };
  19225. /**
  19226. * Get an animation range by name
  19227. * @param name defines the name of the animation range to look for
  19228. * @returns null if not found else the requested animation range
  19229. */
  19230. Node.prototype.getAnimationRange = function (name) {
  19231. return this._ranges[name];
  19232. };
  19233. /**
  19234. * Will start the animation sequence
  19235. * @param name defines the range frames for animation sequence
  19236. * @param loop defines if the animation should loop (false by default)
  19237. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  19238. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  19239. * @returns the object created for this animation. If range does not exist, it will return null
  19240. */
  19241. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  19242. var range = this.getAnimationRange(name);
  19243. if (!range) {
  19244. return null;
  19245. }
  19246. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  19247. };
  19248. /**
  19249. * Serialize animation ranges into a JSON compatible object
  19250. * @returns serialization object
  19251. */
  19252. Node.prototype.serializeAnimationRanges = function () {
  19253. var serializationRanges = [];
  19254. for (var name in this._ranges) {
  19255. var localRange = this._ranges[name];
  19256. if (!localRange) {
  19257. continue;
  19258. }
  19259. var range = {};
  19260. range.name = name;
  19261. range.from = localRange.from;
  19262. range.to = localRange.to;
  19263. serializationRanges.push(range);
  19264. }
  19265. return serializationRanges;
  19266. };
  19267. /**
  19268. * Computes the world matrix of the node
  19269. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  19270. * @returns the world matrix
  19271. */
  19272. Node.prototype.computeWorldMatrix = function (force) {
  19273. if (!this._worldMatrix) {
  19274. this._worldMatrix = BABYLON.Matrix.Identity();
  19275. }
  19276. return this._worldMatrix;
  19277. };
  19278. /**
  19279. * Releases resources associated with this node.
  19280. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19281. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19282. */
  19283. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19284. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19285. if (!doNotRecurse) {
  19286. var nodes = this.getDescendants(true);
  19287. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  19288. var node = nodes_1[_i];
  19289. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  19290. }
  19291. }
  19292. else {
  19293. var transformNodes = this.getChildTransformNodes(true);
  19294. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  19295. var transformNode = transformNodes_1[_a];
  19296. transformNode.parent = null;
  19297. transformNode.computeWorldMatrix(true);
  19298. }
  19299. }
  19300. if (!this.parent) {
  19301. this.removeFromSceneRootNodes();
  19302. }
  19303. else {
  19304. this.parent = null;
  19305. }
  19306. // Callback
  19307. this.onDisposeObservable.notifyObservers(this);
  19308. this.onDisposeObservable.clear();
  19309. // Behaviors
  19310. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  19311. var behavior = _c[_b];
  19312. behavior.detach();
  19313. }
  19314. this._behaviors = [];
  19315. this._isDisposed = true;
  19316. };
  19317. /**
  19318. * Parse animation range data from a serialization object and store them into a given node
  19319. * @param node defines where to store the animation ranges
  19320. * @param parsedNode defines the serialization object to read data from
  19321. * @param scene defines the hosting scene
  19322. */
  19323. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  19324. if (parsedNode.ranges) {
  19325. for (var index = 0; index < parsedNode.ranges.length; index++) {
  19326. var data = parsedNode.ranges[index];
  19327. node.createAnimationRange(data.name, data.from, data.to);
  19328. }
  19329. }
  19330. };
  19331. Node._NodeConstructors = {};
  19332. __decorate([
  19333. BABYLON.serialize()
  19334. ], Node.prototype, "name", void 0);
  19335. __decorate([
  19336. BABYLON.serialize()
  19337. ], Node.prototype, "id", void 0);
  19338. __decorate([
  19339. BABYLON.serialize()
  19340. ], Node.prototype, "uniqueId", void 0);
  19341. __decorate([
  19342. BABYLON.serialize()
  19343. ], Node.prototype, "state", void 0);
  19344. __decorate([
  19345. BABYLON.serialize()
  19346. ], Node.prototype, "metadata", void 0);
  19347. return Node;
  19348. }());
  19349. BABYLON.Node = Node;
  19350. })(BABYLON || (BABYLON = {}));
  19351. //# sourceMappingURL=babylon.node.js.map
  19352. var BABYLON;
  19353. (function (BABYLON) {
  19354. /**
  19355. * Class used to store bounding sphere information
  19356. */
  19357. var BoundingSphere = /** @class */ (function () {
  19358. /**
  19359. * Creates a new bounding sphere
  19360. * @param min defines the minimum vector (in local space)
  19361. * @param max defines the maximum vector (in local space)
  19362. * @param worldMatrix defines the new world matrix
  19363. */
  19364. function BoundingSphere(min, max, worldMatrix) {
  19365. /**
  19366. * Gets the center of the bounding sphere in local space
  19367. */
  19368. this.center = BABYLON.Vector3.Zero();
  19369. /**
  19370. * Gets the center of the bounding sphere in world space
  19371. */
  19372. this.centerWorld = BABYLON.Vector3.Zero();
  19373. /**
  19374. * Gets the minimum vector in local space
  19375. */
  19376. this.minimum = BABYLON.Vector3.Zero();
  19377. /**
  19378. * Gets the maximum vector in local space
  19379. */
  19380. this.maximum = BABYLON.Vector3.Zero();
  19381. this.reConstruct(min, max, worldMatrix);
  19382. }
  19383. /**
  19384. * Recreates the entire bounding sphere from scratch as if we call the constructor in place
  19385. * @param min defines the new minimum vector (in local space)
  19386. * @param max defines the new maximum vector (in local space)
  19387. * @param worldMatrix defines the new world matrix
  19388. */
  19389. BoundingSphere.prototype.reConstruct = function (min, max, worldMatrix) {
  19390. this.minimum.copyFrom(min);
  19391. this.maximum.copyFrom(max);
  19392. var distance = BABYLON.Vector3.Distance(min, max);
  19393. max.addToRef(min, this.center).scaleInPlace(0.5);
  19394. this.radius = distance * 0.5;
  19395. this._update(worldMatrix || BABYLON.Matrix.IdentityReadOnly);
  19396. };
  19397. /**
  19398. * Scale the current bounding sphere by applying a scale factor
  19399. * @param factor defines the scale factor to apply
  19400. * @returns the current bounding box
  19401. */
  19402. BoundingSphere.prototype.scale = function (factor) {
  19403. var newRadius = this.radius * factor;
  19404. var tmpVectors = BoundingSphere.TmpVector3;
  19405. var tempRadiusVector = tmpVectors[0].setAll(newRadius);
  19406. var min = this.center.subtractToRef(tempRadiusVector, tmpVectors[1]);
  19407. var max = this.center.addToRef(tempRadiusVector, tmpVectors[2]);
  19408. this.reConstruct(min, max, this._worldMatrix);
  19409. return this;
  19410. };
  19411. /**
  19412. * Gets the world matrix of the bounding box
  19413. * @returns a matrix
  19414. */
  19415. BoundingSphere.prototype.getWorldMatrix = function () {
  19416. return this._worldMatrix;
  19417. };
  19418. // Methods
  19419. /** @hidden */
  19420. BoundingSphere.prototype._update = function (worldMatrix) {
  19421. if (!worldMatrix.isIdentity()) {
  19422. BABYLON.Vector3.TransformCoordinatesToRef(this.center, worldMatrix, this.centerWorld);
  19423. var tempVector = BoundingSphere.TmpVector3[0];
  19424. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, worldMatrix, tempVector);
  19425. this.radiusWorld = Math.max(Math.abs(tempVector.x), Math.abs(tempVector.y), Math.abs(tempVector.z)) * this.radius;
  19426. }
  19427. else {
  19428. this.centerWorld.copyFrom(this.center);
  19429. this.radiusWorld = this.radius;
  19430. }
  19431. };
  19432. /**
  19433. * Tests if the bounding sphere is intersecting the frustum planes
  19434. * @param frustumPlanes defines the frustum planes to test
  19435. * @returns true if there is an intersection
  19436. */
  19437. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  19438. for (var i = 0; i < 6; i++) {
  19439. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld) {
  19440. return false;
  19441. }
  19442. }
  19443. return true;
  19444. };
  19445. /**
  19446. * Tests if a point is inside the bounding sphere
  19447. * @param point defines the point to test
  19448. * @returns true if the point is inside the bounding sphere
  19449. */
  19450. BoundingSphere.prototype.intersectsPoint = function (point) {
  19451. var squareDistance = BABYLON.Vector3.DistanceSquared(this.centerWorld, point);
  19452. if (this.radiusWorld * this.radiusWorld < squareDistance) {
  19453. return false;
  19454. }
  19455. return true;
  19456. };
  19457. // Statics
  19458. /**
  19459. * Checks if two sphere intersct
  19460. * @param sphere0 sphere 0
  19461. * @param sphere1 sphere 1
  19462. * @returns true if the speres intersect
  19463. */
  19464. BoundingSphere.Intersects = function (sphere0, sphere1) {
  19465. var squareDistance = BABYLON.Vector3.DistanceSquared(sphere0.centerWorld, sphere1.centerWorld);
  19466. var radiusSum = sphere0.radiusWorld + sphere1.radiusWorld;
  19467. if (radiusSum * radiusSum < squareDistance) {
  19468. return false;
  19469. }
  19470. return true;
  19471. };
  19472. BoundingSphere.TmpVector3 = BABYLON.Tools.BuildArray(3, BABYLON.Vector3.Zero);
  19473. return BoundingSphere;
  19474. }());
  19475. BABYLON.BoundingSphere = BoundingSphere;
  19476. })(BABYLON || (BABYLON = {}));
  19477. //# sourceMappingURL=babylon.boundingSphere.js.map
  19478. var BABYLON;
  19479. (function (BABYLON) {
  19480. /**
  19481. * Class used to store bounding box information
  19482. */
  19483. var BoundingBox = /** @class */ (function () {
  19484. /**
  19485. * Creates a new bounding box
  19486. * @param min defines the minimum vector (in local space)
  19487. * @param max defines the maximum vector (in local space)
  19488. * @param worldMatrix defines the new world matrix
  19489. */
  19490. function BoundingBox(min, max, worldMatrix) {
  19491. /**
  19492. * Gets the 8 vectors representing the bounding box in local space
  19493. */
  19494. this.vectors = BABYLON.Tools.BuildArray(8, BABYLON.Vector3.Zero);
  19495. /**
  19496. * Gets the center of the bounding box in local space
  19497. */
  19498. this.center = BABYLON.Vector3.Zero();
  19499. /**
  19500. * Gets the center of the bounding box in world space
  19501. */
  19502. this.centerWorld = BABYLON.Vector3.Zero();
  19503. /**
  19504. * Gets the extend size in local space
  19505. */
  19506. this.extendSize = BABYLON.Vector3.Zero();
  19507. /**
  19508. * Gets the extend size in world space
  19509. */
  19510. this.extendSizeWorld = BABYLON.Vector3.Zero();
  19511. /**
  19512. * Gets the OBB (object bounding box) directions
  19513. */
  19514. this.directions = BABYLON.Tools.BuildArray(3, BABYLON.Vector3.Zero);
  19515. /**
  19516. * Gets the 8 vectors representing the bounding box in world space
  19517. */
  19518. this.vectorsWorld = BABYLON.Tools.BuildArray(8, BABYLON.Vector3.Zero);
  19519. /**
  19520. * Gets the minimum vector in world space
  19521. */
  19522. this.minimumWorld = BABYLON.Vector3.Zero();
  19523. /**
  19524. * Gets the maximum vector in world space
  19525. */
  19526. this.maximumWorld = BABYLON.Vector3.Zero();
  19527. /**
  19528. * Gets the minimum vector in local space
  19529. */
  19530. this.minimum = BABYLON.Vector3.Zero();
  19531. /**
  19532. * Gets the maximum vector in local space
  19533. */
  19534. this.maximum = BABYLON.Vector3.Zero();
  19535. this.reConstruct(min, max, worldMatrix);
  19536. }
  19537. // Methods
  19538. /**
  19539. * Recreates the entire bounding box from scratch as if we call the constructor in place
  19540. * @param min defines the new minimum vector (in local space)
  19541. * @param max defines the new maximum vector (in local space)
  19542. * @param worldMatrix defines the new world matrix
  19543. */
  19544. BoundingBox.prototype.reConstruct = function (min, max, worldMatrix) {
  19545. var minX = min.x, minY = min.y, minZ = min.z, maxX = max.x, maxY = max.y, maxZ = max.z;
  19546. var vectors = this.vectors;
  19547. this.minimum.copyFromFloats(minX, minY, minZ);
  19548. this.maximum.copyFromFloats(maxX, maxY, maxZ);
  19549. vectors[0].copyFromFloats(minX, minY, minZ);
  19550. vectors[1].copyFromFloats(maxX, maxY, maxZ);
  19551. vectors[2].copyFromFloats(maxX, minY, minZ);
  19552. vectors[3].copyFromFloats(minX, maxY, minZ);
  19553. vectors[4].copyFromFloats(minX, minY, maxZ);
  19554. vectors[5].copyFromFloats(maxX, maxY, minZ);
  19555. vectors[6].copyFromFloats(minX, maxY, maxZ);
  19556. vectors[7].copyFromFloats(maxX, minY, maxZ);
  19557. // OBB
  19558. max.addToRef(min, this.center).scaleInPlace(0.5);
  19559. max.subtractToRef(min, this.extendSize).scaleInPlace(0.5);
  19560. this._update(worldMatrix || BABYLON.Matrix.IdentityReadOnly);
  19561. };
  19562. /**
  19563. * Scale the current bounding box by applying a scale factor
  19564. * @param factor defines the scale factor to apply
  19565. * @returns the current bounding box
  19566. */
  19567. BoundingBox.prototype.scale = function (factor) {
  19568. var tmpVectors = BoundingBox.TmpVector3;
  19569. var diff = this.maximum.subtractToRef(this.minimum, tmpVectors[0]);
  19570. var len = diff.length();
  19571. diff.normalizeFromLength(len);
  19572. var distance = len * factor;
  19573. var newRadius = diff.scaleInPlace(distance * 0.5);
  19574. var min = this.center.subtractToRef(newRadius, tmpVectors[1]);
  19575. var max = this.center.addToRef(newRadius, tmpVectors[2]);
  19576. this.reConstruct(min, max, this._worldMatrix);
  19577. return this;
  19578. };
  19579. /**
  19580. * Gets the world matrix of the bounding box
  19581. * @returns a matrix
  19582. */
  19583. BoundingBox.prototype.getWorldMatrix = function () {
  19584. return this._worldMatrix;
  19585. };
  19586. /** @hidden */
  19587. BoundingBox.prototype._update = function (world) {
  19588. var minWorld = this.minimumWorld;
  19589. var maxWorld = this.maximumWorld;
  19590. var directions = this.directions;
  19591. var vectorsWorld = this.vectorsWorld;
  19592. var vectors = this.vectors;
  19593. if (!world.isIdentity()) {
  19594. minWorld.setAll(Number.MAX_VALUE);
  19595. maxWorld.setAll(-Number.MAX_VALUE);
  19596. for (var index = 0; index < 8; ++index) {
  19597. var v = vectorsWorld[index];
  19598. BABYLON.Vector3.TransformCoordinatesToRef(vectors[index], world, v);
  19599. minWorld.minimizeInPlace(v);
  19600. maxWorld.maximizeInPlace(v);
  19601. }
  19602. // Extend
  19603. maxWorld.subtractToRef(minWorld, this.extendSizeWorld).scaleInPlace(0.5);
  19604. maxWorld.addToRef(minWorld, this.centerWorld).scaleInPlace(0.5);
  19605. }
  19606. else {
  19607. minWorld.copyFrom(this.minimum);
  19608. maxWorld.copyFrom(this.maximum);
  19609. for (var index = 0; index < 8; ++index) {
  19610. vectorsWorld[index].copyFrom(vectors[index]);
  19611. }
  19612. // Extend
  19613. this.extendSizeWorld.copyFrom(this.extendSize);
  19614. this.centerWorld.copyFrom(this.center);
  19615. }
  19616. BABYLON.Vector3.FromArrayToRef(world.m, 0, directions[0]);
  19617. BABYLON.Vector3.FromArrayToRef(world.m, 4, directions[1]);
  19618. BABYLON.Vector3.FromArrayToRef(world.m, 8, directions[2]);
  19619. this._worldMatrix = world;
  19620. };
  19621. /**
  19622. * Tests if the bounding box is intersecting the frustum planes
  19623. * @param frustumPlanes defines the frustum planes to test
  19624. * @returns true if there is an intersection
  19625. */
  19626. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  19627. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  19628. };
  19629. /**
  19630. * Tests if the bounding box is entirely inside the frustum planes
  19631. * @param frustumPlanes defines the frustum planes to test
  19632. * @returns true if there is an inclusion
  19633. */
  19634. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  19635. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  19636. };
  19637. /**
  19638. * Tests if a point is inside the bounding box
  19639. * @param point defines the point to test
  19640. * @returns true if the point is inside the bounding box
  19641. */
  19642. BoundingBox.prototype.intersectsPoint = function (point) {
  19643. var min = this.minimumWorld;
  19644. var max = this.maximumWorld;
  19645. var minX = min.x, minY = min.y, minZ = min.z, maxX = max.x, maxY = max.y, maxZ = max.z;
  19646. var pointX = point.x, pointY = point.y, pointZ = point.z;
  19647. var delta = -BABYLON.Epsilon;
  19648. if (maxX - pointX < delta || delta > pointX - minX) {
  19649. return false;
  19650. }
  19651. if (maxY - pointY < delta || delta > pointY - minY) {
  19652. return false;
  19653. }
  19654. if (maxZ - pointZ < delta || delta > pointZ - minZ) {
  19655. return false;
  19656. }
  19657. return true;
  19658. };
  19659. /**
  19660. * Tests if the bounding box intersects with a bounding sphere
  19661. * @param sphere defines the sphere to test
  19662. * @returns true if there is an intersection
  19663. */
  19664. BoundingBox.prototype.intersectsSphere = function (sphere) {
  19665. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  19666. };
  19667. /**
  19668. * Tests if the bounding box intersects with a box defined by a min and max vectors
  19669. * @param min defines the min vector to use
  19670. * @param max defines the max vector to use
  19671. * @returns true if there is an intersection
  19672. */
  19673. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  19674. var myMin = this.minimumWorld;
  19675. var myMax = this.maximumWorld;
  19676. var myMinX = myMin.x, myMinY = myMin.y, myMinZ = myMin.z, myMaxX = myMax.x, myMaxY = myMax.y, myMaxZ = myMax.z;
  19677. var minX = min.x, minY = min.y, minZ = min.z, maxX = max.x, maxY = max.y, maxZ = max.z;
  19678. if (myMaxX < minX || myMinX > maxX) {
  19679. return false;
  19680. }
  19681. if (myMaxY < minY || myMinY > maxY) {
  19682. return false;
  19683. }
  19684. if (myMaxZ < minZ || myMinZ > maxZ) {
  19685. return false;
  19686. }
  19687. return true;
  19688. };
  19689. // Statics
  19690. /**
  19691. * Tests if two bounding boxes are intersections
  19692. * @param box0 defines the first box to test
  19693. * @param box1 defines the second box to test
  19694. * @returns true if there is an intersection
  19695. */
  19696. BoundingBox.Intersects = function (box0, box1) {
  19697. return box0.intersectsMinMax(box1.minimumWorld, box1.maximumWorld);
  19698. };
  19699. /**
  19700. * Tests if a bounding box defines by a min/max vectors intersects a sphere
  19701. * @param minPoint defines the minimum vector of the bounding box
  19702. * @param maxPoint defines the maximum vector of the bounding box
  19703. * @param sphereCenter defines the sphere center
  19704. * @param sphereRadius defines the sphere radius
  19705. * @returns true if there is an intersection
  19706. */
  19707. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  19708. var vector = BoundingBox.TmpVector3[0];
  19709. BABYLON.Vector3.ClampToRef(sphereCenter, minPoint, maxPoint, vector);
  19710. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  19711. return (num <= (sphereRadius * sphereRadius));
  19712. };
  19713. /**
  19714. * Tests if a bounding box defined with 8 vectors is entirely inside frustum planes
  19715. * @param boundingVectors defines an array of 8 vectors representing a bounding box
  19716. * @param frustumPlanes defines the frustum planes to test
  19717. * @return true if there is an inclusion
  19718. */
  19719. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  19720. for (var p = 0; p < 6; ++p) {
  19721. var frustumPlane = frustumPlanes[p];
  19722. for (var i = 0; i < 8; ++i) {
  19723. if (frustumPlane.dotCoordinate(boundingVectors[i]) < 0) {
  19724. return false;
  19725. }
  19726. }
  19727. }
  19728. return true;
  19729. };
  19730. /**
  19731. * Tests if a bounding box defined with 8 vectors intersects frustum planes
  19732. * @param boundingVectors defines an array of 8 vectors representing a bounding box
  19733. * @param frustumPlanes defines the frustum planes to test
  19734. * @return true if there is an intersection
  19735. */
  19736. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  19737. for (var p = 0; p < 6; ++p) {
  19738. var canReturnFalse = true;
  19739. var frustumPlane = frustumPlanes[p];
  19740. for (var i = 0; i < 8; ++i) {
  19741. if (frustumPlane.dotCoordinate(boundingVectors[i]) >= 0) {
  19742. canReturnFalse = false;
  19743. break;
  19744. }
  19745. }
  19746. if (canReturnFalse) {
  19747. return false;
  19748. }
  19749. }
  19750. return true;
  19751. };
  19752. BoundingBox.TmpVector3 = BABYLON.Tools.BuildArray(3, BABYLON.Vector3.Zero);
  19753. return BoundingBox;
  19754. }());
  19755. BABYLON.BoundingBox = BoundingBox;
  19756. })(BABYLON || (BABYLON = {}));
  19757. //# sourceMappingURL=babylon.boundingBox.js.map
  19758. var BABYLON;
  19759. (function (BABYLON) {
  19760. var _result0 = { min: 0, max: 0 };
  19761. var _result1 = { min: 0, max: 0 };
  19762. var computeBoxExtents = function (axis, box, result) {
  19763. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  19764. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  19765. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  19766. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  19767. var r = r0 + r1 + r2;
  19768. result.min = p - r;
  19769. result.max = p + r;
  19770. };
  19771. var axisOverlap = function (axis, box0, box1) {
  19772. computeBoxExtents(axis, box0, _result0);
  19773. computeBoxExtents(axis, box1, _result1);
  19774. return !(_result0.min > _result1.max || _result1.min > _result0.max);
  19775. };
  19776. /**
  19777. * Info for a bounding data of a mesh
  19778. */
  19779. var BoundingInfo = /** @class */ (function () {
  19780. /**
  19781. * Constructs bounding info
  19782. * @param minimum min vector of the bounding box/sphere
  19783. * @param maximum max vector of the bounding box/sphere
  19784. * @param worldMatrix defines the new world matrix
  19785. */
  19786. function BoundingInfo(minimum, maximum, worldMatrix) {
  19787. this._isLocked = false;
  19788. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum, worldMatrix);
  19789. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum, worldMatrix);
  19790. }
  19791. /**
  19792. * Recreates the entire bounding info from scratch as if we call the constructor in place
  19793. * @param min defines the new minimum vector (in local space)
  19794. * @param max defines the new maximum vector (in local space)
  19795. * @param worldMatrix defines the new world matrix
  19796. */
  19797. BoundingInfo.prototype.reConstruct = function (min, max, worldMatrix) {
  19798. this.boundingBox.reConstruct(min, max, worldMatrix);
  19799. this.boundingSphere.reConstruct(min, max, worldMatrix);
  19800. };
  19801. Object.defineProperty(BoundingInfo.prototype, "minimum", {
  19802. /**
  19803. * min vector of the bounding box/sphere
  19804. */
  19805. get: function () {
  19806. return this.boundingBox.minimum;
  19807. },
  19808. enumerable: true,
  19809. configurable: true
  19810. });
  19811. Object.defineProperty(BoundingInfo.prototype, "maximum", {
  19812. /**
  19813. * max vector of the bounding box/sphere
  19814. */
  19815. get: function () {
  19816. return this.boundingBox.maximum;
  19817. },
  19818. enumerable: true,
  19819. configurable: true
  19820. });
  19821. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  19822. /**
  19823. * If the info is locked and won't be updated to avoid perf overhead
  19824. */
  19825. get: function () {
  19826. return this._isLocked;
  19827. },
  19828. set: function (value) {
  19829. this._isLocked = value;
  19830. },
  19831. enumerable: true,
  19832. configurable: true
  19833. });
  19834. // Methods
  19835. /**
  19836. * Updates the bounding sphere and box
  19837. * @param world world matrix to be used to update
  19838. */
  19839. BoundingInfo.prototype.update = function (world) {
  19840. if (this._isLocked) {
  19841. return;
  19842. }
  19843. this.boundingBox._update(world);
  19844. this.boundingSphere._update(world);
  19845. };
  19846. /**
  19847. * Recreate the bounding info to be centered around a specific point given a specific extend.
  19848. * @param center New center of the bounding info
  19849. * @param extend New extend of the bounding info
  19850. * @returns the current bounding info
  19851. */
  19852. BoundingInfo.prototype.centerOn = function (center, extend) {
  19853. var minimum = BoundingInfo.TmpVector3[0].copyFrom(center).subtractInPlace(extend);
  19854. var maximum = BoundingInfo.TmpVector3[1].copyFrom(center).addInPlace(extend);
  19855. this.boundingBox.reConstruct(minimum, maximum, this.boundingBox.getWorldMatrix());
  19856. this.boundingSphere.reConstruct(minimum, maximum, this.boundingBox.getWorldMatrix());
  19857. return this;
  19858. };
  19859. /**
  19860. * Scale the current bounding info by applying a scale factor
  19861. * @param factor defines the scale factor to apply
  19862. * @returns the current bounding info
  19863. */
  19864. BoundingInfo.prototype.scale = function (factor) {
  19865. this.boundingBox.scale(factor);
  19866. this.boundingSphere.scale(factor);
  19867. return this;
  19868. };
  19869. /**
  19870. * Returns `true` if the bounding info is within the frustum defined by the passed array of planes.
  19871. * @param frustumPlanes defines the frustum to test
  19872. * @param strategy defines the strategy to use for the culling (default is BABYLON.Scene.CULLINGSTRATEGY_STANDARD)
  19873. * @returns true if the bounding info is in the frustum planes
  19874. */
  19875. BoundingInfo.prototype.isInFrustum = function (frustumPlanes, strategy) {
  19876. if (strategy === void 0) { strategy = BABYLON.AbstractMesh.CULLINGSTRATEGY_STANDARD; }
  19877. if (!this.boundingSphere.isInFrustum(frustumPlanes)) {
  19878. return false;
  19879. }
  19880. if (strategy === BABYLON.AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY) {
  19881. return true;
  19882. }
  19883. return this.boundingBox.isInFrustum(frustumPlanes);
  19884. };
  19885. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  19886. /**
  19887. * Gets the world distance between the min and max points of the bounding box
  19888. */
  19889. get: function () {
  19890. var boundingBox = this.boundingBox;
  19891. var diag = boundingBox.maximumWorld.subtractToRef(boundingBox.minimumWorld, BoundingInfo.TmpVector3[0]);
  19892. return diag.length();
  19893. },
  19894. enumerable: true,
  19895. configurable: true
  19896. });
  19897. /**
  19898. * Checks if a cullable object (mesh...) is in the camera frustum
  19899. * Unlike isInFrustum this cheks the full bounding box
  19900. * @param frustumPlanes Camera near/planes
  19901. * @returns true if the object is in frustum otherwise false
  19902. */
  19903. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  19904. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  19905. };
  19906. /** @hidden */
  19907. BoundingInfo.prototype._checkCollision = function (collider) {
  19908. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  19909. };
  19910. /**
  19911. * Checks if a point is inside the bounding box and bounding sphere or the mesh
  19912. * @see https://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  19913. * @param point the point to check intersection with
  19914. * @returns if the point intersects
  19915. */
  19916. BoundingInfo.prototype.intersectsPoint = function (point) {
  19917. if (!this.boundingSphere.centerWorld) {
  19918. return false;
  19919. }
  19920. if (!this.boundingSphere.intersectsPoint(point)) {
  19921. return false;
  19922. }
  19923. if (!this.boundingBox.intersectsPoint(point)) {
  19924. return false;
  19925. }
  19926. return true;
  19927. };
  19928. /**
  19929. * Checks if another bounding info intersects the bounding box and bounding sphere or the mesh
  19930. * @see https://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  19931. * @param boundingInfo the bounding info to check intersection with
  19932. * @param precise if the intersection should be done using OBB
  19933. * @returns if the bounding info intersects
  19934. */
  19935. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  19936. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  19937. return false;
  19938. }
  19939. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  19940. return false;
  19941. }
  19942. if (!precise) {
  19943. return true;
  19944. }
  19945. var box0 = this.boundingBox;
  19946. var box1 = boundingInfo.boundingBox;
  19947. if (!axisOverlap(box0.directions[0], box0, box1)) {
  19948. return false;
  19949. }
  19950. if (!axisOverlap(box0.directions[1], box0, box1)) {
  19951. return false;
  19952. }
  19953. if (!axisOverlap(box0.directions[2], box0, box1)) {
  19954. return false;
  19955. }
  19956. if (!axisOverlap(box1.directions[0], box0, box1)) {
  19957. return false;
  19958. }
  19959. if (!axisOverlap(box1.directions[1], box0, box1)) {
  19960. return false;
  19961. }
  19962. if (!axisOverlap(box1.directions[2], box0, box1)) {
  19963. return false;
  19964. }
  19965. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1)) {
  19966. return false;
  19967. }
  19968. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1)) {
  19969. return false;
  19970. }
  19971. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1)) {
  19972. return false;
  19973. }
  19974. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1)) {
  19975. return false;
  19976. }
  19977. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1)) {
  19978. return false;
  19979. }
  19980. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1)) {
  19981. return false;
  19982. }
  19983. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1)) {
  19984. return false;
  19985. }
  19986. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1)) {
  19987. return false;
  19988. }
  19989. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1)) {
  19990. return false;
  19991. }
  19992. return true;
  19993. };
  19994. BoundingInfo.TmpVector3 = BABYLON.Tools.BuildArray(2, BABYLON.Vector3.Zero);
  19995. return BoundingInfo;
  19996. }());
  19997. BABYLON.BoundingInfo = BoundingInfo;
  19998. })(BABYLON || (BABYLON = {}));
  19999. //# sourceMappingURL=babylon.boundingInfo.js.map
  20000. var BABYLON;
  20001. (function (BABYLON) {
  20002. /**
  20003. * A TransformNode is an object that is not rendered but can be used as a center of transformation. This can decrease memory usage and increase rendering speed compared to using an empty mesh as a parent and is less complicated than using a pivot matrix.
  20004. * @see https://doc.babylonjs.com/how_to/transformnode
  20005. */
  20006. var TransformNode = /** @class */ (function (_super) {
  20007. __extends(TransformNode, _super);
  20008. function TransformNode(name, scene, isPure) {
  20009. if (scene === void 0) { scene = null; }
  20010. if (isPure === void 0) { isPure = true; }
  20011. var _this = _super.call(this, name, scene) || this;
  20012. _this._forward = new BABYLON.Vector3(0, 0, 1);
  20013. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  20014. _this._up = new BABYLON.Vector3(0, 1, 0);
  20015. _this._right = new BABYLON.Vector3(1, 0, 0);
  20016. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  20017. // Properties
  20018. _this._position = BABYLON.Vector3.Zero();
  20019. _this._rotation = BABYLON.Vector3.Zero();
  20020. _this._scaling = BABYLON.Vector3.One();
  20021. _this._isDirty = false;
  20022. /**
  20023. * Set the billboard mode. Default is 0.
  20024. *
  20025. * | Value | Type | Description |
  20026. * | --- | --- | --- |
  20027. * | 0 | BILLBOARDMODE_NONE | |
  20028. * | 1 | BILLBOARDMODE_X | |
  20029. * | 2 | BILLBOARDMODE_Y | |
  20030. * | 4 | BILLBOARDMODE_Z | |
  20031. * | 7 | BILLBOARDMODE_ALL | |
  20032. *
  20033. */
  20034. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  20035. /**
  20036. * Multiplication factor on scale x/y/z when computing the world matrix. Eg. for a 1x1x1 cube setting this to 2 will make it a 2x2x2 cube
  20037. */
  20038. _this.scalingDeterminant = 1;
  20039. /**
  20040. * Sets the distance of the object to max, often used by skybox
  20041. */
  20042. _this.infiniteDistance = false;
  20043. /**
  20044. * Gets or sets a boolean indicating that non uniform scaling (when at least one component is different from others) should be ignored.
  20045. * By default the system will update normals to compensate
  20046. */
  20047. _this.ignoreNonUniformScaling = false;
  20048. _this._localWorld = BABYLON.Matrix.Zero();
  20049. _this._absolutePosition = BABYLON.Vector3.Zero();
  20050. _this._pivotMatrix = BABYLON.Matrix.Identity();
  20051. _this._postMultiplyPivotMatrix = false;
  20052. _this._isWorldMatrixFrozen = false;
  20053. /** @hidden */
  20054. _this._indexInSceneTransformNodesArray = -1;
  20055. /**
  20056. * An event triggered after the world matrix is updated
  20057. */
  20058. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  20059. _this._nonUniformScaling = false;
  20060. if (isPure) {
  20061. _this.getScene().addTransformNode(_this);
  20062. }
  20063. return _this;
  20064. }
  20065. /**
  20066. * Gets a string identifying the name of the class
  20067. * @returns "TransformNode" string
  20068. */
  20069. TransformNode.prototype.getClassName = function () {
  20070. return "TransformNode";
  20071. };
  20072. Object.defineProperty(TransformNode.prototype, "position", {
  20073. /**
  20074. * Gets or set the node position (default is (0.0, 0.0, 0.0))
  20075. */
  20076. get: function () {
  20077. return this._position;
  20078. },
  20079. set: function (newPosition) {
  20080. this._position = newPosition;
  20081. this._isDirty = true;
  20082. },
  20083. enumerable: true,
  20084. configurable: true
  20085. });
  20086. Object.defineProperty(TransformNode.prototype, "rotation", {
  20087. /**
  20088. * 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)).
  20089. * If rotation quaternion is set, this Vector3 will be ignored and copy from the quaternion
  20090. */
  20091. get: function () {
  20092. return this._rotation;
  20093. },
  20094. set: function (newRotation) {
  20095. this._rotation = newRotation;
  20096. this._isDirty = true;
  20097. },
  20098. enumerable: true,
  20099. configurable: true
  20100. });
  20101. Object.defineProperty(TransformNode.prototype, "scaling", {
  20102. /**
  20103. * 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)).
  20104. */
  20105. get: function () {
  20106. return this._scaling;
  20107. },
  20108. set: function (newScaling) {
  20109. this._scaling = newScaling;
  20110. this._isDirty = true;
  20111. },
  20112. enumerable: true,
  20113. configurable: true
  20114. });
  20115. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  20116. /**
  20117. * Gets or sets the rotation Quaternion property : this a Quaternion object defining the node rotation by using a unit quaternion (null by default).
  20118. * If set, only the rotationQuaternion is then used to compute the node rotation (ie. node.rotation will be ignored)
  20119. */
  20120. get: function () {
  20121. return this._rotationQuaternion;
  20122. },
  20123. set: function (quaternion) {
  20124. this._rotationQuaternion = quaternion;
  20125. //reset the rotation vector.
  20126. if (quaternion) {
  20127. this.rotation.setAll(0.0);
  20128. }
  20129. },
  20130. enumerable: true,
  20131. configurable: true
  20132. });
  20133. Object.defineProperty(TransformNode.prototype, "forward", {
  20134. /**
  20135. * The forward direction of that transform in world space.
  20136. */
  20137. get: function () {
  20138. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  20139. },
  20140. enumerable: true,
  20141. configurable: true
  20142. });
  20143. Object.defineProperty(TransformNode.prototype, "up", {
  20144. /**
  20145. * The up direction of that transform in world space.
  20146. */
  20147. get: function () {
  20148. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  20149. },
  20150. enumerable: true,
  20151. configurable: true
  20152. });
  20153. Object.defineProperty(TransformNode.prototype, "right", {
  20154. /**
  20155. * The right direction of that transform in world space.
  20156. */
  20157. get: function () {
  20158. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  20159. },
  20160. enumerable: true,
  20161. configurable: true
  20162. });
  20163. /**
  20164. * Copies the parameter passed Matrix into the mesh Pose matrix.
  20165. * @param matrix the matrix to copy the pose from
  20166. * @returns this TransformNode.
  20167. */
  20168. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  20169. this._poseMatrix.copyFrom(matrix);
  20170. return this;
  20171. };
  20172. /**
  20173. * Returns the mesh Pose matrix.
  20174. * @returns the pose matrix
  20175. */
  20176. TransformNode.prototype.getPoseMatrix = function () {
  20177. return this._poseMatrix;
  20178. };
  20179. /** @hidden */
  20180. TransformNode.prototype._isSynchronized = function () {
  20181. if (this._isDirty) {
  20182. return false;
  20183. }
  20184. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  20185. return false;
  20186. }
  20187. if (this._cache.pivotMatrixUpdated) {
  20188. return false;
  20189. }
  20190. if (this.infiniteDistance) {
  20191. return false;
  20192. }
  20193. if (!this._cache.position.equals(this._position)) {
  20194. return false;
  20195. }
  20196. if (this._rotationQuaternion) {
  20197. if (!this._cache.rotationQuaternion.equals(this._rotationQuaternion)) {
  20198. return false;
  20199. }
  20200. }
  20201. if (!this._cache.rotation.equals(this._rotation)) {
  20202. return false;
  20203. }
  20204. if (!this._cache.scaling.equals(this._scaling)) {
  20205. return false;
  20206. }
  20207. return true;
  20208. };
  20209. /** @hidden */
  20210. TransformNode.prototype._initCache = function () {
  20211. _super.prototype._initCache.call(this);
  20212. this._cache.localMatrixUpdated = false;
  20213. this._cache.position = BABYLON.Vector3.Zero();
  20214. this._cache.scaling = BABYLON.Vector3.Zero();
  20215. this._cache.rotation = BABYLON.Vector3.Zero();
  20216. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  20217. this._cache.billboardMode = -1;
  20218. };
  20219. /**
  20220. * Flag the transform node as dirty (Forcing it to update everything)
  20221. * @param property if set to "rotation" the objects rotationQuaternion will be set to null
  20222. * @returns this transform node
  20223. */
  20224. TransformNode.prototype.markAsDirty = function (property) {
  20225. if (property === "rotation") {
  20226. this.rotationQuaternion = null;
  20227. }
  20228. this._currentRenderId = Number.MAX_VALUE;
  20229. this._isDirty = true;
  20230. return this;
  20231. };
  20232. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  20233. /**
  20234. * Returns the current mesh absolute position.
  20235. * Returns a Vector3.
  20236. */
  20237. get: function () {
  20238. return this._absolutePosition;
  20239. },
  20240. enumerable: true,
  20241. configurable: true
  20242. });
  20243. /**
  20244. * Sets a new matrix to apply before all other transformation
  20245. * @param matrix defines the transform matrix
  20246. * @returns the current TransformNode
  20247. */
  20248. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  20249. return this.setPivotMatrix(matrix, false);
  20250. };
  20251. /**
  20252. * Sets a new pivot matrix to the current node
  20253. * @param matrix defines the new pivot matrix to use
  20254. * @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
  20255. * @returns the current TransformNode
  20256. */
  20257. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  20258. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  20259. this._pivotMatrix.copyFrom(matrix);
  20260. this._cache.pivotMatrixUpdated = true;
  20261. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  20262. if (this._postMultiplyPivotMatrix) {
  20263. if (!this._pivotMatrixInverse) {
  20264. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  20265. }
  20266. else {
  20267. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  20268. }
  20269. }
  20270. return this;
  20271. };
  20272. /**
  20273. * Returns the mesh pivot matrix.
  20274. * Default : Identity.
  20275. * @returns the matrix
  20276. */
  20277. TransformNode.prototype.getPivotMatrix = function () {
  20278. return this._pivotMatrix;
  20279. };
  20280. /**
  20281. * Prevents the World matrix to be computed any longer.
  20282. * @returns the TransformNode.
  20283. */
  20284. TransformNode.prototype.freezeWorldMatrix = function () {
  20285. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  20286. this.computeWorldMatrix(true);
  20287. this._isWorldMatrixFrozen = true;
  20288. return this;
  20289. };
  20290. /**
  20291. * Allows back the World matrix computation.
  20292. * @returns the TransformNode.
  20293. */
  20294. TransformNode.prototype.unfreezeWorldMatrix = function () {
  20295. this._isWorldMatrixFrozen = false;
  20296. this.computeWorldMatrix(true);
  20297. return this;
  20298. };
  20299. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  20300. /**
  20301. * True if the World matrix has been frozen.
  20302. */
  20303. get: function () {
  20304. return this._isWorldMatrixFrozen;
  20305. },
  20306. enumerable: true,
  20307. configurable: true
  20308. });
  20309. /**
  20310. * Retuns the mesh absolute position in the World.
  20311. * @returns a Vector3.
  20312. */
  20313. TransformNode.prototype.getAbsolutePosition = function () {
  20314. this.computeWorldMatrix();
  20315. return this._absolutePosition;
  20316. };
  20317. /**
  20318. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  20319. * @param absolutePosition the absolute position to set
  20320. * @returns the TransformNode.
  20321. */
  20322. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  20323. if (!absolutePosition) {
  20324. return this;
  20325. }
  20326. var absolutePositionX;
  20327. var absolutePositionY;
  20328. var absolutePositionZ;
  20329. if (absolutePosition.x === undefined) {
  20330. if (arguments.length < 3) {
  20331. return this;
  20332. }
  20333. absolutePositionX = arguments[0];
  20334. absolutePositionY = arguments[1];
  20335. absolutePositionZ = arguments[2];
  20336. }
  20337. else {
  20338. absolutePositionX = absolutePosition.x;
  20339. absolutePositionY = absolutePosition.y;
  20340. absolutePositionZ = absolutePosition.z;
  20341. }
  20342. if (this.parent) {
  20343. var invertParentWorldMatrix = BABYLON.Tmp.Matrix[0];
  20344. this.parent.getWorldMatrix().invertToRef(invertParentWorldMatrix);
  20345. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(absolutePositionX, absolutePositionY, absolutePositionZ, invertParentWorldMatrix, this.position);
  20346. }
  20347. else {
  20348. this.position.x = absolutePositionX;
  20349. this.position.y = absolutePositionY;
  20350. this.position.z = absolutePositionZ;
  20351. }
  20352. return this;
  20353. };
  20354. /**
  20355. * Sets the mesh position in its local space.
  20356. * @param vector3 the position to set in localspace
  20357. * @returns the TransformNode.
  20358. */
  20359. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  20360. this.computeWorldMatrix();
  20361. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  20362. return this;
  20363. };
  20364. /**
  20365. * Returns the mesh position in the local space from the current World matrix values.
  20366. * @returns a new Vector3.
  20367. */
  20368. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  20369. this.computeWorldMatrix();
  20370. var invLocalWorldMatrix = BABYLON.Tmp.Matrix[0];
  20371. this._localWorld.invertToRef(invLocalWorldMatrix);
  20372. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  20373. };
  20374. /**
  20375. * Translates the mesh along the passed Vector3 in its local space.
  20376. * @param vector3 the distance to translate in localspace
  20377. * @returns the TransformNode.
  20378. */
  20379. TransformNode.prototype.locallyTranslate = function (vector3) {
  20380. this.computeWorldMatrix(true);
  20381. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  20382. return this;
  20383. };
  20384. /**
  20385. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  20386. * @param targetPoint the position (must be in same space as current mesh) to look at
  20387. * @param yawCor optional yaw (y-axis) correction in radians
  20388. * @param pitchCor optional pitch (x-axis) correction in radians
  20389. * @param rollCor optional roll (z-axis) correction in radians
  20390. * @param space the choosen space of the target
  20391. * @returns the TransformNode.
  20392. */
  20393. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  20394. if (yawCor === void 0) { yawCor = 0; }
  20395. if (pitchCor === void 0) { pitchCor = 0; }
  20396. if (rollCor === void 0) { rollCor = 0; }
  20397. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  20398. var dv = TransformNode._lookAtVectorCache;
  20399. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  20400. targetPoint.subtractToRef(pos, dv);
  20401. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  20402. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  20403. var pitch = Math.atan2(dv.y, len);
  20404. if (this.rotationQuaternion) {
  20405. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  20406. }
  20407. else {
  20408. this.rotation.x = pitch + pitchCor;
  20409. this.rotation.y = yaw + yawCor;
  20410. this.rotation.z = rollCor;
  20411. }
  20412. return this;
  20413. };
  20414. /**
  20415. * Returns a new Vector3 that is the localAxis, expressed in the mesh local space, rotated like the mesh.
  20416. * This Vector3 is expressed in the World space.
  20417. * @param localAxis axis to rotate
  20418. * @returns a new Vector3 that is the localAxis, expressed in the mesh local space, rotated like the mesh.
  20419. */
  20420. TransformNode.prototype.getDirection = function (localAxis) {
  20421. var result = BABYLON.Vector3.Zero();
  20422. this.getDirectionToRef(localAxis, result);
  20423. return result;
  20424. };
  20425. /**
  20426. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  20427. * localAxis is expressed in the mesh local space.
  20428. * result is computed in the Wordl space from the mesh World matrix.
  20429. * @param localAxis axis to rotate
  20430. * @param result the resulting transformnode
  20431. * @returns this TransformNode.
  20432. */
  20433. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  20434. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  20435. return this;
  20436. };
  20437. /**
  20438. * Sets a new pivot point to the current node
  20439. * @param point defines the new pivot point to use
  20440. * @param space defines if the point is in world or local space (local by default)
  20441. * @returns the current TransformNode
  20442. */
  20443. TransformNode.prototype.setPivotPoint = function (point, space) {
  20444. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  20445. if (this.getScene().getRenderId() == 0) {
  20446. this.computeWorldMatrix(true);
  20447. }
  20448. var wm = this.getWorldMatrix();
  20449. if (space == BABYLON.Space.WORLD) {
  20450. var tmat = BABYLON.Tmp.Matrix[0];
  20451. wm.invertToRef(tmat);
  20452. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  20453. }
  20454. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  20455. };
  20456. /**
  20457. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  20458. * @returns the pivot point
  20459. */
  20460. TransformNode.prototype.getPivotPoint = function () {
  20461. var point = BABYLON.Vector3.Zero();
  20462. this.getPivotPointToRef(point);
  20463. return point;
  20464. };
  20465. /**
  20466. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  20467. * @param result the vector3 to store the result
  20468. * @returns this TransformNode.
  20469. */
  20470. TransformNode.prototype.getPivotPointToRef = function (result) {
  20471. result.x = -this._pivotMatrix.m[12];
  20472. result.y = -this._pivotMatrix.m[13];
  20473. result.z = -this._pivotMatrix.m[14];
  20474. return this;
  20475. };
  20476. /**
  20477. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  20478. * @returns a new Vector3 set with the mesh pivot point World coordinates.
  20479. */
  20480. TransformNode.prototype.getAbsolutePivotPoint = function () {
  20481. var point = BABYLON.Vector3.Zero();
  20482. this.getAbsolutePivotPointToRef(point);
  20483. return point;
  20484. };
  20485. /**
  20486. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  20487. * @param result vector3 to store the result
  20488. * @returns this TransformNode.
  20489. */
  20490. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  20491. result.x = this._pivotMatrix.m[12];
  20492. result.y = this._pivotMatrix.m[13];
  20493. result.z = this._pivotMatrix.m[14];
  20494. this.getPivotPointToRef(result);
  20495. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  20496. return this;
  20497. };
  20498. /**
  20499. * Defines the passed node as the parent of the current node.
  20500. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  20501. * @param node the node ot set as the parent
  20502. * @returns this TransformNode.
  20503. */
  20504. TransformNode.prototype.setParent = function (node) {
  20505. if (!node && !this.parent) {
  20506. return this;
  20507. }
  20508. var quatRotation = BABYLON.Tmp.Quaternion[0];
  20509. var position = BABYLON.Tmp.Vector3[0];
  20510. var scale = BABYLON.Tmp.Vector3[1];
  20511. if (!node) {
  20512. if (this.parent && this.parent.computeWorldMatrix) {
  20513. this.parent.computeWorldMatrix(true);
  20514. }
  20515. this.computeWorldMatrix(true);
  20516. this.getWorldMatrix().decompose(scale, quatRotation, position);
  20517. }
  20518. else {
  20519. var diffMatrix = BABYLON.Tmp.Matrix[0];
  20520. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  20521. this.computeWorldMatrix(true);
  20522. node.computeWorldMatrix(true);
  20523. node.getWorldMatrix().invertToRef(invParentMatrix);
  20524. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  20525. diffMatrix.decompose(scale, quatRotation, position);
  20526. }
  20527. if (this.rotationQuaternion) {
  20528. this.rotationQuaternion.copyFrom(quatRotation);
  20529. }
  20530. else {
  20531. quatRotation.toEulerAnglesToRef(this.rotation);
  20532. }
  20533. this.scaling.copyFrom(scale);
  20534. this.position.copyFrom(position);
  20535. this.parent = node;
  20536. return this;
  20537. };
  20538. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  20539. /**
  20540. * True if the scaling property of this object is non uniform eg. (1,2,1)
  20541. */
  20542. get: function () {
  20543. return this._nonUniformScaling;
  20544. },
  20545. enumerable: true,
  20546. configurable: true
  20547. });
  20548. /** @hidden */
  20549. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  20550. if (this._nonUniformScaling === value) {
  20551. return false;
  20552. }
  20553. this._nonUniformScaling = value;
  20554. return true;
  20555. };
  20556. /**
  20557. * Attach the current TransformNode to another TransformNode associated with a bone
  20558. * @param bone Bone affecting the TransformNode
  20559. * @param affectedTransformNode TransformNode associated with the bone
  20560. * @returns this object
  20561. */
  20562. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  20563. this._transformToBoneReferal = affectedTransformNode;
  20564. this.parent = bone;
  20565. if (bone.getWorldMatrix().determinant() < 0) {
  20566. this.scalingDeterminant *= -1;
  20567. }
  20568. return this;
  20569. };
  20570. /**
  20571. * Detach the transform node if its associated with a bone
  20572. * @returns this object
  20573. */
  20574. TransformNode.prototype.detachFromBone = function () {
  20575. if (!this.parent) {
  20576. return this;
  20577. }
  20578. if (this.parent.getWorldMatrix().determinant() < 0) {
  20579. this.scalingDeterminant *= -1;
  20580. }
  20581. this._transformToBoneReferal = null;
  20582. this.parent = null;
  20583. return this;
  20584. };
  20585. /**
  20586. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  20587. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  20588. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  20589. * The passed axis is also normalized.
  20590. * @param axis the axis to rotate around
  20591. * @param amount the amount to rotate in radians
  20592. * @param space Space to rotate in (Default: local)
  20593. * @returns the TransformNode.
  20594. */
  20595. TransformNode.prototype.rotate = function (axis, amount, space) {
  20596. axis.normalize();
  20597. if (!this.rotationQuaternion) {
  20598. this.rotationQuaternion = this.rotation.toQuaternion();
  20599. this.rotation.setAll(0);
  20600. }
  20601. var rotationQuaternion;
  20602. if (!space || space === BABYLON.Space.LOCAL) {
  20603. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  20604. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  20605. }
  20606. else {
  20607. if (this.parent) {
  20608. var invertParentWorldMatrix = BABYLON.Tmp.Matrix[0];
  20609. this.parent.getWorldMatrix().invertToRef(invertParentWorldMatrix);
  20610. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  20611. }
  20612. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  20613. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  20614. }
  20615. return this;
  20616. };
  20617. /**
  20618. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  20619. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  20620. * The passed axis is also normalized. .
  20621. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  20622. * @param point the point to rotate around
  20623. * @param axis the axis to rotate around
  20624. * @param amount the amount to rotate in radians
  20625. * @returns the TransformNode
  20626. */
  20627. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  20628. axis.normalize();
  20629. if (!this.rotationQuaternion) {
  20630. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  20631. this.rotation.setAll(0);
  20632. }
  20633. var tmpVector = BABYLON.Tmp.Vector3[0];
  20634. var finalScale = BABYLON.Tmp.Vector3[1];
  20635. var finalTranslation = BABYLON.Tmp.Vector3[2];
  20636. var finalRotation = BABYLON.Tmp.Quaternion[0];
  20637. var translationMatrix = BABYLON.Tmp.Matrix[0]; // T
  20638. var translationMatrixInv = BABYLON.Tmp.Matrix[1]; // T'
  20639. var rotationMatrix = BABYLON.Tmp.Matrix[2]; // R
  20640. var finalMatrix = BABYLON.Tmp.Matrix[3]; // T' x R x T
  20641. point.subtractToRef(this.position, tmpVector);
  20642. BABYLON.Matrix.TranslationToRef(tmpVector.x, tmpVector.y, tmpVector.z, translationMatrix); // T
  20643. BABYLON.Matrix.TranslationToRef(-tmpVector.x, -tmpVector.y, -tmpVector.z, translationMatrixInv); // T'
  20644. BABYLON.Matrix.RotationAxisToRef(axis, amount, rotationMatrix); // R
  20645. translationMatrixInv.multiplyToRef(rotationMatrix, finalMatrix); // T' x R
  20646. finalMatrix.multiplyToRef(translationMatrix, finalMatrix); // T' x R x T
  20647. finalMatrix.decompose(finalScale, finalRotation, finalTranslation);
  20648. this.position.addInPlace(finalTranslation);
  20649. finalRotation.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  20650. return this;
  20651. };
  20652. /**
  20653. * Translates the mesh along the axis vector for the passed distance in the given space.
  20654. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  20655. * @param axis the axis to translate in
  20656. * @param distance the distance to translate
  20657. * @param space Space to rotate in (Default: local)
  20658. * @returns the TransformNode.
  20659. */
  20660. TransformNode.prototype.translate = function (axis, distance, space) {
  20661. var displacementVector = axis.scale(distance);
  20662. if (!space || space === BABYLON.Space.LOCAL) {
  20663. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  20664. this.setPositionWithLocalVector(tempV3);
  20665. }
  20666. else {
  20667. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  20668. }
  20669. return this;
  20670. };
  20671. /**
  20672. * Adds a rotation step to the mesh current rotation.
  20673. * x, y, z are Euler angles expressed in radians.
  20674. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  20675. * This means this rotation is made in the mesh local space only.
  20676. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  20677. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  20678. * ```javascript
  20679. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  20680. * ```
  20681. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  20682. * 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.
  20683. * @param x Rotation to add
  20684. * @param y Rotation to add
  20685. * @param z Rotation to add
  20686. * @returns the TransformNode.
  20687. */
  20688. TransformNode.prototype.addRotation = function (x, y, z) {
  20689. var rotationQuaternion;
  20690. if (this.rotationQuaternion) {
  20691. rotationQuaternion = this.rotationQuaternion;
  20692. }
  20693. else {
  20694. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  20695. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  20696. }
  20697. var accumulation = BABYLON.Tmp.Quaternion[0];
  20698. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  20699. rotationQuaternion.multiplyInPlace(accumulation);
  20700. if (!this.rotationQuaternion) {
  20701. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  20702. }
  20703. return this;
  20704. };
  20705. /**
  20706. * Computes the world matrix of the node
  20707. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  20708. * @returns the world matrix
  20709. */
  20710. TransformNode.prototype.computeWorldMatrix = function (force) {
  20711. if (this._isWorldMatrixFrozen) {
  20712. return this._worldMatrix;
  20713. }
  20714. if (!force && this.isSynchronized()) {
  20715. this._currentRenderId = this.getScene().getRenderId();
  20716. return this._worldMatrix;
  20717. }
  20718. this._updateCache();
  20719. this._cache.position.copyFrom(this.position);
  20720. this._cache.scaling.copyFrom(this.scaling);
  20721. this._cache.pivotMatrixUpdated = false;
  20722. this._cache.billboardMode = this.billboardMode;
  20723. this._currentRenderId = this.getScene().getRenderId();
  20724. this._childRenderId = this.getScene().getRenderId();
  20725. this._isDirty = false;
  20726. // Scaling
  20727. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  20728. // Rotation
  20729. //rotate, if quaternion is set and rotation was used
  20730. if (this.rotationQuaternion) {
  20731. var len = this.rotation.length();
  20732. if (len) {
  20733. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  20734. this.rotation.copyFromFloats(0, 0, 0);
  20735. }
  20736. }
  20737. if (this.rotationQuaternion) {
  20738. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  20739. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  20740. }
  20741. else {
  20742. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  20743. this._cache.rotation.copyFrom(this.rotation);
  20744. }
  20745. // Translation
  20746. var camera = this.getScene().activeCamera;
  20747. if (this.infiniteDistance && !this.parent && camera) {
  20748. var cameraWorldMatrix = camera.getWorldMatrix();
  20749. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  20750. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  20751. }
  20752. else {
  20753. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  20754. }
  20755. // Composing transformations
  20756. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  20757. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  20758. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  20759. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  20760. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  20761. // Need to decompose each rotation here
  20762. var currentPosition = BABYLON.Tmp.Vector3[3];
  20763. if (this.parent && this.parent.getWorldMatrix) {
  20764. if (this._transformToBoneReferal) {
  20765. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  20766. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  20767. }
  20768. else {
  20769. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  20770. }
  20771. }
  20772. else {
  20773. currentPosition.copyFrom(this.position);
  20774. }
  20775. currentPosition.subtractInPlace(camera.globalPosition);
  20776. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  20777. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  20778. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  20779. }
  20780. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  20781. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  20782. }
  20783. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  20784. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  20785. }
  20786. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  20787. }
  20788. else {
  20789. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  20790. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  20791. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  20792. }
  20793. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  20794. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  20795. }
  20796. // Post multiply inverse of pivotMatrix
  20797. if (this._postMultiplyPivotMatrix) {
  20798. BABYLON.Tmp.Matrix[5].multiplyToRef(this._pivotMatrixInverse, BABYLON.Tmp.Matrix[5]);
  20799. }
  20800. // Local world
  20801. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  20802. // Parent
  20803. if (this.parent && this.parent.getWorldMatrix) {
  20804. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  20805. if (this._transformToBoneReferal) {
  20806. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  20807. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  20808. }
  20809. else {
  20810. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  20811. }
  20812. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  20813. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  20814. this._worldMatrix.copyFrom(this._localWorld);
  20815. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  20816. }
  20817. else {
  20818. if (this._transformToBoneReferal) {
  20819. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  20820. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  20821. }
  20822. else {
  20823. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  20824. }
  20825. }
  20826. this._markSyncedWithParent();
  20827. }
  20828. else {
  20829. this._worldMatrix.copyFrom(this._localWorld);
  20830. }
  20831. // Normal matrix
  20832. if (!this.ignoreNonUniformScaling) {
  20833. if (this.scaling.isNonUniform) {
  20834. this._updateNonUniformScalingState(true);
  20835. }
  20836. else if (this.parent && this.parent._nonUniformScaling) {
  20837. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  20838. }
  20839. else {
  20840. this._updateNonUniformScalingState(false);
  20841. }
  20842. }
  20843. else {
  20844. this._updateNonUniformScalingState(false);
  20845. }
  20846. this._afterComputeWorldMatrix();
  20847. // Absolute position
  20848. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  20849. // Callbacks
  20850. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  20851. if (!this._poseMatrix) {
  20852. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  20853. }
  20854. // Cache the determinant
  20855. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  20856. return this._worldMatrix;
  20857. };
  20858. TransformNode.prototype._afterComputeWorldMatrix = function () {
  20859. };
  20860. /**
  20861. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  20862. * @param func callback function to add
  20863. *
  20864. * @returns the TransformNode.
  20865. */
  20866. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  20867. this.onAfterWorldMatrixUpdateObservable.add(func);
  20868. return this;
  20869. };
  20870. /**
  20871. * Removes a registered callback function.
  20872. * @param func callback function to remove
  20873. * @returns the TransformNode.
  20874. */
  20875. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  20876. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  20877. return this;
  20878. };
  20879. /**
  20880. * Gets the position of the current mesh in camera space
  20881. * @param camera defines the camera to use
  20882. * @returns a position
  20883. */
  20884. TransformNode.prototype.getPositionInCameraSpace = function (camera) {
  20885. if (camera === void 0) { camera = null; }
  20886. if (!camera) {
  20887. camera = this.getScene().activeCamera;
  20888. }
  20889. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  20890. };
  20891. /**
  20892. * Returns the distance from the mesh to the active camera
  20893. * @param camera defines the camera to use
  20894. * @returns the distance
  20895. */
  20896. TransformNode.prototype.getDistanceToCamera = function (camera) {
  20897. if (camera === void 0) { camera = null; }
  20898. if (!camera) {
  20899. camera = this.getScene().activeCamera;
  20900. }
  20901. return this.absolutePosition.subtract(camera.position).length();
  20902. };
  20903. /**
  20904. * Clone the current transform node
  20905. * @param name Name of the new clone
  20906. * @param newParent New parent for the clone
  20907. * @param doNotCloneChildren Do not clone children hierarchy
  20908. * @returns the new transform node
  20909. */
  20910. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  20911. var _this = this;
  20912. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  20913. result.name = name;
  20914. result.id = name;
  20915. if (newParent) {
  20916. result.parent = newParent;
  20917. }
  20918. if (!doNotCloneChildren) {
  20919. // Children
  20920. var directDescendants = this.getDescendants(true);
  20921. for (var index = 0; index < directDescendants.length; index++) {
  20922. var child = directDescendants[index];
  20923. if (child.clone) {
  20924. child.clone(name + "." + child.name, result);
  20925. }
  20926. }
  20927. }
  20928. return result;
  20929. };
  20930. /**
  20931. * Serializes the objects information.
  20932. * @param currentSerializationObject defines the object to serialize in
  20933. * @returns the serialized object
  20934. */
  20935. TransformNode.prototype.serialize = function (currentSerializationObject) {
  20936. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  20937. serializationObject.type = this.getClassName();
  20938. // Parent
  20939. if (this.parent) {
  20940. serializationObject.parentId = this.parent.id;
  20941. }
  20942. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  20943. serializationObject.tags = BABYLON.Tags.GetTags(this);
  20944. }
  20945. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  20946. serializationObject.isEnabled = this.isEnabled();
  20947. // Parent
  20948. if (this.parent) {
  20949. serializationObject.parentId = this.parent.id;
  20950. }
  20951. return serializationObject;
  20952. };
  20953. // Statics
  20954. /**
  20955. * Returns a new TransformNode object parsed from the source provided.
  20956. * @param parsedTransformNode is the source.
  20957. * @param scene the scne the object belongs to
  20958. * @param rootUrl is a string, it's the root URL to prefix the `delayLoadingFile` property with
  20959. * @returns a new TransformNode object parsed from the source provided.
  20960. */
  20961. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  20962. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  20963. if (BABYLON.Tags) {
  20964. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  20965. }
  20966. if (parsedTransformNode.localMatrix) {
  20967. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  20968. }
  20969. else if (parsedTransformNode.pivotMatrix) {
  20970. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  20971. }
  20972. transformNode.setEnabled(parsedTransformNode.isEnabled);
  20973. // Parent
  20974. if (parsedTransformNode.parentId) {
  20975. transformNode._waitingParentId = parsedTransformNode.parentId;
  20976. }
  20977. return transformNode;
  20978. };
  20979. /**
  20980. * Releases resources associated with this transform node.
  20981. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20982. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20983. */
  20984. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20985. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20986. // Animations
  20987. this.getScene().stopAnimation(this);
  20988. // Remove from scene
  20989. this.getScene().removeTransformNode(this);
  20990. this.onAfterWorldMatrixUpdateObservable.clear();
  20991. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20992. };
  20993. // Statics
  20994. /**
  20995. * Object will not rotate to face the camera
  20996. */
  20997. TransformNode.BILLBOARDMODE_NONE = 0;
  20998. /**
  20999. * Object will rotate to face the camera but only on the x axis
  21000. */
  21001. TransformNode.BILLBOARDMODE_X = 1;
  21002. /**
  21003. * Object will rotate to face the camera but only on the y axis
  21004. */
  21005. TransformNode.BILLBOARDMODE_Y = 2;
  21006. /**
  21007. * Object will rotate to face the camera but only on the z axis
  21008. */
  21009. TransformNode.BILLBOARDMODE_Z = 4;
  21010. /**
  21011. * Object will rotate to face the camera
  21012. */
  21013. TransformNode.BILLBOARDMODE_ALL = 7;
  21014. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  21015. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  21016. __decorate([
  21017. BABYLON.serializeAsVector3("position")
  21018. ], TransformNode.prototype, "_position", void 0);
  21019. __decorate([
  21020. BABYLON.serializeAsVector3("rotation")
  21021. ], TransformNode.prototype, "_rotation", void 0);
  21022. __decorate([
  21023. BABYLON.serializeAsQuaternion("rotationQuaternion")
  21024. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  21025. __decorate([
  21026. BABYLON.serializeAsVector3("scaling")
  21027. ], TransformNode.prototype, "_scaling", void 0);
  21028. __decorate([
  21029. BABYLON.serialize()
  21030. ], TransformNode.prototype, "billboardMode", void 0);
  21031. __decorate([
  21032. BABYLON.serialize()
  21033. ], TransformNode.prototype, "scalingDeterminant", void 0);
  21034. __decorate([
  21035. BABYLON.serialize()
  21036. ], TransformNode.prototype, "infiniteDistance", void 0);
  21037. __decorate([
  21038. BABYLON.serialize()
  21039. ], TransformNode.prototype, "ignoreNonUniformScaling", void 0);
  21040. return TransformNode;
  21041. }(BABYLON.Node));
  21042. BABYLON.TransformNode = TransformNode;
  21043. })(BABYLON || (BABYLON = {}));
  21044. //# sourceMappingURL=babylon.transformNode.js.map
  21045. var BABYLON;
  21046. (function (BABYLON) {
  21047. /** @hidden */
  21048. var _FacetDataStorage = /** @class */ (function () {
  21049. function _FacetDataStorage() {
  21050. this.facetNb = 0; // facet number
  21051. this.partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  21052. this.partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  21053. this.facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  21054. this.facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  21055. this.bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  21056. this.subDiv = {
  21057. max: 1,
  21058. X: 1,
  21059. Y: 1,
  21060. Z: 1
  21061. };
  21062. this.facetDepthSort = false; // is the facet depth sort to be computed
  21063. this.facetDepthSortEnabled = false; // is the facet depth sort initialized
  21064. }
  21065. return _FacetDataStorage;
  21066. }());
  21067. /**
  21068. * Class used to store all common mesh properties
  21069. */
  21070. var AbstractMesh = /** @class */ (function (_super) {
  21071. __extends(AbstractMesh, _super);
  21072. // Constructor
  21073. /**
  21074. * Creates a new AbstractMesh
  21075. * @param name defines the name of the mesh
  21076. * @param scene defines the hosting scene
  21077. */
  21078. function AbstractMesh(name, scene) {
  21079. if (scene === void 0) { scene = null; }
  21080. var _this = _super.call(this, name, scene, false) || this;
  21081. _this._facetData = new _FacetDataStorage();
  21082. /** Gets ot sets the culling strategy to use to find visible meshes */
  21083. _this.cullingStrategy = AbstractMesh.CULLINGSTRATEGY_STANDARD;
  21084. // Events
  21085. /**
  21086. * An event triggered when this mesh collides with another one
  21087. */
  21088. _this.onCollideObservable = new BABYLON.Observable();
  21089. /**
  21090. * An event triggered when the collision's position changes
  21091. */
  21092. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  21093. /**
  21094. * An event triggered when material is changed
  21095. */
  21096. _this.onMaterialChangedObservable = new BABYLON.Observable();
  21097. // Properties
  21098. /**
  21099. * Gets or sets the orientation for POV movement & rotation
  21100. */
  21101. _this.definedFacingForward = true;
  21102. _this._visibility = 1.0;
  21103. /** Gets or sets the alpha index used to sort transparent meshes
  21104. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index
  21105. */
  21106. _this.alphaIndex = Number.MAX_VALUE;
  21107. /**
  21108. * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true
  21109. */
  21110. _this.isVisible = true;
  21111. /**
  21112. * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true
  21113. */
  21114. _this.isPickable = true;
  21115. /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */
  21116. _this.showSubMeshesBoundingBox = false;
  21117. /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default)
  21118. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  21119. */
  21120. _this.isBlocker = false;
  21121. /**
  21122. * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default)
  21123. */
  21124. _this.enablePointerMoveEvents = false;
  21125. /**
  21126. * Specifies the rendering group id for this mesh (0 by default)
  21127. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups
  21128. */
  21129. _this.renderingGroupId = 0;
  21130. _this._receiveShadows = false;
  21131. /** Defines color to use when rendering outline */
  21132. _this.outlineColor = BABYLON.Color3.Red();
  21133. /** Define width to use when rendering outline */
  21134. _this.outlineWidth = 0.02;
  21135. /** Defines color to use when rendering overlay */
  21136. _this.overlayColor = BABYLON.Color3.Red();
  21137. /** Defines alpha to use when rendering overlay */
  21138. _this.overlayAlpha = 0.5;
  21139. _this._hasVertexAlpha = false;
  21140. _this._useVertexColors = true;
  21141. _this._computeBonesUsingShaders = true;
  21142. _this._numBoneInfluencers = 4;
  21143. _this._applyFog = true;
  21144. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */
  21145. _this.useOctreeForRenderingSelection = true;
  21146. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */
  21147. _this.useOctreeForPicking = true;
  21148. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */
  21149. _this.useOctreeForCollisions = true;
  21150. _this._layerMask = 0x0FFFFFFF;
  21151. /**
  21152. * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase)
  21153. */
  21154. _this.alwaysSelectAsActiveMesh = false;
  21155. /**
  21156. * Gets or sets the current action manager
  21157. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  21158. */
  21159. _this.actionManager = null;
  21160. // Collisions
  21161. _this._checkCollisions = false;
  21162. _this._collisionMask = -1;
  21163. _this._collisionGroup = -1;
  21164. /**
  21165. * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5))
  21166. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  21167. */
  21168. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  21169. /**
  21170. * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0))
  21171. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  21172. */
  21173. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  21174. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  21175. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  21176. // Edges
  21177. /**
  21178. * Defines edge width used when edgesRenderer is enabled
  21179. * @see https://www.babylonjs-playground.com/#10OJSG#13
  21180. */
  21181. _this.edgesWidth = 1;
  21182. /**
  21183. * Defines edge color used when edgesRenderer is enabled
  21184. * @see https://www.babylonjs-playground.com/#10OJSG#13
  21185. */
  21186. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  21187. /** @hidden */
  21188. _this._renderId = 0;
  21189. /** @hidden */
  21190. _this._intersectionsInProgress = new Array();
  21191. /** @hidden */
  21192. _this._unIndexed = false;
  21193. /** @hidden */
  21194. _this._lightSources = new Array();
  21195. /**
  21196. * An event triggered when the mesh is rebuilt.
  21197. */
  21198. _this.onRebuildObservable = new BABYLON.Observable();
  21199. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  21200. if (collidedMesh === void 0) { collidedMesh = null; }
  21201. //TODO move this to the collision coordinator!
  21202. if (_this.getScene().workerCollisions) {
  21203. newPosition.multiplyInPlace(_this._collider._radius);
  21204. }
  21205. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  21206. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  21207. _this.position.addInPlace(_this._diffPositionForCollisions);
  21208. }
  21209. if (collidedMesh) {
  21210. _this.onCollideObservable.notifyObservers(collidedMesh);
  21211. }
  21212. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  21213. };
  21214. _this.getScene().addMesh(_this);
  21215. _this._resyncLightSources();
  21216. return _this;
  21217. }
  21218. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  21219. /**
  21220. * No billboard
  21221. */
  21222. get: function () {
  21223. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  21224. },
  21225. enumerable: true,
  21226. configurable: true
  21227. });
  21228. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  21229. /** Billboard on X axis */
  21230. get: function () {
  21231. return BABYLON.TransformNode.BILLBOARDMODE_X;
  21232. },
  21233. enumerable: true,
  21234. configurable: true
  21235. });
  21236. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  21237. /** Billboard on Y axis */
  21238. get: function () {
  21239. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  21240. },
  21241. enumerable: true,
  21242. configurable: true
  21243. });
  21244. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  21245. /** Billboard on Z axis */
  21246. get: function () {
  21247. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  21248. },
  21249. enumerable: true,
  21250. configurable: true
  21251. });
  21252. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  21253. /** Billboard on all axes */
  21254. get: function () {
  21255. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  21256. },
  21257. enumerable: true,
  21258. configurable: true
  21259. });
  21260. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  21261. /**
  21262. * Gets the number of facets in the mesh
  21263. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  21264. */
  21265. get: function () {
  21266. return this._facetData.facetNb;
  21267. },
  21268. enumerable: true,
  21269. configurable: true
  21270. });
  21271. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  21272. /**
  21273. * Gets or set the number (integer) of subdivisions per axis in the partioning space
  21274. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  21275. */
  21276. get: function () {
  21277. return this._facetData.partitioningSubdivisions;
  21278. },
  21279. set: function (nb) {
  21280. this._facetData.partitioningSubdivisions = nb;
  21281. },
  21282. enumerable: true,
  21283. configurable: true
  21284. });
  21285. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  21286. /**
  21287. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  21288. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box
  21289. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  21290. */
  21291. get: function () {
  21292. return this._facetData.partitioningBBoxRatio;
  21293. },
  21294. set: function (ratio) {
  21295. this._facetData.partitioningBBoxRatio = ratio;
  21296. },
  21297. enumerable: true,
  21298. configurable: true
  21299. });
  21300. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  21301. /**
  21302. * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`.
  21303. * Works only for updatable meshes.
  21304. * Doesn't work with multi-materials
  21305. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  21306. */
  21307. get: function () {
  21308. return this._facetData.facetDepthSort;
  21309. },
  21310. set: function (sort) {
  21311. this._facetData.facetDepthSort = sort;
  21312. },
  21313. enumerable: true,
  21314. configurable: true
  21315. });
  21316. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  21317. /**
  21318. * The location (Vector3) where the facet depth sort must be computed from.
  21319. * By default, the active camera position.
  21320. * Used only when facet depth sort is enabled
  21321. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  21322. */
  21323. get: function () {
  21324. return this._facetData.facetDepthSortFrom;
  21325. },
  21326. set: function (location) {
  21327. this._facetData.facetDepthSortFrom = location;
  21328. },
  21329. enumerable: true,
  21330. configurable: true
  21331. });
  21332. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  21333. /**
  21334. * gets a boolean indicating if facetData is enabled
  21335. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  21336. */
  21337. get: function () {
  21338. return this._facetData.facetDataEnabled;
  21339. },
  21340. enumerable: true,
  21341. configurable: true
  21342. });
  21343. /** @hidden */
  21344. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  21345. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  21346. return false;
  21347. }
  21348. this._markSubMeshesAsMiscDirty();
  21349. return true;
  21350. };
  21351. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  21352. /** Set a function to call when this mesh collides with another one */
  21353. set: function (callback) {
  21354. if (this._onCollideObserver) {
  21355. this.onCollideObservable.remove(this._onCollideObserver);
  21356. }
  21357. this._onCollideObserver = this.onCollideObservable.add(callback);
  21358. },
  21359. enumerable: true,
  21360. configurable: true
  21361. });
  21362. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  21363. /** Set a function to call when the collision's position changes */
  21364. set: function (callback) {
  21365. if (this._onCollisionPositionChangeObserver) {
  21366. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  21367. }
  21368. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  21369. },
  21370. enumerable: true,
  21371. configurable: true
  21372. });
  21373. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  21374. /**
  21375. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  21376. */
  21377. get: function () {
  21378. return this._visibility;
  21379. },
  21380. /**
  21381. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  21382. */
  21383. set: function (value) {
  21384. if (this._visibility === value) {
  21385. return;
  21386. }
  21387. this._visibility = value;
  21388. this._markSubMeshesAsMiscDirty();
  21389. },
  21390. enumerable: true,
  21391. configurable: true
  21392. });
  21393. Object.defineProperty(AbstractMesh.prototype, "material", {
  21394. /** Gets or sets current material */
  21395. get: function () {
  21396. return this._material;
  21397. },
  21398. set: function (value) {
  21399. if (this._material === value) {
  21400. return;
  21401. }
  21402. // remove from material mesh map id needed
  21403. if (this._material && this._material.meshMap) {
  21404. this._material.meshMap[this.uniqueId] = undefined;
  21405. }
  21406. this._material = value;
  21407. if (value && value.meshMap) {
  21408. value.meshMap[this.uniqueId] = this;
  21409. }
  21410. if (this.onMaterialChangedObservable.hasObservers) {
  21411. this.onMaterialChangedObservable.notifyObservers(this);
  21412. }
  21413. if (!this.subMeshes) {
  21414. return;
  21415. }
  21416. this._unBindEffect();
  21417. },
  21418. enumerable: true,
  21419. configurable: true
  21420. });
  21421. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  21422. /**
  21423. * Gets or sets a boolean indicating that this mesh can receive realtime shadows
  21424. * @see http://doc.babylonjs.com/babylon101/shadows
  21425. */
  21426. get: function () {
  21427. return this._receiveShadows;
  21428. },
  21429. set: function (value) {
  21430. if (this._receiveShadows === value) {
  21431. return;
  21432. }
  21433. this._receiveShadows = value;
  21434. this._markSubMeshesAsLightDirty();
  21435. },
  21436. enumerable: true,
  21437. configurable: true
  21438. });
  21439. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  21440. /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */
  21441. get: function () {
  21442. return this._hasVertexAlpha;
  21443. },
  21444. set: function (value) {
  21445. if (this._hasVertexAlpha === value) {
  21446. return;
  21447. }
  21448. this._hasVertexAlpha = value;
  21449. this._markSubMeshesAsAttributesDirty();
  21450. this._markSubMeshesAsMiscDirty();
  21451. },
  21452. enumerable: true,
  21453. configurable: true
  21454. });
  21455. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  21456. /** 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) */
  21457. get: function () {
  21458. return this._useVertexColors;
  21459. },
  21460. set: function (value) {
  21461. if (this._useVertexColors === value) {
  21462. return;
  21463. }
  21464. this._useVertexColors = value;
  21465. this._markSubMeshesAsAttributesDirty();
  21466. },
  21467. enumerable: true,
  21468. configurable: true
  21469. });
  21470. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  21471. /**
  21472. * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default)
  21473. */
  21474. get: function () {
  21475. return this._computeBonesUsingShaders;
  21476. },
  21477. set: function (value) {
  21478. if (this._computeBonesUsingShaders === value) {
  21479. return;
  21480. }
  21481. this._computeBonesUsingShaders = value;
  21482. this._markSubMeshesAsAttributesDirty();
  21483. },
  21484. enumerable: true,
  21485. configurable: true
  21486. });
  21487. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  21488. /** Gets or sets the number of allowed bone influences per vertex (4 by default) */
  21489. get: function () {
  21490. return this._numBoneInfluencers;
  21491. },
  21492. set: function (value) {
  21493. if (this._numBoneInfluencers === value) {
  21494. return;
  21495. }
  21496. this._numBoneInfluencers = value;
  21497. this._markSubMeshesAsAttributesDirty();
  21498. },
  21499. enumerable: true,
  21500. configurable: true
  21501. });
  21502. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  21503. /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */
  21504. get: function () {
  21505. return this._applyFog;
  21506. },
  21507. set: function (value) {
  21508. if (this._applyFog === value) {
  21509. return;
  21510. }
  21511. this._applyFog = value;
  21512. this._markSubMeshesAsMiscDirty();
  21513. },
  21514. enumerable: true,
  21515. configurable: true
  21516. });
  21517. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  21518. /**
  21519. * Gets or sets the current layer mask (default is 0x0FFFFFFF)
  21520. * @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures
  21521. */
  21522. get: function () {
  21523. return this._layerMask;
  21524. },
  21525. set: function (value) {
  21526. if (value === this._layerMask) {
  21527. return;
  21528. }
  21529. this._layerMask = value;
  21530. this._resyncLightSources();
  21531. },
  21532. enumerable: true,
  21533. configurable: true
  21534. });
  21535. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  21536. /**
  21537. * Gets or sets a collision mask used to mask collisions (default is -1).
  21538. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  21539. */
  21540. get: function () {
  21541. return this._collisionMask;
  21542. },
  21543. set: function (mask) {
  21544. this._collisionMask = !isNaN(mask) ? mask : -1;
  21545. },
  21546. enumerable: true,
  21547. configurable: true
  21548. });
  21549. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  21550. /**
  21551. * Gets or sets the current collision group mask (-1 by default).
  21552. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  21553. */
  21554. get: function () {
  21555. return this._collisionGroup;
  21556. },
  21557. set: function (mask) {
  21558. this._collisionGroup = !isNaN(mask) ? mask : -1;
  21559. },
  21560. enumerable: true,
  21561. configurable: true
  21562. });
  21563. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  21564. /** @hidden */
  21565. get: function () {
  21566. return null;
  21567. },
  21568. enumerable: true,
  21569. configurable: true
  21570. });
  21571. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  21572. get: function () {
  21573. return this._skeleton;
  21574. },
  21575. /**
  21576. * Gets or sets a skeleton to apply skining transformations
  21577. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  21578. */
  21579. set: function (value) {
  21580. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  21581. this._skeleton._unregisterMeshWithPoseMatrix(this);
  21582. }
  21583. if (value && value.needInitialSkinMatrix) {
  21584. value._registerMeshWithPoseMatrix(this);
  21585. }
  21586. this._skeleton = value;
  21587. if (!this._skeleton) {
  21588. this._bonesTransformMatrices = null;
  21589. }
  21590. this._markSubMeshesAsAttributesDirty();
  21591. },
  21592. enumerable: true,
  21593. configurable: true
  21594. });
  21595. /**
  21596. * Returns the string "AbstractMesh"
  21597. * @returns "AbstractMesh"
  21598. */
  21599. AbstractMesh.prototype.getClassName = function () {
  21600. return "AbstractMesh";
  21601. };
  21602. /**
  21603. * Gets a string representation of the current mesh
  21604. * @param fullDetails defines a boolean indicating if full details must be included
  21605. * @returns a string representation of the current mesh
  21606. */
  21607. AbstractMesh.prototype.toString = function (fullDetails) {
  21608. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  21609. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  21610. if (this._skeleton) {
  21611. ret += ", skeleton: " + this._skeleton.name;
  21612. }
  21613. if (fullDetails) {
  21614. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  21615. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  21616. }
  21617. return ret;
  21618. };
  21619. /** @hidden */
  21620. AbstractMesh.prototype._rebuild = function () {
  21621. this.onRebuildObservable.notifyObservers(this);
  21622. if (this._occlusionQuery) {
  21623. this._occlusionQuery = null;
  21624. }
  21625. if (!this.subMeshes) {
  21626. return;
  21627. }
  21628. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  21629. var subMesh = _a[_i];
  21630. subMesh._rebuild();
  21631. }
  21632. };
  21633. /** @hidden */
  21634. AbstractMesh.prototype._resyncLightSources = function () {
  21635. this._lightSources.length = 0;
  21636. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  21637. var light = _a[_i];
  21638. if (!light.isEnabled()) {
  21639. continue;
  21640. }
  21641. if (light.canAffectMesh(this)) {
  21642. this._lightSources.push(light);
  21643. }
  21644. }
  21645. this._markSubMeshesAsLightDirty();
  21646. };
  21647. /** @hidden */
  21648. AbstractMesh.prototype._resyncLighSource = function (light) {
  21649. var isIn = light.isEnabled() && light.canAffectMesh(this);
  21650. var index = this._lightSources.indexOf(light);
  21651. if (index === -1) {
  21652. if (!isIn) {
  21653. return;
  21654. }
  21655. this._lightSources.push(light);
  21656. }
  21657. else {
  21658. if (isIn) {
  21659. return;
  21660. }
  21661. this._lightSources.splice(index, 1);
  21662. }
  21663. this._markSubMeshesAsLightDirty();
  21664. };
  21665. /** @hidden */
  21666. AbstractMesh.prototype._unBindEffect = function () {
  21667. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  21668. var subMesh = _a[_i];
  21669. subMesh.setEffect(null);
  21670. }
  21671. };
  21672. /** @hidden */
  21673. AbstractMesh.prototype._removeLightSource = function (light) {
  21674. var index = this._lightSources.indexOf(light);
  21675. if (index === -1) {
  21676. return;
  21677. }
  21678. this._lightSources.splice(index, 1);
  21679. this._markSubMeshesAsLightDirty();
  21680. };
  21681. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  21682. if (!this.subMeshes) {
  21683. return;
  21684. }
  21685. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  21686. var subMesh = _a[_i];
  21687. if (subMesh._materialDefines) {
  21688. func(subMesh._materialDefines);
  21689. }
  21690. }
  21691. };
  21692. /** @hidden */
  21693. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  21694. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  21695. };
  21696. /** @hidden */
  21697. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  21698. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  21699. };
  21700. /** @hidden */
  21701. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  21702. if (!this.subMeshes) {
  21703. return;
  21704. }
  21705. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  21706. var subMesh = _a[_i];
  21707. var material = subMesh.getMaterial();
  21708. if (material) {
  21709. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  21710. }
  21711. }
  21712. };
  21713. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  21714. /**
  21715. * Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z. Default is (1.0, 1.0, 1.0)
  21716. */
  21717. get: function () {
  21718. return this._scaling;
  21719. },
  21720. set: function (newScaling) {
  21721. this._scaling = newScaling;
  21722. if (this.physicsImpostor) {
  21723. this.physicsImpostor.forceUpdate();
  21724. }
  21725. },
  21726. enumerable: true,
  21727. configurable: true
  21728. });
  21729. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  21730. // Methods
  21731. /**
  21732. * Returns true if the mesh is blocked. Implemented by child classes
  21733. */
  21734. get: function () {
  21735. return false;
  21736. },
  21737. enumerable: true,
  21738. configurable: true
  21739. });
  21740. /**
  21741. * Returns the mesh itself by default. Implemented by child classes
  21742. * @param camera defines the camera to use to pick the right LOD level
  21743. * @returns the currentAbstractMesh
  21744. */
  21745. AbstractMesh.prototype.getLOD = function (camera) {
  21746. return this;
  21747. };
  21748. /**
  21749. * Returns 0 by default. Implemented by child classes
  21750. * @returns an integer
  21751. */
  21752. AbstractMesh.prototype.getTotalVertices = function () {
  21753. return 0;
  21754. };
  21755. /**
  21756. * Returns a positive integer : the total number of indices in this mesh geometry.
  21757. * @returns the numner of indices or zero if the mesh has no geometry.
  21758. */
  21759. AbstractMesh.prototype.getTotalIndices = function () {
  21760. return 0;
  21761. };
  21762. /**
  21763. * Returns null by default. Implemented by child classes
  21764. * @returns null
  21765. */
  21766. AbstractMesh.prototype.getIndices = function () {
  21767. return null;
  21768. };
  21769. /**
  21770. * Returns the array of the requested vertex data kind. Implemented by child classes
  21771. * @param kind defines the vertex data kind to use
  21772. * @returns null
  21773. */
  21774. AbstractMesh.prototype.getVerticesData = function (kind) {
  21775. return null;
  21776. };
  21777. /**
  21778. * Sets the vertex data of the mesh geometry for the requested `kind`.
  21779. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  21780. * Note that a new underlying VertexBuffer object is created each call.
  21781. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  21782. * @param kind defines vertex data kind:
  21783. * * BABYLON.VertexBuffer.PositionKind
  21784. * * BABYLON.VertexBuffer.UVKind
  21785. * * BABYLON.VertexBuffer.UV2Kind
  21786. * * BABYLON.VertexBuffer.UV3Kind
  21787. * * BABYLON.VertexBuffer.UV4Kind
  21788. * * BABYLON.VertexBuffer.UV5Kind
  21789. * * BABYLON.VertexBuffer.UV6Kind
  21790. * * BABYLON.VertexBuffer.ColorKind
  21791. * * BABYLON.VertexBuffer.MatricesIndicesKind
  21792. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21793. * * BABYLON.VertexBuffer.MatricesWeightsKind
  21794. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21795. * @param data defines the data source
  21796. * @param updatable defines if the data must be flagged as updatable (or static)
  21797. * @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
  21798. * @returns the current mesh
  21799. */
  21800. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  21801. return this;
  21802. };
  21803. /**
  21804. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  21805. * If the mesh has no geometry, it is simply returned as it is.
  21806. * @param kind defines vertex data kind:
  21807. * * BABYLON.VertexBuffer.PositionKind
  21808. * * BABYLON.VertexBuffer.UVKind
  21809. * * BABYLON.VertexBuffer.UV2Kind
  21810. * * BABYLON.VertexBuffer.UV3Kind
  21811. * * BABYLON.VertexBuffer.UV4Kind
  21812. * * BABYLON.VertexBuffer.UV5Kind
  21813. * * BABYLON.VertexBuffer.UV6Kind
  21814. * * BABYLON.VertexBuffer.ColorKind
  21815. * * BABYLON.VertexBuffer.MatricesIndicesKind
  21816. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21817. * * BABYLON.VertexBuffer.MatricesWeightsKind
  21818. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21819. * @param data defines the data source
  21820. * @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
  21821. * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh
  21822. * @returns the current mesh
  21823. */
  21824. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  21825. return this;
  21826. };
  21827. /**
  21828. * Sets the mesh indices,
  21829. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  21830. * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  21831. * @param totalVertices Defines the total number of vertices
  21832. * @returns the current mesh
  21833. */
  21834. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  21835. return this;
  21836. };
  21837. /**
  21838. * Gets a boolean indicating if specific vertex data is present
  21839. * @param kind defines the vertex data kind to use
  21840. * @returns true is data kind is present
  21841. */
  21842. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  21843. return false;
  21844. };
  21845. /**
  21846. * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined
  21847. * @returns a BoundingInfo
  21848. */
  21849. AbstractMesh.prototype.getBoundingInfo = function () {
  21850. if (this._masterMesh) {
  21851. return this._masterMesh.getBoundingInfo();
  21852. }
  21853. if (!this._boundingInfo) {
  21854. // this._boundingInfo is being created here
  21855. this._updateBoundingInfo();
  21856. }
  21857. // cannot be null.
  21858. return this._boundingInfo;
  21859. };
  21860. /**
  21861. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)
  21862. * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box
  21863. * @returns the current mesh
  21864. */
  21865. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  21866. if (includeDescendants === void 0) { includeDescendants = true; }
  21867. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  21868. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  21869. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  21870. if (maxDimension === 0) {
  21871. return this;
  21872. }
  21873. var scale = 1 / maxDimension;
  21874. this.scaling.scaleInPlace(scale);
  21875. return this;
  21876. };
  21877. /**
  21878. * Overwrite the current bounding info
  21879. * @param boundingInfo defines the new bounding info
  21880. * @returns the current mesh
  21881. */
  21882. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  21883. this._boundingInfo = boundingInfo;
  21884. return this;
  21885. };
  21886. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  21887. /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */
  21888. get: function () {
  21889. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  21890. },
  21891. enumerable: true,
  21892. configurable: true
  21893. });
  21894. /** @hidden */
  21895. AbstractMesh.prototype._preActivate = function () {
  21896. };
  21897. /** @hidden */
  21898. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  21899. };
  21900. /** @hidden */
  21901. AbstractMesh.prototype._activate = function (renderId) {
  21902. this._renderId = renderId;
  21903. };
  21904. /**
  21905. * Gets the current world matrix
  21906. * @returns a Matrix
  21907. */
  21908. AbstractMesh.prototype.getWorldMatrix = function () {
  21909. if (this._masterMesh) {
  21910. return this._masterMesh.getWorldMatrix();
  21911. }
  21912. return _super.prototype.getWorldMatrix.call(this);
  21913. };
  21914. /** @hidden */
  21915. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  21916. if (this._masterMesh) {
  21917. return this._masterMesh._getWorldMatrixDeterminant();
  21918. }
  21919. return _super.prototype._getWorldMatrixDeterminant.call(this);
  21920. };
  21921. // ================================== Point of View Movement =================================
  21922. /**
  21923. * Perform relative position change from the point of view of behind the front of the mesh.
  21924. * This is performed taking into account the meshes current rotation, so you do not have to care.
  21925. * Supports definition of mesh facing forward or backward
  21926. * @param amountRight defines the distance on the right axis
  21927. * @param amountUp defines the distance on the up axis
  21928. * @param amountForward defines the distance on the forward axis
  21929. * @returns the current mesh
  21930. */
  21931. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  21932. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  21933. return this;
  21934. };
  21935. /**
  21936. * Calculate relative position change from the point of view of behind the front of the mesh.
  21937. * This is performed taking into account the meshes current rotation, so you do not have to care.
  21938. * Supports definition of mesh facing forward or backward
  21939. * @param amountRight defines the distance on the right axis
  21940. * @param amountUp defines the distance on the up axis
  21941. * @param amountForward defines the distance on the forward axis
  21942. * @returns the new displacement vector
  21943. */
  21944. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  21945. var rotMatrix = new BABYLON.Matrix();
  21946. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  21947. rotQuaternion.toRotationMatrix(rotMatrix);
  21948. var translationDelta = BABYLON.Vector3.Zero();
  21949. var defForwardMult = this.definedFacingForward ? -1 : 1;
  21950. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  21951. return translationDelta;
  21952. };
  21953. // ================================== Point of View Rotation =================================
  21954. /**
  21955. * Perform relative rotation change from the point of view of behind the front of the mesh.
  21956. * Supports definition of mesh facing forward or backward
  21957. * @param flipBack defines the flip
  21958. * @param twirlClockwise defines the twirl
  21959. * @param tiltRight defines the tilt
  21960. * @returns the current mesh
  21961. */
  21962. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  21963. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  21964. return this;
  21965. };
  21966. /**
  21967. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  21968. * Supports definition of mesh facing forward or backward.
  21969. * @param flipBack defines the flip
  21970. * @param twirlClockwise defines the twirl
  21971. * @param tiltRight defines the tilt
  21972. * @returns the new rotation vector
  21973. */
  21974. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  21975. var defForwardMult = this.definedFacingForward ? 1 : -1;
  21976. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  21977. };
  21978. /**
  21979. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  21980. * @param includeDescendants Include bounding info from descendants as well (true by default)
  21981. * @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
  21982. * @returns the new bounding vectors
  21983. */
  21984. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants, predicate) {
  21985. if (includeDescendants === void 0) { includeDescendants = true; }
  21986. if (predicate === void 0) { predicate = null; }
  21987. // Ensures that all world matrix will be recomputed.
  21988. this.getScene().incrementRenderId();
  21989. this.computeWorldMatrix(true);
  21990. var min;
  21991. var max;
  21992. var boundingInfo = this.getBoundingInfo();
  21993. if (!this.subMeshes) {
  21994. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  21995. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  21996. }
  21997. else {
  21998. min = boundingInfo.boundingBox.minimumWorld;
  21999. max = boundingInfo.boundingBox.maximumWorld;
  22000. }
  22001. if (includeDescendants) {
  22002. var descendants = this.getDescendants(false);
  22003. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  22004. var descendant = descendants_1[_i];
  22005. var childMesh = descendant;
  22006. childMesh.computeWorldMatrix(true);
  22007. // Filters meshes based on custom predicate function.
  22008. if (predicate && !predicate(childMesh)) {
  22009. continue;
  22010. }
  22011. //make sure we have the needed params to get mix and max
  22012. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  22013. continue;
  22014. }
  22015. var childBoundingInfo = childMesh.getBoundingInfo();
  22016. var boundingBox = childBoundingInfo.boundingBox;
  22017. var minBox = boundingBox.minimumWorld;
  22018. var maxBox = boundingBox.maximumWorld;
  22019. BABYLON.Tools.CheckExtends(minBox, min, max);
  22020. BABYLON.Tools.CheckExtends(maxBox, min, max);
  22021. }
  22022. }
  22023. return {
  22024. min: min,
  22025. max: max
  22026. };
  22027. };
  22028. /**
  22029. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  22030. * This means the mesh underlying bounding box and sphere are recomputed.
  22031. * @param applySkeleton defines whether to apply the skeleton before computing the bounding info
  22032. * @returns the current mesh
  22033. */
  22034. AbstractMesh.prototype.refreshBoundingInfo = function (applySkeleton) {
  22035. if (applySkeleton === void 0) { applySkeleton = false; }
  22036. if (this._boundingInfo && this._boundingInfo.isLocked) {
  22037. return this;
  22038. }
  22039. this._refreshBoundingInfo(this._getPositionData(applySkeleton), null);
  22040. return this;
  22041. };
  22042. /** @hidden */
  22043. AbstractMesh.prototype._refreshBoundingInfo = function (data, bias) {
  22044. if (data) {
  22045. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices(), bias);
  22046. if (this._boundingInfo) {
  22047. this._boundingInfo.reConstruct(extend.minimum, extend.maximum);
  22048. }
  22049. else {
  22050. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  22051. }
  22052. }
  22053. if (this.subMeshes) {
  22054. for (var index = 0; index < this.subMeshes.length; index++) {
  22055. this.subMeshes[index].refreshBoundingInfo();
  22056. }
  22057. }
  22058. this._updateBoundingInfo();
  22059. };
  22060. /** @hidden */
  22061. AbstractMesh.prototype._getPositionData = function (applySkeleton) {
  22062. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22063. if (data && applySkeleton && this.skeleton) {
  22064. data = BABYLON.Tools.Slice(data);
  22065. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  22066. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  22067. if (matricesWeightsData && matricesIndicesData) {
  22068. var needExtras = this.numBoneInfluencers > 4;
  22069. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  22070. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  22071. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  22072. var tempVector = BABYLON.Tmp.Vector3[0];
  22073. var finalMatrix = BABYLON.Tmp.Matrix[0];
  22074. var tempMatrix = BABYLON.Tmp.Matrix[1];
  22075. var matWeightIdx = 0;
  22076. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  22077. finalMatrix.reset();
  22078. var inf;
  22079. var weight;
  22080. for (inf = 0; inf < 4; inf++) {
  22081. weight = matricesWeightsData[matWeightIdx + inf];
  22082. if (weight > 0) {
  22083. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  22084. finalMatrix.addToSelf(tempMatrix);
  22085. }
  22086. }
  22087. if (needExtras) {
  22088. for (inf = 0; inf < 4; inf++) {
  22089. weight = matricesWeightsExtraData[matWeightIdx + inf];
  22090. if (weight > 0) {
  22091. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  22092. finalMatrix.addToSelf(tempMatrix);
  22093. }
  22094. }
  22095. }
  22096. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  22097. tempVector.toArray(data, index);
  22098. }
  22099. }
  22100. }
  22101. return data;
  22102. };
  22103. /** @hidden */
  22104. AbstractMesh.prototype._updateBoundingInfo = function () {
  22105. if (this._boundingInfo) {
  22106. this._boundingInfo.update(this.worldMatrixFromCache);
  22107. }
  22108. else {
  22109. this._boundingInfo = new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition, this.worldMatrixFromCache);
  22110. }
  22111. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  22112. return this;
  22113. };
  22114. /** @hidden */
  22115. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  22116. if (!this.subMeshes) {
  22117. return this;
  22118. }
  22119. var count = this.subMeshes.length;
  22120. for (var subIndex = 0; subIndex < count; subIndex++) {
  22121. var subMesh = this.subMeshes[subIndex];
  22122. if (count > 1 || !subMesh.IsGlobal) {
  22123. subMesh.updateBoundingInfo(matrix);
  22124. }
  22125. }
  22126. return this;
  22127. };
  22128. /** @hidden */
  22129. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  22130. // Bounding info
  22131. this._updateBoundingInfo();
  22132. };
  22133. /**
  22134. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  22135. * A mesh is in the frustum if its bounding box intersects the frustum
  22136. * @param frustumPlanes defines the frustum to test
  22137. * @returns true if the mesh is in the frustum planes
  22138. */
  22139. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  22140. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes, this.cullingStrategy);
  22141. };
  22142. /**
  22143. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  22144. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  22145. * @param frustumPlanes defines the frustum to test
  22146. * @returns true if the mesh is completely in the frustum planes
  22147. */
  22148. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  22149. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  22150. };
  22151. /**
  22152. * True if the mesh intersects another mesh or a SolidParticle object
  22153. * @param mesh defines a target mesh or SolidParticle to test
  22154. * @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)
  22155. * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  22156. * @returns true if there is an intersection
  22157. */
  22158. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  22159. if (precise === void 0) { precise = false; }
  22160. if (!this._boundingInfo || !mesh._boundingInfo) {
  22161. return false;
  22162. }
  22163. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  22164. return true;
  22165. }
  22166. if (includeDescendants) {
  22167. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  22168. var child = _a[_i];
  22169. if (child.intersectsMesh(mesh, precise, true)) {
  22170. return true;
  22171. }
  22172. }
  22173. }
  22174. return false;
  22175. };
  22176. /**
  22177. * Returns true if the passed point (Vector3) is inside the mesh bounding box
  22178. * @param point defines the point to test
  22179. * @returns true if there is an intersection
  22180. */
  22181. AbstractMesh.prototype.intersectsPoint = function (point) {
  22182. if (!this._boundingInfo) {
  22183. return false;
  22184. }
  22185. return this._boundingInfo.intersectsPoint(point);
  22186. };
  22187. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  22188. // Collisions
  22189. /**
  22190. * Gets or sets a boolean indicating that this mesh can be used in the collision engine
  22191. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  22192. */
  22193. get: function () {
  22194. return this._checkCollisions;
  22195. },
  22196. set: function (collisionEnabled) {
  22197. this._checkCollisions = collisionEnabled;
  22198. if (this.getScene().workerCollisions) {
  22199. this.getScene().collisionCoordinator.onMeshUpdated(this);
  22200. }
  22201. },
  22202. enumerable: true,
  22203. configurable: true
  22204. });
  22205. Object.defineProperty(AbstractMesh.prototype, "collider", {
  22206. /**
  22207. * Gets Collider object used to compute collisions (not physics)
  22208. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  22209. */
  22210. get: function () {
  22211. return this._collider;
  22212. },
  22213. enumerable: true,
  22214. configurable: true
  22215. });
  22216. /**
  22217. * Move the mesh using collision engine
  22218. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  22219. * @param displacement defines the requested displacement vector
  22220. * @returns the current mesh
  22221. */
  22222. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  22223. var globalPosition = this.getAbsolutePosition();
  22224. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  22225. if (!this._collider) {
  22226. this._collider = new BABYLON.Collider();
  22227. }
  22228. this._collider._radius = this.ellipsoid;
  22229. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  22230. return this;
  22231. };
  22232. // Collisions
  22233. /** @hidden */
  22234. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  22235. this._generatePointsArray();
  22236. if (!this._positions) {
  22237. return this;
  22238. }
  22239. // Transformation
  22240. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  22241. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  22242. subMesh._lastColliderWorldVertices = [];
  22243. subMesh._trianglePlanes = [];
  22244. var start = subMesh.verticesStart;
  22245. var end = (subMesh.verticesStart + subMesh.verticesCount);
  22246. for (var i = start; i < end; i++) {
  22247. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  22248. }
  22249. }
  22250. // Collide
  22251. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  22252. if (collider.collisionFound) {
  22253. collider.collidedMesh = this;
  22254. }
  22255. return this;
  22256. };
  22257. /** @hidden */
  22258. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  22259. var subMeshes = this._scene.getCollidingSubMeshCandidates(this, collider);
  22260. var len = subMeshes.length;
  22261. for (var index = 0; index < len; index++) {
  22262. var subMesh = subMeshes.data[index];
  22263. // Bounding test
  22264. if (len > 1 && !subMesh._checkCollision(collider)) {
  22265. continue;
  22266. }
  22267. this._collideForSubMesh(subMesh, transformMatrix, collider);
  22268. }
  22269. return this;
  22270. };
  22271. /** @hidden */
  22272. AbstractMesh.prototype._checkCollision = function (collider) {
  22273. // Bounding box test
  22274. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider)) {
  22275. return this;
  22276. }
  22277. // Transformation matrix
  22278. var collisionsScalingMatrix = BABYLON.Tmp.Matrix[0];
  22279. var collisionsTransformMatrix = BABYLON.Tmp.Matrix[1];
  22280. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, collisionsScalingMatrix);
  22281. this.worldMatrixFromCache.multiplyToRef(collisionsScalingMatrix, collisionsTransformMatrix);
  22282. this._processCollisionsForSubMeshes(collider, collisionsTransformMatrix);
  22283. return this;
  22284. };
  22285. // Picking
  22286. /** @hidden */
  22287. AbstractMesh.prototype._generatePointsArray = function () {
  22288. return false;
  22289. };
  22290. /**
  22291. * Checks if the passed Ray intersects with the mesh
  22292. * @param ray defines the ray to use
  22293. * @param fastCheck defines if fast mode (but less precise) must be used (false by default)
  22294. * @returns the picking info
  22295. * @see http://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  22296. */
  22297. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  22298. var pickingInfo = new BABYLON.PickingInfo();
  22299. var intersectionThreshold = this.getClassName() === "InstancedLinesMesh" || this.getClassName() === "LinesMesh" ? this.intersectionThreshold : 0;
  22300. var boundingInfo = this._boundingInfo;
  22301. if (!this.subMeshes || !boundingInfo || !ray.intersectsSphere(boundingInfo.boundingSphere, intersectionThreshold) || !ray.intersectsBox(boundingInfo.boundingBox, intersectionThreshold)) {
  22302. return pickingInfo;
  22303. }
  22304. if (!this._generatePointsArray()) {
  22305. return pickingInfo;
  22306. }
  22307. var intersectInfo = null;
  22308. var subMeshes = this._scene.getIntersectingSubMeshCandidates(this, ray);
  22309. var len = subMeshes.length;
  22310. for (var index = 0; index < len; index++) {
  22311. var subMesh = subMeshes.data[index];
  22312. // Bounding test
  22313. if (len > 1 && !subMesh.canIntersects(ray)) {
  22314. continue;
  22315. }
  22316. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  22317. if (currentIntersectInfo) {
  22318. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  22319. intersectInfo = currentIntersectInfo;
  22320. intersectInfo.subMeshId = index;
  22321. if (fastCheck) {
  22322. break;
  22323. }
  22324. }
  22325. }
  22326. }
  22327. if (intersectInfo) {
  22328. // Get picked point
  22329. var world = this.getWorldMatrix();
  22330. var worldOrigin = BABYLON.Tmp.Vector3[0];
  22331. var direction = BABYLON.Tmp.Vector3[1];
  22332. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, world, worldOrigin);
  22333. ray.direction.scaleToRef(intersectInfo.distance, direction);
  22334. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  22335. var pickedPoint = worldDirection.addInPlace(worldOrigin);
  22336. // Return result
  22337. pickingInfo.hit = true;
  22338. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  22339. pickingInfo.pickedPoint = pickedPoint;
  22340. pickingInfo.pickedMesh = this;
  22341. pickingInfo.bu = intersectInfo.bu || 0;
  22342. pickingInfo.bv = intersectInfo.bv || 0;
  22343. pickingInfo.faceId = intersectInfo.faceId;
  22344. pickingInfo.subMeshId = intersectInfo.subMeshId;
  22345. return pickingInfo;
  22346. }
  22347. return pickingInfo;
  22348. };
  22349. /**
  22350. * Clones the current mesh
  22351. * @param name defines the mesh name
  22352. * @param newParent defines the new mesh parent
  22353. * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default)
  22354. * @returns the new mesh
  22355. */
  22356. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  22357. return null;
  22358. };
  22359. /**
  22360. * Disposes all the submeshes of the current meshnp
  22361. * @returns the current mesh
  22362. */
  22363. AbstractMesh.prototype.releaseSubMeshes = function () {
  22364. if (this.subMeshes) {
  22365. while (this.subMeshes.length) {
  22366. this.subMeshes[0].dispose();
  22367. }
  22368. }
  22369. else {
  22370. this.subMeshes = new Array();
  22371. }
  22372. return this;
  22373. };
  22374. /**
  22375. * Releases resources associated with this abstract mesh.
  22376. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22377. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22378. */
  22379. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22380. var _this = this;
  22381. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22382. var index;
  22383. // Smart Array Retainers.
  22384. this.getScene().freeActiveMeshes();
  22385. this.getScene().freeRenderingGroups();
  22386. // Action manager
  22387. if (this.actionManager !== undefined && this.actionManager !== null) {
  22388. this.actionManager.dispose();
  22389. this.actionManager = null;
  22390. }
  22391. // Skeleton
  22392. this._skeleton = null;
  22393. // Intersections in progress
  22394. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  22395. var other = this._intersectionsInProgress[index];
  22396. var pos = other._intersectionsInProgress.indexOf(this);
  22397. other._intersectionsInProgress.splice(pos, 1);
  22398. }
  22399. this._intersectionsInProgress = [];
  22400. // Lights
  22401. var lights = this.getScene().lights;
  22402. lights.forEach(function (light) {
  22403. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  22404. if (meshIndex !== -1) {
  22405. light.includedOnlyMeshes.splice(meshIndex, 1);
  22406. }
  22407. meshIndex = light.excludedMeshes.indexOf(_this);
  22408. if (meshIndex !== -1) {
  22409. light.excludedMeshes.splice(meshIndex, 1);
  22410. }
  22411. // Shadow generators
  22412. var generator = light.getShadowGenerator();
  22413. if (generator) {
  22414. var shadowMap = generator.getShadowMap();
  22415. if (shadowMap && shadowMap.renderList) {
  22416. meshIndex = shadowMap.renderList.indexOf(_this);
  22417. if (meshIndex !== -1) {
  22418. shadowMap.renderList.splice(meshIndex, 1);
  22419. }
  22420. }
  22421. }
  22422. });
  22423. // SubMeshes
  22424. if (this.getClassName() !== "InstancedMesh" || this.getClassName() !== "InstancedLinesMesh") {
  22425. this.releaseSubMeshes();
  22426. }
  22427. // Query
  22428. var engine = this.getScene().getEngine();
  22429. if (this._occlusionQuery) {
  22430. this.isOcclusionQueryInProgress = false;
  22431. engine.deleteQuery(this._occlusionQuery);
  22432. this._occlusionQuery = null;
  22433. }
  22434. // Engine
  22435. engine.wipeCaches();
  22436. // Remove from scene
  22437. this.getScene().removeMesh(this);
  22438. if (disposeMaterialAndTextures) {
  22439. if (this.material) {
  22440. this.material.dispose(false, true);
  22441. }
  22442. }
  22443. if (!doNotRecurse) {
  22444. // Particles
  22445. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  22446. if (this.getScene().particleSystems[index].emitter === this) {
  22447. this.getScene().particleSystems[index].dispose();
  22448. index--;
  22449. }
  22450. }
  22451. }
  22452. // facet data
  22453. if (this._facetData.facetDataEnabled) {
  22454. this.disableFacetData();
  22455. }
  22456. this.onAfterWorldMatrixUpdateObservable.clear();
  22457. this.onCollideObservable.clear();
  22458. this.onCollisionPositionChangeObservable.clear();
  22459. this.onRebuildObservable.clear();
  22460. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22461. };
  22462. /**
  22463. * Adds the passed mesh as a child to the current mesh
  22464. * @param mesh defines the child mesh
  22465. * @returns the current mesh
  22466. */
  22467. AbstractMesh.prototype.addChild = function (mesh) {
  22468. mesh.setParent(this);
  22469. return this;
  22470. };
  22471. /**
  22472. * Removes the passed mesh from the current mesh children list
  22473. * @param mesh defines the child mesh
  22474. * @returns the current mesh
  22475. */
  22476. AbstractMesh.prototype.removeChild = function (mesh) {
  22477. mesh.setParent(null);
  22478. return this;
  22479. };
  22480. // Facet data
  22481. /** @hidden */
  22482. AbstractMesh.prototype._initFacetData = function () {
  22483. var data = this._facetData;
  22484. if (!data.facetNormals) {
  22485. data.facetNormals = new Array();
  22486. }
  22487. if (!data.facetPositions) {
  22488. data.facetPositions = new Array();
  22489. }
  22490. if (!data.facetPartitioning) {
  22491. data.facetPartitioning = new Array();
  22492. }
  22493. data.facetNb = (this.getIndices().length / 3) | 0;
  22494. data.partitioningSubdivisions = (data.partitioningSubdivisions) ? data.partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  22495. data.partitioningBBoxRatio = (data.partitioningBBoxRatio) ? data.partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  22496. for (var f = 0; f < data.facetNb; f++) {
  22497. data.facetNormals[f] = BABYLON.Vector3.Zero();
  22498. data.facetPositions[f] = BABYLON.Vector3.Zero();
  22499. }
  22500. data.facetDataEnabled = true;
  22501. return this;
  22502. };
  22503. /**
  22504. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  22505. * This method can be called within the render loop.
  22506. * 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
  22507. * @returns the current mesh
  22508. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22509. */
  22510. AbstractMesh.prototype.updateFacetData = function () {
  22511. var data = this._facetData;
  22512. if (!data.facetDataEnabled) {
  22513. this._initFacetData();
  22514. }
  22515. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22516. var indices = this.getIndices();
  22517. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22518. var bInfo = this.getBoundingInfo();
  22519. if (data.facetDepthSort && !data.facetDepthSortEnabled) {
  22520. // init arrays, matrix and sort function on first call
  22521. data.facetDepthSortEnabled = true;
  22522. if (indices instanceof Uint16Array) {
  22523. data.depthSortedIndices = new Uint16Array(indices);
  22524. }
  22525. else if (indices instanceof Uint32Array) {
  22526. data.depthSortedIndices = new Uint32Array(indices);
  22527. }
  22528. else {
  22529. var needs32bits = false;
  22530. for (var i = 0; i < indices.length; i++) {
  22531. if (indices[i] > 65535) {
  22532. needs32bits = true;
  22533. break;
  22534. }
  22535. }
  22536. if (needs32bits) {
  22537. data.depthSortedIndices = new Uint32Array(indices);
  22538. }
  22539. else {
  22540. data.depthSortedIndices = new Uint16Array(indices);
  22541. }
  22542. }
  22543. data.facetDepthSortFunction = function (f1, f2) {
  22544. return (f2.sqDistance - f1.sqDistance);
  22545. };
  22546. if (!data.facetDepthSortFrom) {
  22547. var camera = this.getScene().activeCamera;
  22548. data.facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  22549. }
  22550. data.depthSortedFacets = [];
  22551. for (var f = 0; f < data.facetNb; f++) {
  22552. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  22553. data.depthSortedFacets.push(depthSortedFacet);
  22554. }
  22555. data.invertedMatrix = BABYLON.Matrix.Identity();
  22556. data.facetDepthSortOrigin = BABYLON.Vector3.Zero();
  22557. }
  22558. data.bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  22559. data.bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  22560. data.bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  22561. var bbSizeMax = (data.bbSize.x > data.bbSize.y) ? data.bbSize.x : data.bbSize.y;
  22562. bbSizeMax = (bbSizeMax > data.bbSize.z) ? bbSizeMax : data.bbSize.z;
  22563. data.subDiv.max = data.partitioningSubdivisions;
  22564. data.subDiv.X = Math.floor(data.subDiv.max * data.bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  22565. data.subDiv.Y = Math.floor(data.subDiv.max * data.bbSize.y / bbSizeMax); // according to each bbox size per axis
  22566. data.subDiv.Z = Math.floor(data.subDiv.max * data.bbSize.z / bbSizeMax);
  22567. data.subDiv.X = data.subDiv.X < 1 ? 1 : data.subDiv.X; // at least one subdivision
  22568. data.subDiv.Y = data.subDiv.Y < 1 ? 1 : data.subDiv.Y;
  22569. data.subDiv.Z = data.subDiv.Z < 1 ? 1 : data.subDiv.Z;
  22570. // set the parameters for ComputeNormals()
  22571. data.facetParameters.facetNormals = this.getFacetLocalNormals();
  22572. data.facetParameters.facetPositions = this.getFacetLocalPositions();
  22573. data.facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  22574. data.facetParameters.bInfo = bInfo;
  22575. data.facetParameters.bbSize = data.bbSize;
  22576. data.facetParameters.subDiv = data.subDiv;
  22577. data.facetParameters.ratio = this.partitioningBBoxRatio;
  22578. data.facetParameters.depthSort = data.facetDepthSort;
  22579. if (data.facetDepthSort && data.facetDepthSortEnabled) {
  22580. this.computeWorldMatrix(true);
  22581. this._worldMatrix.invertToRef(data.invertedMatrix);
  22582. BABYLON.Vector3.TransformCoordinatesToRef(data.facetDepthSortFrom, data.invertedMatrix, data.facetDepthSortOrigin);
  22583. data.facetParameters.distanceTo = data.facetDepthSortOrigin;
  22584. }
  22585. data.facetParameters.depthSortedFacets = data.depthSortedFacets;
  22586. BABYLON.VertexData.ComputeNormals(positions, indices, normals, data.facetParameters);
  22587. if (data.facetDepthSort && data.facetDepthSortEnabled) {
  22588. data.depthSortedFacets.sort(data.facetDepthSortFunction);
  22589. var l = (data.depthSortedIndices.length / 3) | 0;
  22590. for (var f = 0; f < l; f++) {
  22591. var sind = data.depthSortedFacets[f].ind;
  22592. data.depthSortedIndices[f * 3] = indices[sind];
  22593. data.depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  22594. data.depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  22595. }
  22596. this.updateIndices(data.depthSortedIndices);
  22597. }
  22598. return this;
  22599. };
  22600. /**
  22601. * Returns the facetLocalNormals array.
  22602. * The normals are expressed in the mesh local spac
  22603. * @returns an array of Vector3
  22604. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22605. */
  22606. AbstractMesh.prototype.getFacetLocalNormals = function () {
  22607. if (!this._facetData.facetNormals) {
  22608. this.updateFacetData();
  22609. }
  22610. return this._facetData.facetNormals;
  22611. };
  22612. /**
  22613. * Returns the facetLocalPositions array.
  22614. * The facet positions are expressed in the mesh local space
  22615. * @returns an array of Vector3
  22616. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22617. */
  22618. AbstractMesh.prototype.getFacetLocalPositions = function () {
  22619. if (!this._facetData.facetPositions) {
  22620. this.updateFacetData();
  22621. }
  22622. return this._facetData.facetPositions;
  22623. };
  22624. /**
  22625. * Returns the facetLocalPartioning array
  22626. * @returns an array of array of numbers
  22627. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22628. */
  22629. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  22630. if (!this._facetData.facetPartitioning) {
  22631. this.updateFacetData();
  22632. }
  22633. return this._facetData.facetPartitioning;
  22634. };
  22635. /**
  22636. * Returns the i-th facet position in the world system.
  22637. * This method allocates a new Vector3 per call
  22638. * @param i defines the facet index
  22639. * @returns a new Vector3
  22640. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22641. */
  22642. AbstractMesh.prototype.getFacetPosition = function (i) {
  22643. var pos = BABYLON.Vector3.Zero();
  22644. this.getFacetPositionToRef(i, pos);
  22645. return pos;
  22646. };
  22647. /**
  22648. * Sets the reference Vector3 with the i-th facet position in the world system
  22649. * @param i defines the facet index
  22650. * @param ref defines the target vector
  22651. * @returns the current mesh
  22652. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22653. */
  22654. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  22655. var localPos = (this.getFacetLocalPositions())[i];
  22656. var world = this.getWorldMatrix();
  22657. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  22658. return this;
  22659. };
  22660. /**
  22661. * Returns the i-th facet normal in the world system.
  22662. * This method allocates a new Vector3 per call
  22663. * @param i defines the facet index
  22664. * @returns a new Vector3
  22665. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22666. */
  22667. AbstractMesh.prototype.getFacetNormal = function (i) {
  22668. var norm = BABYLON.Vector3.Zero();
  22669. this.getFacetNormalToRef(i, norm);
  22670. return norm;
  22671. };
  22672. /**
  22673. * Sets the reference Vector3 with the i-th facet normal in the world system
  22674. * @param i defines the facet index
  22675. * @param ref defines the target vector
  22676. * @returns the current mesh
  22677. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22678. */
  22679. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  22680. var localNorm = (this.getFacetLocalNormals())[i];
  22681. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  22682. return this;
  22683. };
  22684. /**
  22685. * 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)
  22686. * @param x defines x coordinate
  22687. * @param y defines y coordinate
  22688. * @param z defines z coordinate
  22689. * @returns the array of facet indexes
  22690. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22691. */
  22692. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  22693. var bInfo = this.getBoundingInfo();
  22694. var data = this._facetData;
  22695. var ox = Math.floor((x - bInfo.minimum.x * data.partitioningBBoxRatio) * data.subDiv.X * data.partitioningBBoxRatio / data.bbSize.x);
  22696. var oy = Math.floor((y - bInfo.minimum.y * data.partitioningBBoxRatio) * data.subDiv.Y * data.partitioningBBoxRatio / data.bbSize.y);
  22697. var oz = Math.floor((z - bInfo.minimum.z * data.partitioningBBoxRatio) * data.subDiv.Z * data.partitioningBBoxRatio / data.bbSize.z);
  22698. if (ox < 0 || ox > data.subDiv.max || oy < 0 || oy > data.subDiv.max || oz < 0 || oz > data.subDiv.max) {
  22699. return null;
  22700. }
  22701. return data.facetPartitioning[ox + data.subDiv.max * oy + data.subDiv.max * data.subDiv.max * oz];
  22702. };
  22703. /**
  22704. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found
  22705. * @param projected sets as the (x,y,z) world projection on the facet
  22706. * @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
  22707. * @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
  22708. * @param x defines x coordinate
  22709. * @param y defines y coordinate
  22710. * @param z defines z coordinate
  22711. * @returns the face index if found (or null instead)
  22712. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22713. */
  22714. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  22715. if (checkFace === void 0) { checkFace = false; }
  22716. if (facing === void 0) { facing = true; }
  22717. var world = this.getWorldMatrix();
  22718. var invMat = BABYLON.Tmp.Matrix[5];
  22719. world.invertToRef(invMat);
  22720. var invVect = BABYLON.Tmp.Vector3[8];
  22721. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  22722. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  22723. if (projected) {
  22724. // tranform the local computed projected vector to world coordinates
  22725. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  22726. }
  22727. return closest;
  22728. };
  22729. /**
  22730. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found
  22731. * @param projected sets as the (x,y,z) local projection on the facet
  22732. * @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
  22733. * @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
  22734. * @param x defines x coordinate
  22735. * @param y defines y coordinate
  22736. * @param z defines z coordinate
  22737. * @returns the face index if found (or null instead)
  22738. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22739. */
  22740. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  22741. if (checkFace === void 0) { checkFace = false; }
  22742. if (facing === void 0) { facing = true; }
  22743. var closest = null;
  22744. var tmpx = 0.0;
  22745. var tmpy = 0.0;
  22746. var tmpz = 0.0;
  22747. var d = 0.0; // tmp dot facet normal * facet position
  22748. var t0 = 0.0;
  22749. var projx = 0.0;
  22750. var projy = 0.0;
  22751. var projz = 0.0;
  22752. // Get all the facets in the same partitioning block than (x, y, z)
  22753. var facetPositions = this.getFacetLocalPositions();
  22754. var facetNormals = this.getFacetLocalNormals();
  22755. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  22756. if (!facetsInBlock) {
  22757. return null;
  22758. }
  22759. // Get the closest facet to (x, y, z)
  22760. var shortest = Number.MAX_VALUE; // init distance vars
  22761. var tmpDistance = shortest;
  22762. var fib; // current facet in the block
  22763. var norm; // current facet normal
  22764. var p0; // current facet barycenter position
  22765. // loop on all the facets in the current partitioning block
  22766. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  22767. fib = facetsInBlock[idx];
  22768. norm = facetNormals[fib];
  22769. p0 = facetPositions[fib];
  22770. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  22771. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  22772. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  22773. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  22774. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  22775. projx = x + norm.x * t0;
  22776. projy = y + norm.y * t0;
  22777. projz = z + norm.z * t0;
  22778. tmpx = projx - x;
  22779. tmpy = projy - y;
  22780. tmpz = projz - z;
  22781. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  22782. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  22783. shortest = tmpDistance;
  22784. closest = fib;
  22785. if (projected) {
  22786. projected.x = projx;
  22787. projected.y = projy;
  22788. projected.z = projz;
  22789. }
  22790. }
  22791. }
  22792. }
  22793. return closest;
  22794. };
  22795. /**
  22796. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  22797. * @returns the parameters
  22798. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22799. */
  22800. AbstractMesh.prototype.getFacetDataParameters = function () {
  22801. return this._facetData.facetParameters;
  22802. };
  22803. /**
  22804. * Disables the feature FacetData and frees the related memory
  22805. * @returns the current mesh
  22806. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22807. */
  22808. AbstractMesh.prototype.disableFacetData = function () {
  22809. if (this._facetData.facetDataEnabled) {
  22810. this._facetData.facetDataEnabled = false;
  22811. this._facetData.facetPositions = new Array();
  22812. this._facetData.facetNormals = new Array();
  22813. this._facetData.facetPartitioning = new Array();
  22814. this._facetData.facetParameters = null;
  22815. this._facetData.depthSortedIndices = new Uint32Array(0);
  22816. }
  22817. return this;
  22818. };
  22819. /**
  22820. * Updates the AbstractMesh indices array
  22821. * @param indices defines the data source
  22822. * @returns the current mesh
  22823. */
  22824. AbstractMesh.prototype.updateIndices = function (indices) {
  22825. return this;
  22826. };
  22827. /**
  22828. * Creates new normals data for the mesh
  22829. * @param updatable defines if the normal vertex buffer must be flagged as updatable
  22830. * @returns the current mesh
  22831. */
  22832. AbstractMesh.prototype.createNormals = function (updatable) {
  22833. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22834. var indices = this.getIndices();
  22835. var normals;
  22836. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  22837. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22838. }
  22839. else {
  22840. normals = [];
  22841. }
  22842. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  22843. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  22844. return this;
  22845. };
  22846. /**
  22847. * Align the mesh with a normal
  22848. * @param normal defines the normal to use
  22849. * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default)
  22850. * @returns the current mesh
  22851. */
  22852. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  22853. if (!upDirection) {
  22854. upDirection = BABYLON.Axis.Y;
  22855. }
  22856. var axisX = BABYLON.Tmp.Vector3[0];
  22857. var axisZ = BABYLON.Tmp.Vector3[1];
  22858. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  22859. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  22860. if (this.rotationQuaternion) {
  22861. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  22862. }
  22863. else {
  22864. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  22865. }
  22866. return this;
  22867. };
  22868. /** @hidden */
  22869. AbstractMesh.prototype._checkOcclusionQuery = function () {
  22870. return false;
  22871. };
  22872. /** No occlusion */
  22873. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  22874. /** Occlusion set to optimisitic */
  22875. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  22876. /** Occlusion set to strict */
  22877. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  22878. /** Use an accurante occlusion algorithm */
  22879. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  22880. /** Use a conservative occlusion algorithm */
  22881. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  22882. /** Default culling strategy with bounding box and bounding sphere and then frustum culling */
  22883. AbstractMesh.CULLINGSTRATEGY_STANDARD = 0;
  22884. /** Culling strategy with bounding sphere only and then frustum culling */
  22885. AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY = 1;
  22886. return AbstractMesh;
  22887. }(BABYLON.TransformNode));
  22888. BABYLON.AbstractMesh = AbstractMesh;
  22889. })(BABYLON || (BABYLON = {}));
  22890. //# sourceMappingURL=babylon.abstractMesh.js.map
  22891. var BABYLON;
  22892. (function (BABYLON) {
  22893. /**
  22894. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  22895. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  22896. * 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.
  22897. */
  22898. var Light = /** @class */ (function (_super) {
  22899. __extends(Light, _super);
  22900. /**
  22901. * Creates a Light object in the scene.
  22902. * Documentation : http://doc.babylonjs.com/tutorials/lights
  22903. * @param name The firendly name of the light
  22904. * @param scene The scene the light belongs too
  22905. */
  22906. function Light(name, scene) {
  22907. var _this = _super.call(this, name, scene) || this;
  22908. /**
  22909. * Diffuse gives the basic color to an object.
  22910. */
  22911. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  22912. /**
  22913. * Specular produces a highlight color on an object.
  22914. * Note: This is note affecting PBR materials.
  22915. */
  22916. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  22917. /**
  22918. * Defines the falloff type for this light. This lets overrriding how punctual light are
  22919. * falling off base on range or angle.
  22920. * This can be set to any values in Light.FALLOFF_x.
  22921. *
  22922. * Note: This is only usefull for PBR Materials at the moment. This could be extended if required to
  22923. * other types of materials.
  22924. */
  22925. _this.falloffType = Light.FALLOFF_DEFAULT;
  22926. /**
  22927. * Strength of the light.
  22928. * Note: By default it is define in the framework own unit.
  22929. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  22930. */
  22931. _this.intensity = 1.0;
  22932. _this._range = Number.MAX_VALUE;
  22933. _this._inverseSquaredRange = 0;
  22934. /**
  22935. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  22936. * of light.
  22937. */
  22938. _this._photometricScale = 1.0;
  22939. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  22940. _this._radius = 0.00001;
  22941. /**
  22942. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  22943. * exceeding the number allowed of the materials.
  22944. */
  22945. _this.renderPriority = 0;
  22946. _this._shadowEnabled = true;
  22947. _this._excludeWithLayerMask = 0;
  22948. _this._includeOnlyWithLayerMask = 0;
  22949. _this._lightmapMode = 0;
  22950. /**
  22951. * @hidden Internal use only.
  22952. */
  22953. _this._excludedMeshesIds = new Array();
  22954. /**
  22955. * @hidden Internal use only.
  22956. */
  22957. _this._includedOnlyMeshesIds = new Array();
  22958. _this.getScene().addLight(_this);
  22959. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  22960. _this._buildUniformLayout();
  22961. _this.includedOnlyMeshes = new Array();
  22962. _this.excludedMeshes = new Array();
  22963. _this._resyncMeshes();
  22964. return _this;
  22965. }
  22966. Object.defineProperty(Light.prototype, "range", {
  22967. /**
  22968. * Defines how far from the source the light is impacting in scene units.
  22969. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  22970. */
  22971. get: function () {
  22972. return this._range;
  22973. },
  22974. /**
  22975. * Defines how far from the source the light is impacting in scene units.
  22976. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  22977. */
  22978. set: function (value) {
  22979. this._range = value;
  22980. this._inverseSquaredRange = 1.0 / (this.range * this.range);
  22981. },
  22982. enumerable: true,
  22983. configurable: true
  22984. });
  22985. Object.defineProperty(Light.prototype, "intensityMode", {
  22986. /**
  22987. * Gets the photometric scale used to interpret the intensity.
  22988. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  22989. */
  22990. get: function () {
  22991. return this._intensityMode;
  22992. },
  22993. /**
  22994. * Sets the photometric scale used to interpret the intensity.
  22995. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  22996. */
  22997. set: function (value) {
  22998. this._intensityMode = value;
  22999. this._computePhotometricScale();
  23000. },
  23001. enumerable: true,
  23002. configurable: true
  23003. });
  23004. Object.defineProperty(Light.prototype, "radius", {
  23005. /**
  23006. * Gets the light radius used by PBR Materials to simulate soft area lights.
  23007. */
  23008. get: function () {
  23009. return this._radius;
  23010. },
  23011. /**
  23012. * sets the light radius used by PBR Materials to simulate soft area lights.
  23013. */
  23014. set: function (value) {
  23015. this._radius = value;
  23016. this._computePhotometricScale();
  23017. },
  23018. enumerable: true,
  23019. configurable: true
  23020. });
  23021. Object.defineProperty(Light.prototype, "shadowEnabled", {
  23022. /**
  23023. * Gets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  23024. * the current shadow generator.
  23025. */
  23026. get: function () {
  23027. return this._shadowEnabled;
  23028. },
  23029. /**
  23030. * Sets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  23031. * the current shadow generator.
  23032. */
  23033. set: function (value) {
  23034. if (this._shadowEnabled === value) {
  23035. return;
  23036. }
  23037. this._shadowEnabled = value;
  23038. this._markMeshesAsLightDirty();
  23039. },
  23040. enumerable: true,
  23041. configurable: true
  23042. });
  23043. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  23044. /**
  23045. * Gets the only meshes impacted by this light.
  23046. */
  23047. get: function () {
  23048. return this._includedOnlyMeshes;
  23049. },
  23050. /**
  23051. * Sets the only meshes impacted by this light.
  23052. */
  23053. set: function (value) {
  23054. this._includedOnlyMeshes = value;
  23055. this._hookArrayForIncludedOnly(value);
  23056. },
  23057. enumerable: true,
  23058. configurable: true
  23059. });
  23060. Object.defineProperty(Light.prototype, "excludedMeshes", {
  23061. /**
  23062. * Gets the meshes not impacted by this light.
  23063. */
  23064. get: function () {
  23065. return this._excludedMeshes;
  23066. },
  23067. /**
  23068. * Sets the meshes not impacted by this light.
  23069. */
  23070. set: function (value) {
  23071. this._excludedMeshes = value;
  23072. this._hookArrayForExcluded(value);
  23073. },
  23074. enumerable: true,
  23075. configurable: true
  23076. });
  23077. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  23078. /**
  23079. * Gets the layer id use to find what meshes are not impacted by the light.
  23080. * Inactive if 0
  23081. */
  23082. get: function () {
  23083. return this._excludeWithLayerMask;
  23084. },
  23085. /**
  23086. * Sets the layer id use to find what meshes are not impacted by the light.
  23087. * Inactive if 0
  23088. */
  23089. set: function (value) {
  23090. this._excludeWithLayerMask = value;
  23091. this._resyncMeshes();
  23092. },
  23093. enumerable: true,
  23094. configurable: true
  23095. });
  23096. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  23097. /**
  23098. * Gets the layer id use to find what meshes are impacted by the light.
  23099. * Inactive if 0
  23100. */
  23101. get: function () {
  23102. return this._includeOnlyWithLayerMask;
  23103. },
  23104. /**
  23105. * Sets the layer id use to find what meshes are impacted by the light.
  23106. * Inactive if 0
  23107. */
  23108. set: function (value) {
  23109. this._includeOnlyWithLayerMask = value;
  23110. this._resyncMeshes();
  23111. },
  23112. enumerable: true,
  23113. configurable: true
  23114. });
  23115. Object.defineProperty(Light.prototype, "lightmapMode", {
  23116. /**
  23117. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  23118. */
  23119. get: function () {
  23120. return this._lightmapMode;
  23121. },
  23122. /**
  23123. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  23124. */
  23125. set: function (value) {
  23126. if (this._lightmapMode === value) {
  23127. return;
  23128. }
  23129. this._lightmapMode = value;
  23130. this._markMeshesAsLightDirty();
  23131. },
  23132. enumerable: true,
  23133. configurable: true
  23134. });
  23135. /**
  23136. * Returns the string "Light".
  23137. * @returns the class name
  23138. */
  23139. Light.prototype.getClassName = function () {
  23140. return "Light";
  23141. };
  23142. /**
  23143. * Converts the light information to a readable string for debug purpose.
  23144. * @param fullDetails Supports for multiple levels of logging within scene loading
  23145. * @returns the human readable light info
  23146. */
  23147. Light.prototype.toString = function (fullDetails) {
  23148. var ret = "Name: " + this.name;
  23149. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  23150. if (this.animations) {
  23151. for (var i = 0; i < this.animations.length; i++) {
  23152. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  23153. }
  23154. }
  23155. if (fullDetails) {
  23156. }
  23157. return ret;
  23158. };
  23159. /** @hidden */
  23160. Light.prototype._syncParentEnabledState = function () {
  23161. _super.prototype._syncParentEnabledState.call(this);
  23162. this._resyncMeshes();
  23163. };
  23164. /**
  23165. * Set the enabled state of this node.
  23166. * @param value - the new enabled state
  23167. */
  23168. Light.prototype.setEnabled = function (value) {
  23169. _super.prototype.setEnabled.call(this, value);
  23170. this._resyncMeshes();
  23171. };
  23172. /**
  23173. * Returns the Light associated shadow generator if any.
  23174. * @return the associated shadow generator.
  23175. */
  23176. Light.prototype.getShadowGenerator = function () {
  23177. return this._shadowGenerator;
  23178. };
  23179. /**
  23180. * Returns a Vector3, the absolute light position in the World.
  23181. * @returns the world space position of the light
  23182. */
  23183. Light.prototype.getAbsolutePosition = function () {
  23184. return BABYLON.Vector3.Zero();
  23185. };
  23186. /**
  23187. * Specifies if the light will affect the passed mesh.
  23188. * @param mesh The mesh to test against the light
  23189. * @return true the mesh is affected otherwise, false.
  23190. */
  23191. Light.prototype.canAffectMesh = function (mesh) {
  23192. if (!mesh) {
  23193. return true;
  23194. }
  23195. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  23196. return false;
  23197. }
  23198. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  23199. return false;
  23200. }
  23201. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  23202. return false;
  23203. }
  23204. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  23205. return false;
  23206. }
  23207. return true;
  23208. };
  23209. /**
  23210. * Sort function to order lights for rendering.
  23211. * @param a First Light object to compare to second.
  23212. * @param b Second Light object to compare first.
  23213. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  23214. */
  23215. Light.CompareLightsPriority = function (a, b) {
  23216. //shadow-casting lights have priority over non-shadow-casting lights
  23217. //the renderPrioirty is a secondary sort criterion
  23218. if (a.shadowEnabled !== b.shadowEnabled) {
  23219. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  23220. }
  23221. return b.renderPriority - a.renderPriority;
  23222. };
  23223. /**
  23224. * Releases resources associated with this node.
  23225. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  23226. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  23227. */
  23228. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  23229. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  23230. if (this._shadowGenerator) {
  23231. this._shadowGenerator.dispose();
  23232. this._shadowGenerator = null;
  23233. }
  23234. // Animations
  23235. this.getScene().stopAnimation(this);
  23236. // Remove from meshes
  23237. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  23238. var mesh = _a[_i];
  23239. mesh._removeLightSource(this);
  23240. }
  23241. this._uniformBuffer.dispose();
  23242. // Remove from scene
  23243. this.getScene().removeLight(this);
  23244. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  23245. };
  23246. /**
  23247. * Returns the light type ID (integer).
  23248. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  23249. */
  23250. Light.prototype.getTypeID = function () {
  23251. return 0;
  23252. };
  23253. /**
  23254. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  23255. * @returns the scaled intensity in intensity mode unit
  23256. */
  23257. Light.prototype.getScaledIntensity = function () {
  23258. return this._photometricScale * this.intensity;
  23259. };
  23260. /**
  23261. * Returns a new Light object, named "name", from the current one.
  23262. * @param name The name of the cloned light
  23263. * @returns the new created light
  23264. */
  23265. Light.prototype.clone = function (name) {
  23266. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  23267. if (!constructor) {
  23268. return null;
  23269. }
  23270. return BABYLON.SerializationHelper.Clone(constructor, this);
  23271. };
  23272. /**
  23273. * Serializes the current light into a Serialization object.
  23274. * @returns the serialized object.
  23275. */
  23276. Light.prototype.serialize = function () {
  23277. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  23278. // Type
  23279. serializationObject.type = this.getTypeID();
  23280. // Parent
  23281. if (this.parent) {
  23282. serializationObject.parentId = this.parent.id;
  23283. }
  23284. // Inclusion / exclusions
  23285. if (this.excludedMeshes.length > 0) {
  23286. serializationObject.excludedMeshesIds = [];
  23287. this.excludedMeshes.forEach(function (mesh) {
  23288. serializationObject.excludedMeshesIds.push(mesh.id);
  23289. });
  23290. }
  23291. if (this.includedOnlyMeshes.length > 0) {
  23292. serializationObject.includedOnlyMeshesIds = [];
  23293. this.includedOnlyMeshes.forEach(function (mesh) {
  23294. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  23295. });
  23296. }
  23297. // Animations
  23298. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  23299. serializationObject.ranges = this.serializeAnimationRanges();
  23300. return serializationObject;
  23301. };
  23302. /**
  23303. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  23304. * This new light is named "name" and added to the passed scene.
  23305. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  23306. * @param name The friendly name of the light
  23307. * @param scene The scene the new light will belong to
  23308. * @returns the constructor function
  23309. */
  23310. Light.GetConstructorFromName = function (type, name, scene) {
  23311. var constructorFunc = BABYLON.Node.Construct("Light_Type_" + type, name, scene);
  23312. if (constructorFunc) {
  23313. return constructorFunc;
  23314. }
  23315. // Default to no light for none present once.
  23316. return null;
  23317. };
  23318. /**
  23319. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  23320. * @param parsedLight The JSON representation of the light
  23321. * @param scene The scene to create the parsed light in
  23322. * @returns the created light after parsing
  23323. */
  23324. Light.Parse = function (parsedLight, scene) {
  23325. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  23326. if (!constructor) {
  23327. return null;
  23328. }
  23329. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  23330. // Inclusion / exclusions
  23331. if (parsedLight.excludedMeshesIds) {
  23332. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  23333. }
  23334. if (parsedLight.includedOnlyMeshesIds) {
  23335. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  23336. }
  23337. // Parent
  23338. if (parsedLight.parentId) {
  23339. light._waitingParentId = parsedLight.parentId;
  23340. }
  23341. // Animations
  23342. if (parsedLight.animations) {
  23343. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  23344. var parsedAnimation = parsedLight.animations[animationIndex];
  23345. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  23346. }
  23347. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  23348. }
  23349. if (parsedLight.autoAnimate) {
  23350. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  23351. }
  23352. return light;
  23353. };
  23354. Light.prototype._hookArrayForExcluded = function (array) {
  23355. var _this = this;
  23356. var oldPush = array.push;
  23357. array.push = function () {
  23358. var items = [];
  23359. for (var _i = 0; _i < arguments.length; _i++) {
  23360. items[_i] = arguments[_i];
  23361. }
  23362. var result = oldPush.apply(array, items);
  23363. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  23364. var item = items_1[_a];
  23365. item._resyncLighSource(_this);
  23366. }
  23367. return result;
  23368. };
  23369. var oldSplice = array.splice;
  23370. array.splice = function (index, deleteCount) {
  23371. var deleted = oldSplice.apply(array, [index, deleteCount]);
  23372. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  23373. var item = deleted_1[_i];
  23374. item._resyncLighSource(_this);
  23375. }
  23376. return deleted;
  23377. };
  23378. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  23379. var item = array_1[_i];
  23380. item._resyncLighSource(this);
  23381. }
  23382. };
  23383. Light.prototype._hookArrayForIncludedOnly = function (array) {
  23384. var _this = this;
  23385. var oldPush = array.push;
  23386. array.push = function () {
  23387. var items = [];
  23388. for (var _i = 0; _i < arguments.length; _i++) {
  23389. items[_i] = arguments[_i];
  23390. }
  23391. var result = oldPush.apply(array, items);
  23392. _this._resyncMeshes();
  23393. return result;
  23394. };
  23395. var oldSplice = array.splice;
  23396. array.splice = function (index, deleteCount) {
  23397. var deleted = oldSplice.apply(array, [index, deleteCount]);
  23398. _this._resyncMeshes();
  23399. return deleted;
  23400. };
  23401. this._resyncMeshes();
  23402. };
  23403. Light.prototype._resyncMeshes = function () {
  23404. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  23405. var mesh = _a[_i];
  23406. mesh._resyncLighSource(this);
  23407. }
  23408. };
  23409. /**
  23410. * Forces the meshes to update their light related information in their rendering used effects
  23411. * @hidden Internal Use Only
  23412. */
  23413. Light.prototype._markMeshesAsLightDirty = function () {
  23414. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  23415. var mesh = _a[_i];
  23416. if (mesh._lightSources.indexOf(this) !== -1) {
  23417. mesh._markSubMeshesAsLightDirty();
  23418. }
  23419. }
  23420. };
  23421. /**
  23422. * Recomputes the cached photometric scale if needed.
  23423. */
  23424. Light.prototype._computePhotometricScale = function () {
  23425. this._photometricScale = this._getPhotometricScale();
  23426. this.getScene().resetCachedMaterial();
  23427. };
  23428. /**
  23429. * Returns the Photometric Scale according to the light type and intensity mode.
  23430. */
  23431. Light.prototype._getPhotometricScale = function () {
  23432. var photometricScale = 0.0;
  23433. var lightTypeID = this.getTypeID();
  23434. //get photometric mode
  23435. var photometricMode = this.intensityMode;
  23436. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  23437. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  23438. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  23439. }
  23440. else {
  23441. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  23442. }
  23443. }
  23444. //compute photometric scale
  23445. switch (lightTypeID) {
  23446. case Light.LIGHTTYPEID_POINTLIGHT:
  23447. case Light.LIGHTTYPEID_SPOTLIGHT:
  23448. switch (photometricMode) {
  23449. case Light.INTENSITYMODE_LUMINOUSPOWER:
  23450. photometricScale = 1.0 / (4.0 * Math.PI);
  23451. break;
  23452. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  23453. photometricScale = 1.0;
  23454. break;
  23455. case Light.INTENSITYMODE_LUMINANCE:
  23456. photometricScale = this.radius * this.radius;
  23457. break;
  23458. }
  23459. break;
  23460. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  23461. switch (photometricMode) {
  23462. case Light.INTENSITYMODE_ILLUMINANCE:
  23463. photometricScale = 1.0;
  23464. break;
  23465. case Light.INTENSITYMODE_LUMINANCE:
  23466. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  23467. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  23468. var apexAngleRadians = this.radius;
  23469. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  23470. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  23471. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  23472. photometricScale = solidAngle;
  23473. break;
  23474. }
  23475. break;
  23476. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  23477. // No fall off in hemisperic light.
  23478. photometricScale = 1.0;
  23479. break;
  23480. }
  23481. return photometricScale;
  23482. };
  23483. /**
  23484. * Reorder the light in the scene according to their defined priority.
  23485. * @hidden Internal Use Only
  23486. */
  23487. Light.prototype._reorderLightsInScene = function () {
  23488. var scene = this.getScene();
  23489. if (this._renderPriority != 0) {
  23490. scene.requireLightSorting = true;
  23491. }
  23492. this.getScene().sortLightsByPriority();
  23493. };
  23494. /**
  23495. * Falloff Default: light is falling off following the material specification:
  23496. * standard material is using standard falloff whereas pbr material can request special falloff per materials.
  23497. */
  23498. Light.FALLOFF_DEFAULT = 0;
  23499. /**
  23500. * Falloff Physical: light is falling off following the inverse squared distance law.
  23501. */
  23502. Light.FALLOFF_PHYSICAL = 1;
  23503. /**
  23504. * Falloff gltf: light is falling off as described in the gltf moving to PBR document
  23505. * to enhance interoperability with other engines.
  23506. */
  23507. Light.FALLOFF_GLTF = 2;
  23508. /**
  23509. * Falloff Standard: light is falling off like in the standard material
  23510. * to enhance interoperability with other materials.
  23511. */
  23512. Light.FALLOFF_STANDARD = 3;
  23513. //lightmapMode Consts
  23514. /**
  23515. * If every light affecting the material is in this lightmapMode,
  23516. * material.lightmapTexture adds or multiplies
  23517. * (depends on material.useLightmapAsShadowmap)
  23518. * after every other light calculations.
  23519. */
  23520. Light.LIGHTMAP_DEFAULT = 0;
  23521. /**
  23522. * material.lightmapTexture as only diffuse lighting from this light
  23523. * adds only specular lighting from this light
  23524. * adds dynamic shadows
  23525. */
  23526. Light.LIGHTMAP_SPECULAR = 1;
  23527. /**
  23528. * material.lightmapTexture as only lighting
  23529. * no light calculation from this light
  23530. * only adds dynamic shadows from this light
  23531. */
  23532. Light.LIGHTMAP_SHADOWSONLY = 2;
  23533. // Intensity Mode Consts
  23534. /**
  23535. * Each light type uses the default quantity according to its type:
  23536. * point/spot lights use luminous intensity
  23537. * directional lights use illuminance
  23538. */
  23539. Light.INTENSITYMODE_AUTOMATIC = 0;
  23540. /**
  23541. * lumen (lm)
  23542. */
  23543. Light.INTENSITYMODE_LUMINOUSPOWER = 1;
  23544. /**
  23545. * candela (lm/sr)
  23546. */
  23547. Light.INTENSITYMODE_LUMINOUSINTENSITY = 2;
  23548. /**
  23549. * lux (lm/m^2)
  23550. */
  23551. Light.INTENSITYMODE_ILLUMINANCE = 3;
  23552. /**
  23553. * nit (cd/m^2)
  23554. */
  23555. Light.INTENSITYMODE_LUMINANCE = 4;
  23556. // Light types ids const.
  23557. /**
  23558. * Light type const id of the point light.
  23559. */
  23560. Light.LIGHTTYPEID_POINTLIGHT = 0;
  23561. /**
  23562. * Light type const id of the directional light.
  23563. */
  23564. Light.LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  23565. /**
  23566. * Light type const id of the spot light.
  23567. */
  23568. Light.LIGHTTYPEID_SPOTLIGHT = 2;
  23569. /**
  23570. * Light type const id of the hemispheric light.
  23571. */
  23572. Light.LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  23573. __decorate([
  23574. BABYLON.serializeAsColor3()
  23575. ], Light.prototype, "diffuse", void 0);
  23576. __decorate([
  23577. BABYLON.serializeAsColor3()
  23578. ], Light.prototype, "specular", void 0);
  23579. __decorate([
  23580. BABYLON.serialize()
  23581. ], Light.prototype, "falloffType", void 0);
  23582. __decorate([
  23583. BABYLON.serialize()
  23584. ], Light.prototype, "intensity", void 0);
  23585. __decorate([
  23586. BABYLON.serialize()
  23587. ], Light.prototype, "range", null);
  23588. __decorate([
  23589. BABYLON.serialize()
  23590. ], Light.prototype, "intensityMode", null);
  23591. __decorate([
  23592. BABYLON.serialize()
  23593. ], Light.prototype, "radius", null);
  23594. __decorate([
  23595. BABYLON.serialize()
  23596. ], Light.prototype, "_renderPriority", void 0);
  23597. __decorate([
  23598. BABYLON.expandToProperty("_reorderLightsInScene")
  23599. ], Light.prototype, "renderPriority", void 0);
  23600. __decorate([
  23601. BABYLON.serialize("shadowEnabled")
  23602. ], Light.prototype, "_shadowEnabled", void 0);
  23603. __decorate([
  23604. BABYLON.serialize("excludeWithLayerMask")
  23605. ], Light.prototype, "_excludeWithLayerMask", void 0);
  23606. __decorate([
  23607. BABYLON.serialize("includeOnlyWithLayerMask")
  23608. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  23609. __decorate([
  23610. BABYLON.serialize("lightmapMode")
  23611. ], Light.prototype, "_lightmapMode", void 0);
  23612. return Light;
  23613. }(BABYLON.Node));
  23614. BABYLON.Light = Light;
  23615. })(BABYLON || (BABYLON = {}));
  23616. //# sourceMappingURL=babylon.light.js.map
  23617. var BABYLON;
  23618. (function (BABYLON) {
  23619. /**
  23620. * This is the base class of all the camera used in the application.
  23621. * @see http://doc.babylonjs.com/features/cameras
  23622. */
  23623. var Camera = /** @class */ (function (_super) {
  23624. __extends(Camera, _super);
  23625. /**
  23626. * Instantiates a new camera object.
  23627. * This should not be used directly but through the inherited cameras: ArcRotate, Free...
  23628. * @see http://doc.babylonjs.com/features/cameras
  23629. * @param name Defines the name of the camera in the scene
  23630. * @param position Defines the position of the camera
  23631. * @param scene Defines the scene the camera belongs too
  23632. * @param setActiveOnSceneIfNoneActive Defines if the camera should be set as active after creation if no other camera have been defined in the scene
  23633. */
  23634. function Camera(name, position, scene, setActiveOnSceneIfNoneActive) {
  23635. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  23636. var _this = _super.call(this, name, scene) || this;
  23637. /**
  23638. * The vector the camera should consider as up.
  23639. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  23640. */
  23641. _this.upVector = BABYLON.Vector3.Up();
  23642. /**
  23643. * Define the current limit on the left side for an orthographic camera
  23644. * In scene unit
  23645. */
  23646. _this.orthoLeft = null;
  23647. /**
  23648. * Define the current limit on the right side for an orthographic camera
  23649. * In scene unit
  23650. */
  23651. _this.orthoRight = null;
  23652. /**
  23653. * Define the current limit on the bottom side for an orthographic camera
  23654. * In scene unit
  23655. */
  23656. _this.orthoBottom = null;
  23657. /**
  23658. * Define the current limit on the top side for an orthographic camera
  23659. * In scene unit
  23660. */
  23661. _this.orthoTop = null;
  23662. /**
  23663. * Field Of View is set in Radians. (default is 0.8)
  23664. */
  23665. _this.fov = 0.8;
  23666. /**
  23667. * Define the minimum distance the camera can see from.
  23668. * This is important to note that the depth buffer are not infinite and the closer it starts
  23669. * the more your scene might encounter depth fighting issue.
  23670. */
  23671. _this.minZ = 1;
  23672. /**
  23673. * Define the maximum distance the camera can see to.
  23674. * This is important to note that the depth buffer are not infinite and the further it end
  23675. * the more your scene might encounter depth fighting issue.
  23676. */
  23677. _this.maxZ = 10000.0;
  23678. /**
  23679. * Define the default inertia of the camera.
  23680. * This helps giving a smooth feeling to the camera movement.
  23681. */
  23682. _this.inertia = 0.9;
  23683. /**
  23684. * Define the mode of the camera (Camera.PERSPECTIVE_CAMERA or Camera.PERSPECTIVE_ORTHOGRAPHIC)
  23685. */
  23686. _this.mode = Camera.PERSPECTIVE_CAMERA;
  23687. /**
  23688. * Define wether the camera is intermediate.
  23689. * This is usefull to not present the output directly to the screen in case of rig without post process for instance
  23690. */
  23691. _this.isIntermediate = false;
  23692. /**
  23693. * Define the viewport of the camera.
  23694. * This correspond to the portion of the screen the camera will render to in normalized 0 to 1 unit.
  23695. */
  23696. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  23697. /**
  23698. * Restricts the camera to viewing objects with the same layerMask.
  23699. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  23700. */
  23701. _this.layerMask = 0x0FFFFFFF;
  23702. /**
  23703. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  23704. */
  23705. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  23706. /**
  23707. * Rig mode of the camera.
  23708. * This is usefull to create the camera with two "eyes" instead of one to create VR or stereoscopic scenes.
  23709. * This is normally controlled byt the camera themselves as internal use.
  23710. */
  23711. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  23712. /**
  23713. * Defines the list of custom render target which are rendered to and then used as the input to this camera's render. Eg. display another camera view on a TV in the main scene
  23714. * This is pretty helpfull if you wish to make a camera render to a texture you could reuse somewhere
  23715. * else in the scene.
  23716. */
  23717. _this.customRenderTargets = new Array();
  23718. /**
  23719. * When set, the camera will render to this render target instead of the default canvas
  23720. */
  23721. _this.outputRenderTarget = null;
  23722. /**
  23723. * Observable triggered when the camera view matrix has changed.
  23724. */
  23725. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  23726. /**
  23727. * Observable triggered when the camera Projection matrix has changed.
  23728. */
  23729. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  23730. /**
  23731. * Observable triggered when the inputs have been processed.
  23732. */
  23733. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  23734. /**
  23735. * Observable triggered when reset has been called and applied to the camera.
  23736. */
  23737. _this.onRestoreStateObservable = new BABYLON.Observable();
  23738. /** @hidden */
  23739. _this._rigCameras = new Array();
  23740. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  23741. /** @hidden */
  23742. _this._skipRendering = false;
  23743. /** @hidden */
  23744. _this._projectionMatrix = new BABYLON.Matrix();
  23745. /** @hidden */
  23746. _this._postProcesses = new Array();
  23747. /** @hidden */
  23748. _this._activeMeshes = new BABYLON.SmartArray(256);
  23749. _this._globalPosition = BABYLON.Vector3.Zero();
  23750. /** hidden */
  23751. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  23752. _this._doNotComputeProjectionMatrix = false;
  23753. _this._transformMatrix = BABYLON.Matrix.Zero();
  23754. _this._refreshFrustumPlanes = true;
  23755. _this.getScene().addCamera(_this);
  23756. if (setActiveOnSceneIfNoneActive && !_this.getScene().activeCamera) {
  23757. _this.getScene().activeCamera = _this;
  23758. }
  23759. _this.position = position;
  23760. return _this;
  23761. }
  23762. /**
  23763. * Store current camera state (fov, position, etc..)
  23764. * @returns the camera
  23765. */
  23766. Camera.prototype.storeState = function () {
  23767. this._stateStored = true;
  23768. this._storedFov = this.fov;
  23769. return this;
  23770. };
  23771. /**
  23772. * Restores the camera state values if it has been stored. You must call storeState() first
  23773. */
  23774. Camera.prototype._restoreStateValues = function () {
  23775. if (!this._stateStored) {
  23776. return false;
  23777. }
  23778. this.fov = this._storedFov;
  23779. return true;
  23780. };
  23781. /**
  23782. * Restored camera state. You must call storeState() first.
  23783. * @returns true if restored and false otherwise
  23784. */
  23785. Camera.prototype.restoreState = function () {
  23786. if (this._restoreStateValues()) {
  23787. this.onRestoreStateObservable.notifyObservers(this);
  23788. return true;
  23789. }
  23790. return false;
  23791. };
  23792. /**
  23793. * Gets the class name of the camera.
  23794. * @returns the class name
  23795. */
  23796. Camera.prototype.getClassName = function () {
  23797. return "Camera";
  23798. };
  23799. /**
  23800. * Gets a string representation of the camera usefull for debug purpose.
  23801. * @param fullDetails Defines that a more verboe level of logging is required
  23802. * @returns the string representation
  23803. */
  23804. Camera.prototype.toString = function (fullDetails) {
  23805. var ret = "Name: " + this.name;
  23806. ret += ", type: " + this.getClassName();
  23807. if (this.animations) {
  23808. for (var i = 0; i < this.animations.length; i++) {
  23809. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  23810. }
  23811. }
  23812. if (fullDetails) {
  23813. }
  23814. return ret;
  23815. };
  23816. Object.defineProperty(Camera.prototype, "globalPosition", {
  23817. /**
  23818. * Gets the current world space position of the camera.
  23819. */
  23820. get: function () {
  23821. return this._globalPosition;
  23822. },
  23823. enumerable: true,
  23824. configurable: true
  23825. });
  23826. /**
  23827. * Gets the list of active meshes this frame (meshes no culled or excluded by lod s in the frame)
  23828. * @returns the active meshe list
  23829. */
  23830. Camera.prototype.getActiveMeshes = function () {
  23831. return this._activeMeshes;
  23832. };
  23833. /**
  23834. * Check wether a mesh is part of the current active mesh list of the camera
  23835. * @param mesh Defines the mesh to check
  23836. * @returns true if active, false otherwise
  23837. */
  23838. Camera.prototype.isActiveMesh = function (mesh) {
  23839. return (this._activeMeshes.indexOf(mesh) !== -1);
  23840. };
  23841. /**
  23842. * Is this camera ready to be used/rendered
  23843. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  23844. * @return true if the camera is ready
  23845. */
  23846. Camera.prototype.isReady = function (completeCheck) {
  23847. if (completeCheck === void 0) { completeCheck = false; }
  23848. if (completeCheck) {
  23849. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  23850. var pp = _a[_i];
  23851. if (pp && !pp.isReady()) {
  23852. return false;
  23853. }
  23854. }
  23855. }
  23856. return _super.prototype.isReady.call(this, completeCheck);
  23857. };
  23858. /** @hidden */
  23859. Camera.prototype._initCache = function () {
  23860. _super.prototype._initCache.call(this);
  23861. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  23862. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  23863. this._cache.mode = undefined;
  23864. this._cache.minZ = undefined;
  23865. this._cache.maxZ = undefined;
  23866. this._cache.fov = undefined;
  23867. this._cache.fovMode = undefined;
  23868. this._cache.aspectRatio = undefined;
  23869. this._cache.orthoLeft = undefined;
  23870. this._cache.orthoRight = undefined;
  23871. this._cache.orthoBottom = undefined;
  23872. this._cache.orthoTop = undefined;
  23873. this._cache.renderWidth = undefined;
  23874. this._cache.renderHeight = undefined;
  23875. };
  23876. /** @hidden */
  23877. Camera.prototype._updateCache = function (ignoreParentClass) {
  23878. if (!ignoreParentClass) {
  23879. _super.prototype._updateCache.call(this);
  23880. }
  23881. this._cache.position.copyFrom(this.position);
  23882. this._cache.upVector.copyFrom(this.upVector);
  23883. };
  23884. /** @hidden */
  23885. Camera.prototype._isSynchronized = function () {
  23886. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  23887. };
  23888. /** @hidden */
  23889. Camera.prototype._isSynchronizedViewMatrix = function () {
  23890. if (!_super.prototype._isSynchronized.call(this)) {
  23891. return false;
  23892. }
  23893. return this._cache.position.equals(this.position)
  23894. && this._cache.upVector.equals(this.upVector)
  23895. && this.isSynchronizedWithParent();
  23896. };
  23897. /** @hidden */
  23898. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  23899. var check = this._cache.mode === this.mode
  23900. && this._cache.minZ === this.minZ
  23901. && this._cache.maxZ === this.maxZ;
  23902. if (!check) {
  23903. return false;
  23904. }
  23905. var engine = this.getEngine();
  23906. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  23907. check = this._cache.fov === this.fov
  23908. && this._cache.fovMode === this.fovMode
  23909. && this._cache.aspectRatio === engine.getAspectRatio(this);
  23910. }
  23911. else {
  23912. check = this._cache.orthoLeft === this.orthoLeft
  23913. && this._cache.orthoRight === this.orthoRight
  23914. && this._cache.orthoBottom === this.orthoBottom
  23915. && this._cache.orthoTop === this.orthoTop
  23916. && this._cache.renderWidth === engine.getRenderWidth()
  23917. && this._cache.renderHeight === engine.getRenderHeight();
  23918. }
  23919. return check;
  23920. };
  23921. /**
  23922. * Attach the input controls to a specific dom element to get the input from.
  23923. * @param element Defines the element the controls should be listened from
  23924. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  23925. */
  23926. Camera.prototype.attachControl = function (element, noPreventDefault) {
  23927. };
  23928. /**
  23929. * Detach the current controls from the specified dom element.
  23930. * @param element Defines the element to stop listening the inputs from
  23931. */
  23932. Camera.prototype.detachControl = function (element) {
  23933. };
  23934. /**
  23935. * Update the camera state according to the different inputs gathered during the frame.
  23936. */
  23937. Camera.prototype.update = function () {
  23938. this._checkInputs();
  23939. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  23940. this._updateRigCameras();
  23941. }
  23942. };
  23943. /** @hidden */
  23944. Camera.prototype._checkInputs = function () {
  23945. this.onAfterCheckInputsObservable.notifyObservers(this);
  23946. };
  23947. Object.defineProperty(Camera.prototype, "rigCameras", {
  23948. /** @hidden */
  23949. get: function () {
  23950. return this._rigCameras;
  23951. },
  23952. enumerable: true,
  23953. configurable: true
  23954. });
  23955. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  23956. /**
  23957. * Gets the post process used by the rig cameras
  23958. */
  23959. get: function () {
  23960. return this._rigPostProcess;
  23961. },
  23962. enumerable: true,
  23963. configurable: true
  23964. });
  23965. /**
  23966. * Internal, gets the first post proces.
  23967. * @returns the first post process to be run on this camera.
  23968. */
  23969. Camera.prototype._getFirstPostProcess = function () {
  23970. for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
  23971. if (this._postProcesses[ppIndex] !== null) {
  23972. return this._postProcesses[ppIndex];
  23973. }
  23974. }
  23975. return null;
  23976. };
  23977. Camera.prototype._cascadePostProcessesToRigCams = function () {
  23978. // invalidate framebuffer
  23979. var firstPostProcess = this._getFirstPostProcess();
  23980. if (firstPostProcess) {
  23981. firstPostProcess.markTextureDirty();
  23982. }
  23983. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  23984. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  23985. var cam = this._rigCameras[i];
  23986. var rigPostProcess = cam._rigPostProcess;
  23987. // for VR rig, there does not have to be a post process
  23988. if (rigPostProcess) {
  23989. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  23990. if (isPass) {
  23991. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  23992. cam.isIntermediate = this._postProcesses.length === 0;
  23993. }
  23994. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  23995. rigPostProcess.markTextureDirty();
  23996. }
  23997. else {
  23998. cam._postProcesses = this._postProcesses.slice(0);
  23999. }
  24000. }
  24001. };
  24002. /**
  24003. * Attach a post process to the camera.
  24004. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocesses#attach-postprocess
  24005. * @param postProcess The post process to attach to the camera
  24006. * @param insertAt The position of the post process in case several of them are in use in the scene
  24007. * @returns the position the post process has been inserted at
  24008. */
  24009. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  24010. if (insertAt === void 0) { insertAt = null; }
  24011. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  24012. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  24013. return 0;
  24014. }
  24015. if (insertAt == null || insertAt < 0) {
  24016. this._postProcesses.push(postProcess);
  24017. }
  24018. else if (this._postProcesses[insertAt] === null) {
  24019. this._postProcesses[insertAt] = postProcess;
  24020. }
  24021. else {
  24022. this._postProcesses.splice(insertAt, 0, postProcess);
  24023. }
  24024. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  24025. return this._postProcesses.indexOf(postProcess);
  24026. };
  24027. /**
  24028. * Detach a post process to the camera.
  24029. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocesses#attach-postprocess
  24030. * @param postProcess The post process to detach from the camera
  24031. */
  24032. Camera.prototype.detachPostProcess = function (postProcess) {
  24033. var idx = this._postProcesses.indexOf(postProcess);
  24034. if (idx !== -1) {
  24035. this._postProcesses[idx] = null;
  24036. }
  24037. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  24038. };
  24039. /**
  24040. * Gets the current world matrix of the camera
  24041. */
  24042. Camera.prototype.getWorldMatrix = function () {
  24043. if (this._isSynchronizedViewMatrix()) {
  24044. return this._worldMatrix;
  24045. }
  24046. // Getting the the view matrix will also compute the world matrix.
  24047. this.getViewMatrix();
  24048. return this._worldMatrix;
  24049. };
  24050. /** @hidden */
  24051. Camera.prototype._getViewMatrix = function () {
  24052. return BABYLON.Matrix.Identity();
  24053. };
  24054. /**
  24055. * Gets the current view matrix of the camera.
  24056. * @param force forces the camera to recompute the matrix without looking at the cached state
  24057. * @returns the view matrix
  24058. */
  24059. Camera.prototype.getViewMatrix = function (force) {
  24060. if (!force && this._isSynchronizedViewMatrix()) {
  24061. return this._computedViewMatrix;
  24062. }
  24063. this.updateCache();
  24064. this._computedViewMatrix = this._getViewMatrix();
  24065. this._currentRenderId = this.getScene().getRenderId();
  24066. this._childRenderId = this._currentRenderId;
  24067. this._refreshFrustumPlanes = true;
  24068. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  24069. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  24070. }
  24071. this.onViewMatrixChangedObservable.notifyObservers(this);
  24072. this._computedViewMatrix.invertToRef(this._worldMatrix);
  24073. return this._computedViewMatrix;
  24074. };
  24075. /**
  24076. * Freeze the projection matrix.
  24077. * It will prevent the cache check of the camera projection compute and can speed up perf
  24078. * if no parameter of the camera are meant to change
  24079. * @param projection Defines manually a projection if necessary
  24080. */
  24081. Camera.prototype.freezeProjectionMatrix = function (projection) {
  24082. this._doNotComputeProjectionMatrix = true;
  24083. if (projection !== undefined) {
  24084. this._projectionMatrix = projection;
  24085. }
  24086. };
  24087. /**
  24088. * Unfreeze the projection matrix if it has previously been freezed by freezeProjectionMatrix.
  24089. */
  24090. Camera.prototype.unfreezeProjectionMatrix = function () {
  24091. this._doNotComputeProjectionMatrix = false;
  24092. };
  24093. /**
  24094. * Gets the current projection matrix of the camera.
  24095. * @param force forces the camera to recompute the matrix without looking at the cached state
  24096. * @returns the projection matrix
  24097. */
  24098. Camera.prototype.getProjectionMatrix = function (force) {
  24099. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  24100. return this._projectionMatrix;
  24101. }
  24102. // Cache
  24103. this._cache.mode = this.mode;
  24104. this._cache.minZ = this.minZ;
  24105. this._cache.maxZ = this.maxZ;
  24106. // Matrix
  24107. this._refreshFrustumPlanes = true;
  24108. var engine = this.getEngine();
  24109. var scene = this.getScene();
  24110. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  24111. this._cache.fov = this.fov;
  24112. this._cache.fovMode = this.fovMode;
  24113. this._cache.aspectRatio = engine.getAspectRatio(this);
  24114. if (this.minZ <= 0) {
  24115. this.minZ = 0.1;
  24116. }
  24117. if (scene.useRightHandedSystem) {
  24118. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  24119. }
  24120. else {
  24121. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  24122. }
  24123. }
  24124. else {
  24125. var halfWidth = engine.getRenderWidth() / 2.0;
  24126. var halfHeight = engine.getRenderHeight() / 2.0;
  24127. if (scene.useRightHandedSystem) {
  24128. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  24129. }
  24130. else {
  24131. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  24132. }
  24133. this._cache.orthoLeft = this.orthoLeft;
  24134. this._cache.orthoRight = this.orthoRight;
  24135. this._cache.orthoBottom = this.orthoBottom;
  24136. this._cache.orthoTop = this.orthoTop;
  24137. this._cache.renderWidth = engine.getRenderWidth();
  24138. this._cache.renderHeight = engine.getRenderHeight();
  24139. }
  24140. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  24141. return this._projectionMatrix;
  24142. };
  24143. /**
  24144. * Gets the transformation matrix (ie. the multiplication of view by projection matrices)
  24145. * @returns a Matrix
  24146. */
  24147. Camera.prototype.getTransformationMatrix = function () {
  24148. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  24149. return this._transformMatrix;
  24150. };
  24151. Camera.prototype._updateFrustumPlanes = function () {
  24152. if (!this._refreshFrustumPlanes) {
  24153. return;
  24154. }
  24155. this.getTransformationMatrix();
  24156. if (!this._frustumPlanes) {
  24157. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  24158. }
  24159. else {
  24160. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  24161. }
  24162. this._refreshFrustumPlanes = false;
  24163. };
  24164. /**
  24165. * Checks if a cullable object (mesh...) is in the camera frustum
  24166. * This checks the bounding box center. See isCompletelyInFrustum for a full bounding check
  24167. * @param target The object to check
  24168. * @returns true if the object is in frustum otherwise false
  24169. */
  24170. Camera.prototype.isInFrustum = function (target) {
  24171. this._updateFrustumPlanes();
  24172. return target.isInFrustum(this._frustumPlanes);
  24173. };
  24174. /**
  24175. * Checks if a cullable object (mesh...) is in the camera frustum
  24176. * Unlike isInFrustum this cheks the full bounding box
  24177. * @param target The object to check
  24178. * @returns true if the object is in frustum otherwise false
  24179. */
  24180. Camera.prototype.isCompletelyInFrustum = function (target) {
  24181. this._updateFrustumPlanes();
  24182. return target.isCompletelyInFrustum(this._frustumPlanes);
  24183. };
  24184. /**
  24185. * Gets a ray in the forward direction from the camera.
  24186. * @param length Defines the length of the ray to create
  24187. * @param transform Defines the transform to apply to the ray, by default the world matrx is used to create a workd space ray
  24188. * @param origin Defines the start point of the ray which defaults to the camera position
  24189. * @returns the forward ray
  24190. */
  24191. Camera.prototype.getForwardRay = function (length, transform, origin) {
  24192. if (length === void 0) { length = 100; }
  24193. if (!transform) {
  24194. transform = this.getWorldMatrix();
  24195. }
  24196. if (!origin) {
  24197. origin = this.position;
  24198. }
  24199. var forward = this._scene.useRightHandedSystem ? new BABYLON.Vector3(0, 0, -1) : new BABYLON.Vector3(0, 0, 1);
  24200. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  24201. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  24202. return new BABYLON.Ray(origin, direction, length);
  24203. };
  24204. /**
  24205. * Releases resources associated with this node.
  24206. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  24207. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  24208. */
  24209. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  24210. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  24211. // Observables
  24212. this.onViewMatrixChangedObservable.clear();
  24213. this.onProjectionMatrixChangedObservable.clear();
  24214. this.onAfterCheckInputsObservable.clear();
  24215. this.onRestoreStateObservable.clear();
  24216. // Inputs
  24217. if (this.inputs) {
  24218. this.inputs.clear();
  24219. }
  24220. // Animations
  24221. this.getScene().stopAnimation(this);
  24222. // Remove from scene
  24223. this.getScene().removeCamera(this);
  24224. while (this._rigCameras.length > 0) {
  24225. var camera = this._rigCameras.pop();
  24226. if (camera) {
  24227. camera.dispose();
  24228. }
  24229. }
  24230. // Postprocesses
  24231. if (this._rigPostProcess) {
  24232. this._rigPostProcess.dispose(this);
  24233. this._rigPostProcess = null;
  24234. this._postProcesses = [];
  24235. }
  24236. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  24237. this._rigPostProcess = null;
  24238. this._postProcesses = [];
  24239. }
  24240. else {
  24241. var i = this._postProcesses.length;
  24242. while (--i >= 0) {
  24243. var postProcess = this._postProcesses[i];
  24244. if (postProcess) {
  24245. postProcess.dispose(this);
  24246. }
  24247. }
  24248. }
  24249. // Render targets
  24250. var i = this.customRenderTargets.length;
  24251. while (--i >= 0) {
  24252. this.customRenderTargets[i].dispose();
  24253. }
  24254. this.customRenderTargets = [];
  24255. // Active Meshes
  24256. this._activeMeshes.dispose();
  24257. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  24258. };
  24259. Object.defineProperty(Camera.prototype, "leftCamera", {
  24260. /**
  24261. * Gets the left camera of a rig setup in case of Rigged Camera
  24262. */
  24263. get: function () {
  24264. if (this._rigCameras.length < 1) {
  24265. return null;
  24266. }
  24267. return this._rigCameras[0];
  24268. },
  24269. enumerable: true,
  24270. configurable: true
  24271. });
  24272. Object.defineProperty(Camera.prototype, "rightCamera", {
  24273. /**
  24274. * Gets the right camera of a rig setup in case of Rigged Camera
  24275. */
  24276. get: function () {
  24277. if (this._rigCameras.length < 2) {
  24278. return null;
  24279. }
  24280. return this._rigCameras[1];
  24281. },
  24282. enumerable: true,
  24283. configurable: true
  24284. });
  24285. /**
  24286. * Gets the left camera target of a rig setup in case of Rigged Camera
  24287. * @returns the target position
  24288. */
  24289. Camera.prototype.getLeftTarget = function () {
  24290. if (this._rigCameras.length < 1) {
  24291. return null;
  24292. }
  24293. return this._rigCameras[0].getTarget();
  24294. };
  24295. /**
  24296. * Gets the right camera target of a rig setup in case of Rigged Camera
  24297. * @returns the target position
  24298. */
  24299. Camera.prototype.getRightTarget = function () {
  24300. if (this._rigCameras.length < 2) {
  24301. return null;
  24302. }
  24303. return this._rigCameras[1].getTarget();
  24304. };
  24305. /**
  24306. * @hidden
  24307. */
  24308. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  24309. if (this.cameraRigMode === mode) {
  24310. return;
  24311. }
  24312. while (this._rigCameras.length > 0) {
  24313. var camera = this._rigCameras.pop();
  24314. if (camera) {
  24315. camera.dispose();
  24316. }
  24317. }
  24318. this.cameraRigMode = mode;
  24319. this._cameraRigParams = {};
  24320. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  24321. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  24322. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  24323. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  24324. // create the rig cameras, unless none
  24325. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  24326. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  24327. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  24328. if (leftCamera && rightCamera) {
  24329. this._rigCameras.push(leftCamera);
  24330. this._rigCameras.push(rightCamera);
  24331. }
  24332. }
  24333. switch (this.cameraRigMode) {
  24334. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  24335. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  24336. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  24337. break;
  24338. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  24339. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  24340. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  24341. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  24342. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  24343. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  24344. break;
  24345. case Camera.RIG_MODE_VR:
  24346. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  24347. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  24348. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  24349. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  24350. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  24351. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  24352. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  24353. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  24354. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  24355. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  24356. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  24357. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  24358. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  24359. if (metrics.compensateDistortion) {
  24360. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  24361. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  24362. }
  24363. break;
  24364. case Camera.RIG_MODE_WEBVR:
  24365. if (rigParams.vrDisplay) {
  24366. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  24367. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  24368. //Left eye
  24369. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  24370. this._rigCameras[0].setCameraRigParameter("left", true);
  24371. //leaving this for future reference
  24372. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  24373. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  24374. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  24375. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  24376. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  24377. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  24378. this._rigCameras[0].parent = this;
  24379. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  24380. //Right eye
  24381. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  24382. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  24383. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  24384. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  24385. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  24386. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  24387. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  24388. this._rigCameras[1].parent = this;
  24389. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  24390. if (Camera.UseAlternateWebVRRendering) {
  24391. this._rigCameras[1]._skipRendering = true;
  24392. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  24393. }
  24394. }
  24395. break;
  24396. }
  24397. this._cascadePostProcessesToRigCams();
  24398. this.update();
  24399. };
  24400. Camera.prototype._getVRProjectionMatrix = function () {
  24401. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  24402. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  24403. return this._projectionMatrix;
  24404. };
  24405. Camera.prototype._updateCameraRotationMatrix = function () {
  24406. //Here for WebVR
  24407. };
  24408. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  24409. //Here for WebVR
  24410. };
  24411. /**
  24412. * This function MUST be overwritten by the different WebVR cameras available.
  24413. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  24414. */
  24415. Camera.prototype._getWebVRProjectionMatrix = function () {
  24416. return BABYLON.Matrix.Identity();
  24417. };
  24418. /**
  24419. * This function MUST be overwritten by the different WebVR cameras available.
  24420. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  24421. */
  24422. Camera.prototype._getWebVRViewMatrix = function () {
  24423. return BABYLON.Matrix.Identity();
  24424. };
  24425. /** @hidden */
  24426. Camera.prototype.setCameraRigParameter = function (name, value) {
  24427. if (!this._cameraRigParams) {
  24428. this._cameraRigParams = {};
  24429. }
  24430. this._cameraRigParams[name] = value;
  24431. //provisionnally:
  24432. if (name === "interaxialDistance") {
  24433. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  24434. }
  24435. };
  24436. /**
  24437. * needs to be overridden by children so sub has required properties to be copied
  24438. * @hidden
  24439. */
  24440. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  24441. return null;
  24442. };
  24443. /**
  24444. * May need to be overridden by children
  24445. * @hidden
  24446. */
  24447. Camera.prototype._updateRigCameras = function () {
  24448. for (var i = 0; i < this._rigCameras.length; i++) {
  24449. this._rigCameras[i].minZ = this.minZ;
  24450. this._rigCameras[i].maxZ = this.maxZ;
  24451. this._rigCameras[i].fov = this.fov;
  24452. }
  24453. // only update viewport when ANAGLYPH
  24454. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  24455. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  24456. }
  24457. };
  24458. /** @hidden */
  24459. Camera.prototype._setupInputs = function () {
  24460. };
  24461. /**
  24462. * Serialiaze the camera setup to a json represention
  24463. * @returns the JSON representation
  24464. */
  24465. Camera.prototype.serialize = function () {
  24466. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  24467. // Type
  24468. serializationObject.type = this.getClassName();
  24469. // Parent
  24470. if (this.parent) {
  24471. serializationObject.parentId = this.parent.id;
  24472. }
  24473. if (this.inputs) {
  24474. this.inputs.serialize(serializationObject);
  24475. }
  24476. // Animations
  24477. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  24478. serializationObject.ranges = this.serializeAnimationRanges();
  24479. return serializationObject;
  24480. };
  24481. /**
  24482. * Clones the current camera.
  24483. * @param name The cloned camera name
  24484. * @returns the cloned camera
  24485. */
  24486. Camera.prototype.clone = function (name) {
  24487. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  24488. };
  24489. /**
  24490. * Gets the direction of the camera relative to a given local axis.
  24491. * @param localAxis Defines the reference axis to provide a relative direction.
  24492. * @return the direction
  24493. */
  24494. Camera.prototype.getDirection = function (localAxis) {
  24495. var result = BABYLON.Vector3.Zero();
  24496. this.getDirectionToRef(localAxis, result);
  24497. return result;
  24498. };
  24499. /**
  24500. * Gets the direction of the camera relative to a given local axis into a passed vector.
  24501. * @param localAxis Defines the reference axis to provide a relative direction.
  24502. * @param result Defines the vector to store the result in
  24503. */
  24504. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  24505. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  24506. };
  24507. /**
  24508. * Gets a camera constructor for a given camera type
  24509. * @param type The type of the camera to construct (should be equal to one of the camera class name)
  24510. * @param name The name of the camera the result will be able to instantiate
  24511. * @param scene The scene the result will construct the camera in
  24512. * @param interaxial_distance In case of stereoscopic setup, the distance between both eyes
  24513. * @param isStereoscopicSideBySide In case of stereoscopic setup, should the sereo be side b side
  24514. * @returns a factory method to construc the camera
  24515. */
  24516. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  24517. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  24518. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  24519. var constructorFunc = BABYLON.Node.Construct(type, name, scene, {
  24520. interaxial_distance: interaxial_distance,
  24521. isStereoscopicSideBySide: isStereoscopicSideBySide
  24522. });
  24523. if (constructorFunc) {
  24524. return constructorFunc;
  24525. }
  24526. // Default to universal camera
  24527. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  24528. };
  24529. /**
  24530. * Compute the world matrix of the camera.
  24531. * @returns the camera workd matrix
  24532. */
  24533. Camera.prototype.computeWorldMatrix = function () {
  24534. return this.getWorldMatrix();
  24535. };
  24536. /**
  24537. * Parse a JSON and creates the camera from the parsed information
  24538. * @param parsedCamera The JSON to parse
  24539. * @param scene The scene to instantiate the camera in
  24540. * @returns the newly constructed camera
  24541. */
  24542. Camera.Parse = function (parsedCamera, scene) {
  24543. var type = parsedCamera.type;
  24544. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  24545. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  24546. // Parent
  24547. if (parsedCamera.parentId) {
  24548. camera._waitingParentId = parsedCamera.parentId;
  24549. }
  24550. //If camera has an input manager, let it parse inputs settings
  24551. if (camera.inputs) {
  24552. camera.inputs.parse(parsedCamera);
  24553. camera._setupInputs();
  24554. }
  24555. if (camera.setPosition) { // need to force position
  24556. camera.position.copyFromFloats(0, 0, 0);
  24557. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  24558. }
  24559. // Target
  24560. if (parsedCamera.target) {
  24561. if (camera.setTarget) {
  24562. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  24563. }
  24564. }
  24565. // Apply 3d rig, when found
  24566. if (parsedCamera.cameraRigMode) {
  24567. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  24568. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  24569. }
  24570. // Animations
  24571. if (parsedCamera.animations) {
  24572. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  24573. var parsedAnimation = parsedCamera.animations[animationIndex];
  24574. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  24575. }
  24576. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  24577. }
  24578. if (parsedCamera.autoAnimate) {
  24579. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  24580. }
  24581. return camera;
  24582. };
  24583. /**
  24584. * This is the default projection mode used by the cameras.
  24585. * It helps recreating a feeling of perspective and better appreciate depth.
  24586. * This is the best way to simulate real life cameras.
  24587. */
  24588. Camera.PERSPECTIVE_CAMERA = 0;
  24589. /**
  24590. * This helps creating camera with an orthographic mode.
  24591. * 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.
  24592. */
  24593. Camera.ORTHOGRAPHIC_CAMERA = 1;
  24594. /**
  24595. * This is the default FOV mode for perspective cameras.
  24596. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  24597. */
  24598. Camera.FOVMODE_VERTICAL_FIXED = 0;
  24599. /**
  24600. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  24601. */
  24602. Camera.FOVMODE_HORIZONTAL_FIXED = 1;
  24603. /**
  24604. * This specifies ther is no need for a camera rig.
  24605. * Basically only one eye is rendered corresponding to the camera.
  24606. */
  24607. Camera.RIG_MODE_NONE = 0;
  24608. /**
  24609. * Simulates a camera Rig with one blue eye and one red eye.
  24610. * This can be use with 3d blue and red glasses.
  24611. */
  24612. Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  24613. /**
  24614. * Defines that both eyes of the camera will be rendered side by side with a parallel target.
  24615. */
  24616. Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  24617. /**
  24618. * Defines that both eyes of the camera will be rendered side by side with a none parallel target.
  24619. */
  24620. Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  24621. /**
  24622. * Defines that both eyes of the camera will be rendered over under each other.
  24623. */
  24624. Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  24625. /**
  24626. * Defines that both eyes of the camera should be renderered in a VR mode (carbox).
  24627. */
  24628. Camera.RIG_MODE_VR = 20;
  24629. /**
  24630. * Defines that both eyes of the camera should be renderered in a VR mode (webVR).
  24631. */
  24632. Camera.RIG_MODE_WEBVR = 21;
  24633. /**
  24634. * Custom rig mode allowing rig cameras to be populated manually with any number of cameras
  24635. */
  24636. Camera.RIG_MODE_CUSTOM = 22;
  24637. /**
  24638. * Defines if by default attaching controls should prevent the default javascript event to continue.
  24639. */
  24640. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  24641. /**
  24642. * @hidden
  24643. * Might be removed once multiview will be a thing
  24644. */
  24645. Camera.UseAlternateWebVRRendering = false;
  24646. __decorate([
  24647. BABYLON.serializeAsVector3()
  24648. ], Camera.prototype, "position", void 0);
  24649. __decorate([
  24650. BABYLON.serializeAsVector3()
  24651. ], Camera.prototype, "upVector", void 0);
  24652. __decorate([
  24653. BABYLON.serialize()
  24654. ], Camera.prototype, "orthoLeft", void 0);
  24655. __decorate([
  24656. BABYLON.serialize()
  24657. ], Camera.prototype, "orthoRight", void 0);
  24658. __decorate([
  24659. BABYLON.serialize()
  24660. ], Camera.prototype, "orthoBottom", void 0);
  24661. __decorate([
  24662. BABYLON.serialize()
  24663. ], Camera.prototype, "orthoTop", void 0);
  24664. __decorate([
  24665. BABYLON.serialize()
  24666. ], Camera.prototype, "fov", void 0);
  24667. __decorate([
  24668. BABYLON.serialize()
  24669. ], Camera.prototype, "minZ", void 0);
  24670. __decorate([
  24671. BABYLON.serialize()
  24672. ], Camera.prototype, "maxZ", void 0);
  24673. __decorate([
  24674. BABYLON.serialize()
  24675. ], Camera.prototype, "inertia", void 0);
  24676. __decorate([
  24677. BABYLON.serialize()
  24678. ], Camera.prototype, "mode", void 0);
  24679. __decorate([
  24680. BABYLON.serialize()
  24681. ], Camera.prototype, "layerMask", void 0);
  24682. __decorate([
  24683. BABYLON.serialize()
  24684. ], Camera.prototype, "fovMode", void 0);
  24685. __decorate([
  24686. BABYLON.serialize()
  24687. ], Camera.prototype, "cameraRigMode", void 0);
  24688. __decorate([
  24689. BABYLON.serialize()
  24690. ], Camera.prototype, "interaxialDistance", void 0);
  24691. __decorate([
  24692. BABYLON.serialize()
  24693. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  24694. return Camera;
  24695. }(BABYLON.Node));
  24696. BABYLON.Camera = Camera;
  24697. })(BABYLON || (BABYLON = {}));
  24698. //# sourceMappingURL=babylon.camera.js.map
  24699. var BABYLON;
  24700. (function (BABYLON) {
  24701. /**
  24702. * This is the manager responsible of all the rendering for meshes sprites and particles.
  24703. * It is enable to manage the different groups as well as the different necessary sort functions.
  24704. * This should not be used directly aside of the few static configurations
  24705. */
  24706. var RenderingManager = /** @class */ (function () {
  24707. /**
  24708. * Instantiates a new rendering group for a particular scene
  24709. * @param scene Defines the scene the groups belongs to
  24710. */
  24711. function RenderingManager(scene) {
  24712. /**
  24713. * @hidden
  24714. */
  24715. this._useSceneAutoClearSetup = false;
  24716. this._renderingGroups = new Array();
  24717. this._autoClearDepthStencil = {};
  24718. this._customOpaqueSortCompareFn = {};
  24719. this._customAlphaTestSortCompareFn = {};
  24720. this._customTransparentSortCompareFn = {};
  24721. this._renderingGroupInfo = new BABYLON.RenderingGroupInfo();
  24722. this._scene = scene;
  24723. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  24724. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  24725. }
  24726. }
  24727. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  24728. if (depth === void 0) { depth = true; }
  24729. if (stencil === void 0) { stencil = true; }
  24730. if (this._depthStencilBufferAlreadyCleaned) {
  24731. return;
  24732. }
  24733. this._scene.getEngine().clear(null, false, depth, stencil);
  24734. this._depthStencilBufferAlreadyCleaned = true;
  24735. };
  24736. /**
  24737. * Renders the entire managed groups. This is used by the scene or the different rennder targets.
  24738. * @hidden
  24739. */
  24740. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  24741. // Update the observable context (not null as it only goes away on dispose)
  24742. var info = this._renderingGroupInfo;
  24743. info.scene = this._scene;
  24744. info.camera = this._scene.activeCamera;
  24745. // Dispatch sprites
  24746. if (this._scene.spriteManagers && renderSprites) {
  24747. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  24748. var manager = this._scene.spriteManagers[index];
  24749. this.dispatchSprites(manager);
  24750. }
  24751. }
  24752. // Render
  24753. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  24754. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  24755. var renderingGroup = this._renderingGroups[index];
  24756. if (!renderingGroup) {
  24757. continue;
  24758. }
  24759. var renderingGroupMask = Math.pow(2, index);
  24760. info.renderingGroupId = index;
  24761. // Before Observable
  24762. this._scene.onBeforeRenderingGroupObservable.notifyObservers(info, renderingGroupMask);
  24763. // Clear depth/stencil if needed
  24764. if (RenderingManager.AUTOCLEAR) {
  24765. var autoClear = this._useSceneAutoClearSetup ?
  24766. this._scene.getAutoClearDepthStencilSetup(index) :
  24767. this._autoClearDepthStencil[index];
  24768. if (autoClear && autoClear.autoClear) {
  24769. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  24770. }
  24771. }
  24772. // Render
  24773. for (var _i = 0, _a = this._scene._beforeRenderingGroupDrawStage; _i < _a.length; _i++) {
  24774. var step = _a[_i];
  24775. step.action(index);
  24776. }
  24777. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  24778. for (var _b = 0, _c = this._scene._afterRenderingGroupDrawStage; _b < _c.length; _b++) {
  24779. var step = _c[_b];
  24780. step.action(index);
  24781. }
  24782. // After Observable
  24783. this._scene.onAfterRenderingGroupObservable.notifyObservers(info, renderingGroupMask);
  24784. }
  24785. };
  24786. /**
  24787. * Resets the different information of the group to prepare a new frame
  24788. * @hidden
  24789. */
  24790. RenderingManager.prototype.reset = function () {
  24791. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  24792. var renderingGroup = this._renderingGroups[index];
  24793. if (renderingGroup) {
  24794. renderingGroup.prepare();
  24795. }
  24796. }
  24797. };
  24798. /**
  24799. * Dispose and release the group and its associated resources.
  24800. * @hidden
  24801. */
  24802. RenderingManager.prototype.dispose = function () {
  24803. this.freeRenderingGroups();
  24804. this._renderingGroups.length = 0;
  24805. this._renderingGroupInfo = null;
  24806. };
  24807. /**
  24808. * Clear the info related to rendering groups preventing retention points during dispose.
  24809. */
  24810. RenderingManager.prototype.freeRenderingGroups = function () {
  24811. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  24812. var renderingGroup = this._renderingGroups[index];
  24813. if (renderingGroup) {
  24814. renderingGroup.dispose();
  24815. }
  24816. }
  24817. };
  24818. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  24819. if (this._renderingGroups[renderingGroupId] === undefined) {
  24820. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  24821. }
  24822. };
  24823. /**
  24824. * Add a sprite manager to the rendering manager in order to render it this frame.
  24825. * @param spriteManager Define the sprite manager to render
  24826. */
  24827. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  24828. var renderingGroupId = spriteManager.renderingGroupId || 0;
  24829. this._prepareRenderingGroup(renderingGroupId);
  24830. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  24831. };
  24832. /**
  24833. * Add a particle system to the rendering manager in order to render it this frame.
  24834. * @param particleSystem Define the particle system to render
  24835. */
  24836. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  24837. var renderingGroupId = particleSystem.renderingGroupId || 0;
  24838. this._prepareRenderingGroup(renderingGroupId);
  24839. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  24840. };
  24841. /**
  24842. * Add a submesh to the manager in order to render it this frame
  24843. * @param subMesh The submesh to dispatch
  24844. * @param mesh Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  24845. * @param material Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  24846. */
  24847. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  24848. if (mesh === undefined) {
  24849. mesh = subMesh.getMesh();
  24850. }
  24851. var renderingGroupId = mesh.renderingGroupId || 0;
  24852. this._prepareRenderingGroup(renderingGroupId);
  24853. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  24854. };
  24855. /**
  24856. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  24857. * This allowed control for front to back rendering or reversly depending of the special needs.
  24858. *
  24859. * @param renderingGroupId The rendering group id corresponding to its index
  24860. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  24861. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  24862. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  24863. */
  24864. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  24865. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  24866. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  24867. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  24868. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  24869. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  24870. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  24871. if (this._renderingGroups[renderingGroupId]) {
  24872. var group = this._renderingGroups[renderingGroupId];
  24873. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  24874. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  24875. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  24876. }
  24877. };
  24878. /**
  24879. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  24880. *
  24881. * @param renderingGroupId The rendering group id corresponding to its index
  24882. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  24883. * @param depth Automatically clears depth between groups if true and autoClear is true.
  24884. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  24885. */
  24886. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  24887. if (depth === void 0) { depth = true; }
  24888. if (stencil === void 0) { stencil = true; }
  24889. this._autoClearDepthStencil[renderingGroupId] = {
  24890. autoClear: autoClearDepthStencil,
  24891. depth: depth,
  24892. stencil: stencil
  24893. };
  24894. };
  24895. /**
  24896. * Gets the current auto clear configuration for one rendering group of the rendering
  24897. * manager.
  24898. * @param index the rendering group index to get the information for
  24899. * @returns The auto clear setup for the requested rendering group
  24900. */
  24901. RenderingManager.prototype.getAutoClearDepthStencilSetup = function (index) {
  24902. return this._autoClearDepthStencil[index];
  24903. };
  24904. /**
  24905. * The max id used for rendering groups (not included)
  24906. */
  24907. RenderingManager.MAX_RENDERINGGROUPS = 4;
  24908. /**
  24909. * The min id used for rendering groups (included)
  24910. */
  24911. RenderingManager.MIN_RENDERINGGROUPS = 0;
  24912. /**
  24913. * Used to globally prevent autoclearing scenes.
  24914. */
  24915. RenderingManager.AUTOCLEAR = true;
  24916. return RenderingManager;
  24917. }());
  24918. BABYLON.RenderingManager = RenderingManager;
  24919. })(BABYLON || (BABYLON = {}));
  24920. //# sourceMappingURL=babylon.renderingManager.js.map
  24921. var BABYLON;
  24922. (function (BABYLON) {
  24923. /**
  24924. * This represents the object necessary to create a rendering group.
  24925. * This is exclusively used and created by the rendering manager.
  24926. * To modify the behavior, you use the available helpers in your scene or meshes.
  24927. * @hidden
  24928. */
  24929. var RenderingGroup = /** @class */ (function () {
  24930. /**
  24931. * Creates a new rendering group.
  24932. * @param index The rendering group index
  24933. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  24934. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  24935. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  24936. */
  24937. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  24938. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  24939. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  24940. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  24941. this.index = index;
  24942. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  24943. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  24944. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  24945. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  24946. this._particleSystems = new BABYLON.SmartArray(256);
  24947. this._spriteManagers = new BABYLON.SmartArray(256);
  24948. this._edgesRenderers = new BABYLON.SmartArray(16);
  24949. this._scene = scene;
  24950. this.opaqueSortCompareFn = opaqueSortCompareFn;
  24951. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  24952. this.transparentSortCompareFn = transparentSortCompareFn;
  24953. }
  24954. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  24955. /**
  24956. * Set the opaque sort comparison function.
  24957. * If null the sub meshes will be render in the order they were created
  24958. */
  24959. set: function (value) {
  24960. this._opaqueSortCompareFn = value;
  24961. if (value) {
  24962. this._renderOpaque = this.renderOpaqueSorted;
  24963. }
  24964. else {
  24965. this._renderOpaque = RenderingGroup.renderUnsorted;
  24966. }
  24967. },
  24968. enumerable: true,
  24969. configurable: true
  24970. });
  24971. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  24972. /**
  24973. * Set the alpha test sort comparison function.
  24974. * If null the sub meshes will be render in the order they were created
  24975. */
  24976. set: function (value) {
  24977. this._alphaTestSortCompareFn = value;
  24978. if (value) {
  24979. this._renderAlphaTest = this.renderAlphaTestSorted;
  24980. }
  24981. else {
  24982. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  24983. }
  24984. },
  24985. enumerable: true,
  24986. configurable: true
  24987. });
  24988. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  24989. /**
  24990. * Set the transparent sort comparison function.
  24991. * If null the sub meshes will be render in the order they were created
  24992. */
  24993. set: function (value) {
  24994. if (value) {
  24995. this._transparentSortCompareFn = value;
  24996. }
  24997. else {
  24998. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  24999. }
  25000. this._renderTransparent = this.renderTransparentSorted;
  25001. },
  25002. enumerable: true,
  25003. configurable: true
  25004. });
  25005. /**
  25006. * Render all the sub meshes contained in the group.
  25007. * @param customRenderFunction Used to override the default render behaviour of the group.
  25008. * @returns true if rendered some submeshes.
  25009. */
  25010. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  25011. if (customRenderFunction) {
  25012. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  25013. return;
  25014. }
  25015. var engine = this._scene.getEngine();
  25016. // Depth only
  25017. if (this._depthOnlySubMeshes.length !== 0) {
  25018. engine.setColorWrite(false);
  25019. this._renderAlphaTest(this._depthOnlySubMeshes);
  25020. engine.setColorWrite(true);
  25021. }
  25022. // Opaque
  25023. if (this._opaqueSubMeshes.length !== 0) {
  25024. this._renderOpaque(this._opaqueSubMeshes);
  25025. }
  25026. // Alpha test
  25027. if (this._alphaTestSubMeshes.length !== 0) {
  25028. this._renderAlphaTest(this._alphaTestSubMeshes);
  25029. }
  25030. var stencilState = engine.getStencilBuffer();
  25031. engine.setStencilBuffer(false);
  25032. // Sprites
  25033. if (renderSprites) {
  25034. this._renderSprites();
  25035. }
  25036. // Particles
  25037. if (renderParticles) {
  25038. this._renderParticles(activeMeshes);
  25039. }
  25040. if (this.onBeforeTransparentRendering) {
  25041. this.onBeforeTransparentRendering();
  25042. }
  25043. // Transparent
  25044. if (this._transparentSubMeshes.length !== 0) {
  25045. this._renderTransparent(this._transparentSubMeshes);
  25046. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  25047. }
  25048. // Set back stencil to false in case it changes before the edge renderer.
  25049. engine.setStencilBuffer(false);
  25050. // Edges
  25051. if (this._edgesRenderers.length) {
  25052. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  25053. this._edgesRenderers.data[edgesRendererIndex].render();
  25054. }
  25055. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  25056. }
  25057. // Restore Stencil state.
  25058. engine.setStencilBuffer(stencilState);
  25059. };
  25060. /**
  25061. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  25062. * @param subMeshes The submeshes to render
  25063. */
  25064. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  25065. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  25066. };
  25067. /**
  25068. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  25069. * @param subMeshes The submeshes to render
  25070. */
  25071. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  25072. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  25073. };
  25074. /**
  25075. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  25076. * @param subMeshes The submeshes to render
  25077. */
  25078. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  25079. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  25080. };
  25081. /**
  25082. * Renders the submeshes in a specified order.
  25083. * @param subMeshes The submeshes to sort before render
  25084. * @param sortCompareFn The comparison function use to sort
  25085. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  25086. * @param transparent Specifies to activate blending if true
  25087. */
  25088. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  25089. var subIndex = 0;
  25090. var subMesh;
  25091. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  25092. for (; subIndex < subMeshes.length; subIndex++) {
  25093. subMesh = subMeshes.data[subIndex];
  25094. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  25095. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  25096. }
  25097. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  25098. if (sortCompareFn) {
  25099. sortedArray.sort(sortCompareFn);
  25100. }
  25101. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  25102. subMesh = sortedArray[subIndex];
  25103. if (transparent) {
  25104. var material = subMesh.getMaterial();
  25105. if (material && material.needDepthPrePass) {
  25106. var engine = material.getScene().getEngine();
  25107. engine.setColorWrite(false);
  25108. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  25109. subMesh.render(false);
  25110. engine.setColorWrite(true);
  25111. }
  25112. }
  25113. subMesh.render(transparent);
  25114. }
  25115. };
  25116. /**
  25117. * Renders the submeshes in the order they were dispatched (no sort applied).
  25118. * @param subMeshes The submeshes to render
  25119. */
  25120. RenderingGroup.renderUnsorted = function (subMeshes) {
  25121. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  25122. var submesh = subMeshes.data[subIndex];
  25123. submesh.render(false);
  25124. }
  25125. };
  25126. /**
  25127. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  25128. * are rendered back to front if in the same alpha index.
  25129. *
  25130. * @param a The first submesh
  25131. * @param b The second submesh
  25132. * @returns The result of the comparison
  25133. */
  25134. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  25135. // Alpha index first
  25136. if (a._alphaIndex > b._alphaIndex) {
  25137. return 1;
  25138. }
  25139. if (a._alphaIndex < b._alphaIndex) {
  25140. return -1;
  25141. }
  25142. // Then distance to camera
  25143. return RenderingGroup.backToFrontSortCompare(a, b);
  25144. };
  25145. /**
  25146. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  25147. * are rendered back to front.
  25148. *
  25149. * @param a The first submesh
  25150. * @param b The second submesh
  25151. * @returns The result of the comparison
  25152. */
  25153. RenderingGroup.backToFrontSortCompare = function (a, b) {
  25154. // Then distance to camera
  25155. if (a._distanceToCamera < b._distanceToCamera) {
  25156. return 1;
  25157. }
  25158. if (a._distanceToCamera > b._distanceToCamera) {
  25159. return -1;
  25160. }
  25161. return 0;
  25162. };
  25163. /**
  25164. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  25165. * are rendered front to back (prevent overdraw).
  25166. *
  25167. * @param a The first submesh
  25168. * @param b The second submesh
  25169. * @returns The result of the comparison
  25170. */
  25171. RenderingGroup.frontToBackSortCompare = function (a, b) {
  25172. // Then distance to camera
  25173. if (a._distanceToCamera < b._distanceToCamera) {
  25174. return -1;
  25175. }
  25176. if (a._distanceToCamera > b._distanceToCamera) {
  25177. return 1;
  25178. }
  25179. return 0;
  25180. };
  25181. /**
  25182. * Resets the different lists of submeshes to prepare a new frame.
  25183. */
  25184. RenderingGroup.prototype.prepare = function () {
  25185. this._opaqueSubMeshes.reset();
  25186. this._transparentSubMeshes.reset();
  25187. this._alphaTestSubMeshes.reset();
  25188. this._depthOnlySubMeshes.reset();
  25189. this._particleSystems.reset();
  25190. this._spriteManagers.reset();
  25191. this._edgesRenderers.reset();
  25192. };
  25193. RenderingGroup.prototype.dispose = function () {
  25194. this._opaqueSubMeshes.dispose();
  25195. this._transparentSubMeshes.dispose();
  25196. this._alphaTestSubMeshes.dispose();
  25197. this._depthOnlySubMeshes.dispose();
  25198. this._particleSystems.dispose();
  25199. this._spriteManagers.dispose();
  25200. this._edgesRenderers.dispose();
  25201. };
  25202. /**
  25203. * Inserts the submesh in its correct queue depending on its material.
  25204. * @param subMesh The submesh to dispatch
  25205. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  25206. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  25207. */
  25208. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  25209. // Get mesh and materials if not provided
  25210. if (mesh === undefined) {
  25211. mesh = subMesh.getMesh();
  25212. }
  25213. if (material === undefined) {
  25214. material = subMesh.getMaterial();
  25215. }
  25216. if (material === null || material === undefined) {
  25217. return;
  25218. }
  25219. if (material.needAlphaBlendingForMesh(mesh)) { // Transparent
  25220. this._transparentSubMeshes.push(subMesh);
  25221. }
  25222. else if (material.needAlphaTesting()) { // Alpha test
  25223. if (material.needDepthPrePass) {
  25224. this._depthOnlySubMeshes.push(subMesh);
  25225. }
  25226. this._alphaTestSubMeshes.push(subMesh);
  25227. }
  25228. else {
  25229. if (material.needDepthPrePass) {
  25230. this._depthOnlySubMeshes.push(subMesh);
  25231. }
  25232. this._opaqueSubMeshes.push(subMesh); // Opaque
  25233. }
  25234. if (mesh._edgesRenderer && mesh._edgesRenderer.isEnabled) {
  25235. this._edgesRenderers.push(mesh._edgesRenderer);
  25236. }
  25237. };
  25238. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  25239. this._spriteManagers.push(spriteManager);
  25240. };
  25241. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  25242. this._particleSystems.push(particleSystem);
  25243. };
  25244. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  25245. if (this._particleSystems.length === 0) {
  25246. return;
  25247. }
  25248. // Particles
  25249. var activeCamera = this._scene.activeCamera;
  25250. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  25251. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  25252. var particleSystem = this._particleSystems.data[particleIndex];
  25253. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  25254. continue;
  25255. }
  25256. var emitter = particleSystem.emitter;
  25257. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  25258. this._scene._activeParticles.addCount(particleSystem.render(), false);
  25259. }
  25260. }
  25261. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  25262. };
  25263. RenderingGroup.prototype._renderSprites = function () {
  25264. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  25265. return;
  25266. }
  25267. // Sprites
  25268. var activeCamera = this._scene.activeCamera;
  25269. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  25270. for (var id = 0; id < this._spriteManagers.length; id++) {
  25271. var spriteManager = this._spriteManagers.data[id];
  25272. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  25273. spriteManager.render();
  25274. }
  25275. }
  25276. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  25277. };
  25278. return RenderingGroup;
  25279. }());
  25280. BABYLON.RenderingGroup = RenderingGroup;
  25281. })(BABYLON || (BABYLON = {}));
  25282. //# sourceMappingURL=babylon.renderingGroup.js.map
  25283. var BABYLON;
  25284. (function (BABYLON) {
  25285. /**
  25286. * Groups all the scene component constants in one place to ease maintenance.
  25287. * @hidden
  25288. */
  25289. var SceneComponentConstants = /** @class */ (function () {
  25290. function SceneComponentConstants() {
  25291. }
  25292. SceneComponentConstants.NAME_EFFECTLAYER = "EffectLayer";
  25293. SceneComponentConstants.NAME_LAYER = "Layer";
  25294. SceneComponentConstants.NAME_LENSFLARESYSTEM = "LensFlareSystem";
  25295. SceneComponentConstants.NAME_BOUNDINGBOXRENDERER = "BoundingBoxRenderer";
  25296. SceneComponentConstants.NAME_PARTICLESYSTEM = "ParticleSystem";
  25297. SceneComponentConstants.NAME_GAMEPAD = "Gamepad";
  25298. SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE = "SimplificationQueue";
  25299. SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER = "GeometryBufferRenderer";
  25300. SceneComponentConstants.NAME_DEPTHRENDERER = "DepthRenderer";
  25301. SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER = "PostProcessRenderPipelineManager";
  25302. SceneComponentConstants.NAME_SPRITE = "Sprite";
  25303. SceneComponentConstants.NAME_OUTLINERENDERER = "Outline";
  25304. SceneComponentConstants.NAME_PROCEDURALTEXTURE = "ProceduralTexture";
  25305. SceneComponentConstants.NAME_SHADOWGENERATOR = "ShadowGenerator";
  25306. SceneComponentConstants.NAME_OCTREE = "Octree";
  25307. SceneComponentConstants.NAME_PHYSICSENGINE = "PhysicsEngine";
  25308. SceneComponentConstants.NAME_AUDIO = "Audio";
  25309. SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER = 0;
  25310. SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER = 0;
  25311. SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER = 0;
  25312. SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER = 0;
  25313. SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER = 1;
  25314. SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER = 0;
  25315. SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER = 1;
  25316. SceneComponentConstants.STEP_BEFORERENDERTARGETDRAW_LAYER = 0;
  25317. SceneComponentConstants.STEP_BEFORERENDERINGMESH_OUTLINE = 0;
  25318. SceneComponentConstants.STEP_AFTERRENDERINGMESH_OUTLINE = 0;
  25319. SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW = 0;
  25320. SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER = 1;
  25321. SceneComponentConstants.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE = 0;
  25322. SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD = 1;
  25323. SceneComponentConstants.STEP_BEFORECLEAR_PROCEDURALTEXTURE = 0;
  25324. SceneComponentConstants.STEP_AFTERRENDERTARGETDRAW_LAYER = 0;
  25325. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER = 0;
  25326. SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM = 1;
  25327. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW = 2;
  25328. SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER = 3;
  25329. SceneComponentConstants.STEP_AFTERRENDER_AUDIO = 0;
  25330. SceneComponentConstants.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR = 0;
  25331. SceneComponentConstants.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER = 1;
  25332. SceneComponentConstants.STEP_GATHERRENDERTARGETS_DEPTHRENDERER = 2;
  25333. SceneComponentConstants.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER = 3;
  25334. SceneComponentConstants.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER = 0;
  25335. SceneComponentConstants.STEP_POINTERMOVE_SPRITE = 0;
  25336. SceneComponentConstants.STEP_POINTERDOWN_SPRITE = 0;
  25337. SceneComponentConstants.STEP_POINTERUP_SPRITE = 0;
  25338. return SceneComponentConstants;
  25339. }());
  25340. BABYLON.SceneComponentConstants = SceneComponentConstants;
  25341. /**
  25342. * Repressentation of a stage in the scene (Basically a list of ordered steps)
  25343. * @hidden
  25344. */
  25345. var Stage = /** @class */ (function (_super) {
  25346. __extends(Stage, _super);
  25347. /**
  25348. * Hide ctor from the rest of the world.
  25349. * @param items The items to add.
  25350. */
  25351. function Stage(items) {
  25352. return _super.apply(this, items) || this;
  25353. }
  25354. /**
  25355. * Creates a new Stage.
  25356. * @returns A new instance of a Stage
  25357. */
  25358. Stage.Create = function () {
  25359. return Object.create(Stage.prototype);
  25360. };
  25361. /**
  25362. * Registers a step in an ordered way in the targeted stage.
  25363. * @param index Defines the position to register the step in
  25364. * @param component Defines the component attached to the step
  25365. * @param action Defines the action to launch during the step
  25366. */
  25367. Stage.prototype.registerStep = function (index, component, action) {
  25368. var i = 0;
  25369. var maxIndex = Number.MAX_VALUE;
  25370. for (; i < this.length; i++) {
  25371. var step = this[i];
  25372. maxIndex = step.index;
  25373. if (index < maxIndex) {
  25374. break;
  25375. }
  25376. }
  25377. this.splice(i, 0, { index: index, component: component, action: action.bind(component) });
  25378. };
  25379. /**
  25380. * Clears all the steps from the stage.
  25381. */
  25382. Stage.prototype.clear = function () {
  25383. this.length = 0;
  25384. };
  25385. return Stage;
  25386. }(Array));
  25387. BABYLON.Stage = Stage;
  25388. })(BABYLON || (BABYLON = {}));
  25389. //# sourceMappingURL=babylon.sceneComponent.js.map
  25390. var BABYLON;
  25391. (function (BABYLON) {
  25392. /**
  25393. * Base class of the scene acting as a container for the different elements composing a scene.
  25394. * This class is dynamically extended by the different components of the scene increasing
  25395. * flexibility and reducing coupling
  25396. */
  25397. var AbstractScene = /** @class */ (function () {
  25398. function AbstractScene() {
  25399. /**
  25400. * Gets the list of root nodes (ie. nodes with no parent)
  25401. */
  25402. this.rootNodes = new Array();
  25403. /** All of the cameras added to this scene
  25404. * @see http://doc.babylonjs.com/babylon101/cameras
  25405. */
  25406. this.cameras = new Array();
  25407. /**
  25408. * All of the lights added to this scene
  25409. * @see http://doc.babylonjs.com/babylon101/lights
  25410. */
  25411. this.lights = new Array();
  25412. /**
  25413. * All of the (abstract) meshes added to this scene
  25414. */
  25415. this.meshes = new Array();
  25416. /**
  25417. * The list of skeletons added to the scene
  25418. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  25419. */
  25420. this.skeletons = new Array();
  25421. /**
  25422. * All of the particle systems added to this scene
  25423. * @see http://doc.babylonjs.com/babylon101/particles
  25424. */
  25425. this.particleSystems = new Array();
  25426. /**
  25427. * Gets a list of Animations associated with the scene
  25428. */
  25429. this.animations = [];
  25430. /**
  25431. * All of the animation groups added to this scene
  25432. * @see http://doc.babylonjs.com/how_to/group
  25433. */
  25434. this.animationGroups = new Array();
  25435. /**
  25436. * All of the multi-materials added to this scene
  25437. * @see http://doc.babylonjs.com/how_to/multi_materials
  25438. */
  25439. this.multiMaterials = new Array();
  25440. /**
  25441. * All of the materials added to this scene
  25442. * In the context of a Scene, it is not supposed to be modified manually.
  25443. * Any addition or removal should be done using the addMaterial and removeMAterial Scene methods.
  25444. * Note also that the order of the Material wihin the array is not significant and might change.
  25445. * @see http://doc.babylonjs.com/babylon101/materials
  25446. */
  25447. this.materials = new Array();
  25448. /**
  25449. * The list of morph target managers added to the scene
  25450. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  25451. */
  25452. this.morphTargetManagers = new Array();
  25453. /**
  25454. * The list of geometries used in the scene.
  25455. */
  25456. this.geometries = new Array();
  25457. /**
  25458. * All of the tranform nodes added to this scene
  25459. * In the context of a Scene, it is not supposed to be modified manually.
  25460. * Any addition or removal should be done using the addTransformNode and removeTransformNode Scene methods.
  25461. * Note also that the order of the TransformNode wihin the array is not significant and might change.
  25462. * @see http://doc.babylonjs.com/how_to/transformnode
  25463. */
  25464. this.transformNodes = new Array();
  25465. /**
  25466. * ActionManagers available on the scene.
  25467. */
  25468. this.actionManagers = new Array();
  25469. /**
  25470. * Textures to keep.
  25471. */
  25472. this.textures = new Array();
  25473. }
  25474. /**
  25475. * Adds a parser in the list of available ones
  25476. * @param name Defines the name of the parser
  25477. * @param parser Defines the parser to add
  25478. */
  25479. AbstractScene.AddParser = function (name, parser) {
  25480. this._BabylonFileParsers[name] = parser;
  25481. };
  25482. /**
  25483. * Gets a general parser from the list of avaialble ones
  25484. * @param name Defines the name of the parser
  25485. * @returns the requested parser or null
  25486. */
  25487. AbstractScene.GetParser = function (name) {
  25488. if (this._BabylonFileParsers[name]) {
  25489. return this._BabylonFileParsers[name];
  25490. }
  25491. return null;
  25492. };
  25493. /**
  25494. * Adds n individual parser in the list of available ones
  25495. * @param name Defines the name of the parser
  25496. * @param parser Defines the parser to add
  25497. */
  25498. AbstractScene.AddIndividualParser = function (name, parser) {
  25499. this._IndividualBabylonFileParsers[name] = parser;
  25500. };
  25501. /**
  25502. * Gets an individual parser from the list of avaialble ones
  25503. * @param name Defines the name of the parser
  25504. * @returns the requested parser or null
  25505. */
  25506. AbstractScene.GetIndividualParser = function (name) {
  25507. if (this._IndividualBabylonFileParsers[name]) {
  25508. return this._IndividualBabylonFileParsers[name];
  25509. }
  25510. return null;
  25511. };
  25512. /**
  25513. * Parser json data and populate both a scene and its associated container object
  25514. * @param jsonData Defines the data to parse
  25515. * @param scene Defines the scene to parse the data for
  25516. * @param container Defines the container attached to the parsing sequence
  25517. * @param rootUrl Defines the root url of the data
  25518. */
  25519. AbstractScene.Parse = function (jsonData, scene, container, rootUrl) {
  25520. for (var parserName in this._BabylonFileParsers) {
  25521. if (this._BabylonFileParsers.hasOwnProperty(parserName)) {
  25522. this._BabylonFileParsers[parserName](jsonData, scene, container, rootUrl);
  25523. }
  25524. }
  25525. };
  25526. /**
  25527. * Stores the list of available parsers in the application.
  25528. */
  25529. AbstractScene._BabylonFileParsers = {};
  25530. /**
  25531. * Stores the list of available individual parsers in the application.
  25532. */
  25533. AbstractScene._IndividualBabylonFileParsers = {};
  25534. return AbstractScene;
  25535. }());
  25536. BABYLON.AbstractScene = AbstractScene;
  25537. })(BABYLON || (BABYLON = {}));
  25538. //# sourceMappingURL=babylon.abstractScene.js.map
  25539. var BABYLON;
  25540. (function (BABYLON) {
  25541. /** @hidden */
  25542. var ClickInfo = /** @class */ (function () {
  25543. function ClickInfo() {
  25544. this._singleClick = false;
  25545. this._doubleClick = false;
  25546. this._hasSwiped = false;
  25547. this._ignore = false;
  25548. }
  25549. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  25550. get: function () {
  25551. return this._singleClick;
  25552. },
  25553. set: function (b) {
  25554. this._singleClick = b;
  25555. },
  25556. enumerable: true,
  25557. configurable: true
  25558. });
  25559. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  25560. get: function () {
  25561. return this._doubleClick;
  25562. },
  25563. set: function (b) {
  25564. this._doubleClick = b;
  25565. },
  25566. enumerable: true,
  25567. configurable: true
  25568. });
  25569. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  25570. get: function () {
  25571. return this._hasSwiped;
  25572. },
  25573. set: function (b) {
  25574. this._hasSwiped = b;
  25575. },
  25576. enumerable: true,
  25577. configurable: true
  25578. });
  25579. Object.defineProperty(ClickInfo.prototype, "ignore", {
  25580. get: function () {
  25581. return this._ignore;
  25582. },
  25583. set: function (b) {
  25584. this._ignore = b;
  25585. },
  25586. enumerable: true,
  25587. configurable: true
  25588. });
  25589. return ClickInfo;
  25590. }());
  25591. /**
  25592. * This class is used by the onRenderingGroupObservable
  25593. */
  25594. var RenderingGroupInfo = /** @class */ (function () {
  25595. function RenderingGroupInfo() {
  25596. }
  25597. return RenderingGroupInfo;
  25598. }());
  25599. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  25600. /**
  25601. * Represents a scene to be rendered by the engine.
  25602. * @see http://doc.babylonjs.com/features/scene
  25603. */
  25604. var Scene = /** @class */ (function (_super) {
  25605. __extends(Scene, _super);
  25606. /**
  25607. * Creates a new Scene
  25608. * @param engine defines the engine to use to render this scene
  25609. */
  25610. function Scene(engine, options) {
  25611. var _this = _super.call(this) || this;
  25612. // Members
  25613. /**
  25614. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  25615. */
  25616. _this.autoClear = true;
  25617. /**
  25618. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  25619. */
  25620. _this.autoClearDepthAndStencil = true;
  25621. /**
  25622. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  25623. */
  25624. _this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  25625. /**
  25626. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  25627. */
  25628. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  25629. _this._forceWireframe = false;
  25630. _this._forcePointsCloud = false;
  25631. /**
  25632. * Gets or sets a boolean indicating if animations are enabled
  25633. */
  25634. _this.animationsEnabled = true;
  25635. _this._animationPropertiesOverride = null;
  25636. /**
  25637. * Gets or sets a boolean indicating if a constant deltatime has to be used
  25638. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  25639. */
  25640. _this.useConstantAnimationDeltaTime = false;
  25641. /**
  25642. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  25643. * Please note that it requires to run a ray cast through the scene on every frame
  25644. */
  25645. _this.constantlyUpdateMeshUnderPointer = false;
  25646. /**
  25647. * Defines the HTML cursor to use when hovering over interactive elements
  25648. */
  25649. _this.hoverCursor = "pointer";
  25650. /**
  25651. * Defines the HTML default cursor to use (empty by default)
  25652. */
  25653. _this.defaultCursor = "";
  25654. /**
  25655. * This is used to call preventDefault() on pointer down
  25656. * in order to block unwanted artifacts like system double clicks
  25657. */
  25658. _this.preventDefaultOnPointerDown = true;
  25659. /**
  25660. * This is used to call preventDefault() on pointer up
  25661. * in order to block unwanted artifacts like system double clicks
  25662. */
  25663. _this.preventDefaultOnPointerUp = true;
  25664. // Metadata
  25665. /**
  25666. * Gets or sets user defined metadata
  25667. */
  25668. _this.metadata = null;
  25669. /**
  25670. * Use this array to add regular expressions used to disable offline support for specific urls
  25671. */
  25672. _this.disableOfflineSupportExceptionRules = new Array();
  25673. /**
  25674. * An event triggered when the scene is disposed.
  25675. */
  25676. _this.onDisposeObservable = new BABYLON.Observable();
  25677. _this._onDisposeObserver = null;
  25678. /**
  25679. * An event triggered before rendering the scene (right after animations and physics)
  25680. */
  25681. _this.onBeforeRenderObservable = new BABYLON.Observable();
  25682. _this._onBeforeRenderObserver = null;
  25683. /**
  25684. * An event triggered after rendering the scene
  25685. */
  25686. _this.onAfterRenderObservable = new BABYLON.Observable();
  25687. _this._onAfterRenderObserver = null;
  25688. /**
  25689. * An event triggered before animating the scene
  25690. */
  25691. _this.onBeforeAnimationsObservable = new BABYLON.Observable();
  25692. /**
  25693. * An event triggered after animations processing
  25694. */
  25695. _this.onAfterAnimationsObservable = new BABYLON.Observable();
  25696. /**
  25697. * An event triggered before draw calls are ready to be sent
  25698. */
  25699. _this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  25700. /**
  25701. * An event triggered after draw calls have been sent
  25702. */
  25703. _this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  25704. /**
  25705. * An event triggered when the scene is ready
  25706. */
  25707. _this.onReadyObservable = new BABYLON.Observable();
  25708. /**
  25709. * An event triggered before rendering a camera
  25710. */
  25711. _this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  25712. _this._onBeforeCameraRenderObserver = null;
  25713. /**
  25714. * An event triggered after rendering a camera
  25715. */
  25716. _this.onAfterCameraRenderObservable = new BABYLON.Observable();
  25717. _this._onAfterCameraRenderObserver = null;
  25718. /**
  25719. * An event triggered when active meshes evaluation is about to start
  25720. */
  25721. _this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  25722. /**
  25723. * An event triggered when active meshes evaluation is done
  25724. */
  25725. _this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  25726. /**
  25727. * An event triggered when particles rendering is about to start
  25728. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  25729. */
  25730. _this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  25731. /**
  25732. * An event triggered when particles rendering is done
  25733. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  25734. */
  25735. _this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  25736. /**
  25737. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  25738. */
  25739. _this.onDataLoadedObservable = new BABYLON.Observable();
  25740. /**
  25741. * An event triggered when a camera is created
  25742. */
  25743. _this.onNewCameraAddedObservable = new BABYLON.Observable();
  25744. /**
  25745. * An event triggered when a camera is removed
  25746. */
  25747. _this.onCameraRemovedObservable = new BABYLON.Observable();
  25748. /**
  25749. * An event triggered when a light is created
  25750. */
  25751. _this.onNewLightAddedObservable = new BABYLON.Observable();
  25752. /**
  25753. * An event triggered when a light is removed
  25754. */
  25755. _this.onLightRemovedObservable = new BABYLON.Observable();
  25756. /**
  25757. * An event triggered when a geometry is created
  25758. */
  25759. _this.onNewGeometryAddedObservable = new BABYLON.Observable();
  25760. /**
  25761. * An event triggered when a geometry is removed
  25762. */
  25763. _this.onGeometryRemovedObservable = new BABYLON.Observable();
  25764. /**
  25765. * An event triggered when a transform node is created
  25766. */
  25767. _this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  25768. /**
  25769. * An event triggered when a transform node is removed
  25770. */
  25771. _this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  25772. /**
  25773. * An event triggered when a mesh is created
  25774. */
  25775. _this.onNewMeshAddedObservable = new BABYLON.Observable();
  25776. /**
  25777. * An event triggered when a mesh is removed
  25778. */
  25779. _this.onMeshRemovedObservable = new BABYLON.Observable();
  25780. /**
  25781. * An event triggered when a material is created
  25782. */
  25783. _this.onNewMaterialAddedObservable = new BABYLON.Observable();
  25784. /**
  25785. * An event triggered when a material is removed
  25786. */
  25787. _this.onMaterialRemovedObservable = new BABYLON.Observable();
  25788. /**
  25789. * An event triggered when a texture is created
  25790. */
  25791. _this.onNewTextureAddedObservable = new BABYLON.Observable();
  25792. /**
  25793. * An event triggered when a texture is removed
  25794. */
  25795. _this.onTextureRemovedObservable = new BABYLON.Observable();
  25796. /**
  25797. * An event triggered when render targets are about to be rendered
  25798. * Can happen multiple times per frame.
  25799. */
  25800. _this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  25801. /**
  25802. * An event triggered when render targets were rendered.
  25803. * Can happen multiple times per frame.
  25804. */
  25805. _this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  25806. /**
  25807. * An event triggered before calculating deterministic simulation step
  25808. */
  25809. _this.onBeforeStepObservable = new BABYLON.Observable();
  25810. /**
  25811. * An event triggered after calculating deterministic simulation step
  25812. */
  25813. _this.onAfterStepObservable = new BABYLON.Observable();
  25814. /**
  25815. * An event triggered when the activeCamera property is updated
  25816. */
  25817. _this.onActiveCameraChanged = new BABYLON.Observable();
  25818. /**
  25819. * This Observable will be triggered before rendering each renderingGroup of each rendered camera.
  25820. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  25821. * 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)
  25822. */
  25823. _this.onBeforeRenderingGroupObservable = new BABYLON.Observable();
  25824. /**
  25825. * This Observable will be triggered after rendering each renderingGroup of each rendered camera.
  25826. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  25827. * 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)
  25828. */
  25829. _this.onAfterRenderingGroupObservable = new BABYLON.Observable();
  25830. /**
  25831. * This Observable will when a mesh has been imported into the scene.
  25832. */
  25833. _this.onMeshImportedObservable = new BABYLON.Observable();
  25834. // Animations
  25835. _this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  25836. /**
  25837. * 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).
  25838. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  25839. */
  25840. _this.onPrePointerObservable = new BABYLON.Observable();
  25841. /**
  25842. * Observable event triggered each time an input event is received from the rendering canvas
  25843. */
  25844. _this.onPointerObservable = new BABYLON.Observable();
  25845. _this._meshPickProceed = false;
  25846. _this._currentPickResult = null;
  25847. _this._previousPickResult = null;
  25848. _this._totalPointersPressed = 0;
  25849. _this._doubleClickOccured = false;
  25850. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  25851. _this.cameraToUseForPointers = null;
  25852. _this._pointerX = 0;
  25853. _this._pointerY = 0;
  25854. _this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  25855. _this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  25856. _this._startingPointerTime = 0;
  25857. _this._previousStartingPointerTime = 0;
  25858. _this._pointerCaptures = {};
  25859. // Deterministic lockstep
  25860. _this._timeAccumulator = 0;
  25861. _this._currentStepId = 0;
  25862. _this._currentInternalStep = 0;
  25863. // Keyboard
  25864. /**
  25865. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  25866. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  25867. */
  25868. _this.onPreKeyboardObservable = new BABYLON.Observable();
  25869. /**
  25870. * Observable event triggered each time an keyboard event is received from the hosting window
  25871. */
  25872. _this.onKeyboardObservable = new BABYLON.Observable();
  25873. // Coordinates system
  25874. _this._useRightHandedSystem = false;
  25875. // Fog
  25876. _this._fogEnabled = true;
  25877. _this._fogMode = Scene.FOGMODE_NONE;
  25878. /**
  25879. * Gets or sets the fog color to use
  25880. * @see http://doc.babylonjs.com/babylon101/environment#fog
  25881. * (Default is Color3(0.2, 0.2, 0.3))
  25882. */
  25883. _this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  25884. /**
  25885. * Gets or sets the fog density to use
  25886. * @see http://doc.babylonjs.com/babylon101/environment#fog
  25887. * (Default is 0.1)
  25888. */
  25889. _this.fogDensity = 0.1;
  25890. /**
  25891. * Gets or sets the fog start distance to use
  25892. * @see http://doc.babylonjs.com/babylon101/environment#fog
  25893. * (Default is 0)
  25894. */
  25895. _this.fogStart = 0;
  25896. /**
  25897. * Gets or sets the fog end distance to use
  25898. * @see http://doc.babylonjs.com/babylon101/environment#fog
  25899. * (Default is 1000)
  25900. */
  25901. _this.fogEnd = 1000.0;
  25902. // Lights
  25903. _this._shadowsEnabled = true;
  25904. _this._lightsEnabled = true;
  25905. /** All of the active cameras added to this scene. */
  25906. _this.activeCameras = new Array();
  25907. // Textures
  25908. _this._texturesEnabled = true;
  25909. // Particles
  25910. /**
  25911. * Gets or sets a boolean indicating if particles are enabled on this scene
  25912. */
  25913. _this.particlesEnabled = true;
  25914. // Sprites
  25915. /**
  25916. * Gets or sets a boolean indicating if sprites are enabled on this scene
  25917. */
  25918. _this.spritesEnabled = true;
  25919. // Skeletons
  25920. _this._skeletonsEnabled = true;
  25921. // Lens flares
  25922. /**
  25923. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  25924. */
  25925. _this.lensFlaresEnabled = true;
  25926. // Collisions
  25927. /**
  25928. * Gets or sets a boolean indicating if collisions are enabled on this scene
  25929. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  25930. */
  25931. _this.collisionsEnabled = true;
  25932. /**
  25933. * Defines the gravity applied to this scene (used only for collisions)
  25934. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  25935. */
  25936. _this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  25937. // Postprocesses
  25938. /**
  25939. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  25940. */
  25941. _this.postProcessesEnabled = true;
  25942. /**
  25943. * The list of postprocesses added to the scene
  25944. */
  25945. _this.postProcesses = new Array();
  25946. // Customs render targets
  25947. /**
  25948. * Gets or sets a boolean indicating if render targets are enabled on this scene
  25949. */
  25950. _this.renderTargetsEnabled = true;
  25951. /**
  25952. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  25953. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  25954. */
  25955. _this.dumpNextRenderTargets = false;
  25956. /**
  25957. * The list of user defined render targets added to the scene
  25958. */
  25959. _this.customRenderTargets = new Array();
  25960. /**
  25961. * Gets the list of meshes imported to the scene through SceneLoader
  25962. */
  25963. _this.importedMeshesFiles = new Array();
  25964. // Probes
  25965. /**
  25966. * Gets or sets a boolean indicating if probes are enabled on this scene
  25967. */
  25968. _this.probesEnabled = true;
  25969. _this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  25970. // Procedural textures
  25971. /**
  25972. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  25973. */
  25974. _this.proceduralTexturesEnabled = true;
  25975. // Performance counters
  25976. _this._totalVertices = new BABYLON.PerfCounter();
  25977. /** @hidden */
  25978. _this._activeIndices = new BABYLON.PerfCounter();
  25979. /** @hidden */
  25980. _this._activeParticles = new BABYLON.PerfCounter();
  25981. /** @hidden */
  25982. _this._activeBones = new BABYLON.PerfCounter();
  25983. _this._animationTime = 0;
  25984. /**
  25985. * Gets or sets a general scale for animation speed
  25986. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  25987. */
  25988. _this.animationTimeScale = 1;
  25989. _this._renderId = 0;
  25990. _this._frameId = 0;
  25991. _this._executeWhenReadyTimeoutId = -1;
  25992. _this._intermediateRendering = false;
  25993. _this._viewUpdateFlag = -1;
  25994. _this._projectionUpdateFlag = -1;
  25995. _this._alternateViewUpdateFlag = -1;
  25996. _this._alternateProjectionUpdateFlag = -1;
  25997. /** @hidden */
  25998. _this._toBeDisposed = new Array(256);
  25999. _this._activeRequests = new Array();
  26000. _this._pendingData = new Array();
  26001. _this._isDisposed = false;
  26002. /**
  26003. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  26004. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  26005. */
  26006. _this.dispatchAllSubMeshesOfActiveMeshes = false;
  26007. _this._activeMeshes = new BABYLON.SmartArray(256);
  26008. _this._processedMaterials = new BABYLON.SmartArray(256);
  26009. _this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  26010. /** @hidden */
  26011. _this._activeParticleSystems = new BABYLON.SmartArray(256);
  26012. _this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  26013. _this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  26014. /** @hidden */
  26015. _this._activeAnimatables = new Array();
  26016. _this._transformMatrix = BABYLON.Matrix.Zero();
  26017. _this._useAlternateCameraConfiguration = false;
  26018. _this._alternateRendering = false;
  26019. _this._wheelEventName = "";
  26020. /**
  26021. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  26022. * This is useful if there are more lights that the maximum simulteanous authorized
  26023. */
  26024. _this.requireLightSorting = false;
  26025. /**
  26026. * @hidden
  26027. * Backing store of defined scene components.
  26028. */
  26029. _this._components = [];
  26030. /**
  26031. * @hidden
  26032. * Backing store of defined scene components.
  26033. */
  26034. _this._serializableComponents = [];
  26035. /**
  26036. * List of components to register on the next registration step.
  26037. */
  26038. _this._transientComponents = [];
  26039. /**
  26040. * @hidden
  26041. * Defines the actions happening before camera updates.
  26042. */
  26043. _this._beforeCameraUpdateStage = BABYLON.Stage.Create();
  26044. /**
  26045. * @hidden
  26046. * Defines the actions happening before clear the canvas.
  26047. */
  26048. _this._beforeClearStage = BABYLON.Stage.Create();
  26049. /**
  26050. * @hidden
  26051. * Defines the actions when collecting render targets for the frame.
  26052. */
  26053. _this._gatherRenderTargetsStage = BABYLON.Stage.Create();
  26054. /**
  26055. * @hidden
  26056. * Defines the actions happening for one camera in the frame.
  26057. */
  26058. _this._gatherActiveCameraRenderTargetsStage = BABYLON.Stage.Create();
  26059. /**
  26060. * @hidden
  26061. * Defines the actions happening during the per mesh ready checks.
  26062. */
  26063. _this._isReadyForMeshStage = BABYLON.Stage.Create();
  26064. /**
  26065. * @hidden
  26066. * Defines the actions happening before evaluate active mesh checks.
  26067. */
  26068. _this._beforeEvaluateActiveMeshStage = BABYLON.Stage.Create();
  26069. /**
  26070. * @hidden
  26071. * Defines the actions happening during the evaluate sub mesh checks.
  26072. */
  26073. _this._evaluateSubMeshStage = BABYLON.Stage.Create();
  26074. /**
  26075. * @hidden
  26076. * Defines the actions happening during the active mesh stage.
  26077. */
  26078. _this._activeMeshStage = BABYLON.Stage.Create();
  26079. /**
  26080. * @hidden
  26081. * Defines the actions happening during the per camera render target step.
  26082. */
  26083. _this._cameraDrawRenderTargetStage = BABYLON.Stage.Create();
  26084. /**
  26085. * @hidden
  26086. * Defines the actions happening just before the active camera is drawing.
  26087. */
  26088. _this._beforeCameraDrawStage = BABYLON.Stage.Create();
  26089. /**
  26090. * @hidden
  26091. * Defines the actions happening just before a render target is drawing.
  26092. */
  26093. _this._beforeRenderTargetDrawStage = BABYLON.Stage.Create();
  26094. /**
  26095. * @hidden
  26096. * Defines the actions happening just before a rendering group is drawing.
  26097. */
  26098. _this._beforeRenderingGroupDrawStage = BABYLON.Stage.Create();
  26099. /**
  26100. * @hidden
  26101. * Defines the actions happening just before a mesh is drawing.
  26102. */
  26103. _this._beforeRenderingMeshStage = BABYLON.Stage.Create();
  26104. /**
  26105. * @hidden
  26106. * Defines the actions happening just after a mesh has been drawn.
  26107. */
  26108. _this._afterRenderingMeshStage = BABYLON.Stage.Create();
  26109. /**
  26110. * @hidden
  26111. * Defines the actions happening just after a rendering group has been drawn.
  26112. */
  26113. _this._afterRenderingGroupDrawStage = BABYLON.Stage.Create();
  26114. /**
  26115. * @hidden
  26116. * Defines the actions happening just after the active camera has been drawn.
  26117. */
  26118. _this._afterCameraDrawStage = BABYLON.Stage.Create();
  26119. /**
  26120. * @hidden
  26121. * Defines the actions happening just after a render target has been drawn.
  26122. */
  26123. _this._afterRenderTargetDrawStage = BABYLON.Stage.Create();
  26124. /**
  26125. * @hidden
  26126. * Defines the actions happening just after rendering all cameras and computing intersections.
  26127. */
  26128. _this._afterRenderStage = BABYLON.Stage.Create();
  26129. /**
  26130. * @hidden
  26131. * Defines the actions happening when a pointer move event happens.
  26132. */
  26133. _this._pointerMoveStage = BABYLON.Stage.Create();
  26134. /**
  26135. * @hidden
  26136. * Defines the actions happening when a pointer down event happens.
  26137. */
  26138. _this._pointerDownStage = BABYLON.Stage.Create();
  26139. /**
  26140. * @hidden
  26141. * Defines the actions happening when a pointer up event happens.
  26142. */
  26143. _this._pointerUpStage = BABYLON.Stage.Create();
  26144. /**
  26145. * an optional map from Geometry Id to Geometry index in the 'geometries' array
  26146. */
  26147. _this.geometriesById = null;
  26148. _this._defaultMeshCandidates = {
  26149. data: [],
  26150. length: 0
  26151. };
  26152. _this._defaultSubMeshCandidates = {
  26153. data: [],
  26154. length: 0
  26155. };
  26156. _this._preventFreeActiveMeshesAndRenderingGroups = false;
  26157. _this._activeMeshesFrozen = false;
  26158. /** @hidden */
  26159. _this._allowPostProcessClearColor = true;
  26160. /**
  26161. * User updatable function that will return a deterministic frame time when engine is in deterministic lock step mode
  26162. */
  26163. _this.getDeterministicFrameTime = function () {
  26164. return 1000.0 / 60.0; // frame time in ms
  26165. };
  26166. _this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  26167. _this._blockMaterialDirtyMechanism = false;
  26168. _this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  26169. _this._engine.scenes.push(_this);
  26170. _this._uid = null;
  26171. _this._renderingManager = new BABYLON.RenderingManager(_this);
  26172. if (BABYLON.PostProcessManager) {
  26173. _this.postProcessManager = new BABYLON.PostProcessManager(_this);
  26174. }
  26175. if (BABYLON.Tools.IsWindowObjectExist()) {
  26176. _this.attachControl();
  26177. }
  26178. //collision coordinator initialization. For now legacy per default.
  26179. _this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  26180. // Uniform Buffer
  26181. _this._createUbo();
  26182. // Default Image processing definition
  26183. if (BABYLON.ImageProcessingConfiguration) {
  26184. _this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  26185. }
  26186. _this.setDefaultCandidateProviders();
  26187. if (options && options.useGeometryIdsMap === true) {
  26188. _this.geometriesById = {};
  26189. }
  26190. _this.useMaterialMeshMap = options && options.useGeometryIdsMap || false;
  26191. _this.useClonedMeshhMap = options && options.useClonedMeshhMap || false;
  26192. _this._engine.onNewSceneAddedObservable.notifyObservers(_this);
  26193. return _this;
  26194. }
  26195. Object.defineProperty(Scene.prototype, "environmentTexture", {
  26196. /**
  26197. * Texture used in all pbr material as the reflection texture.
  26198. * As in the majority of the scene they are the same (exception for multi room and so on),
  26199. * this is easier to reference from here than from all the materials.
  26200. */
  26201. get: function () {
  26202. return this._environmentTexture;
  26203. },
  26204. /**
  26205. * Texture used in all pbr material as the reflection texture.
  26206. * As in the majority of the scene they are the same (exception for multi room and so on),
  26207. * this is easier to set here than in all the materials.
  26208. */
  26209. set: function (value) {
  26210. if (this._environmentTexture === value) {
  26211. return;
  26212. }
  26213. this._environmentTexture = value;
  26214. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  26215. },
  26216. enumerable: true,
  26217. configurable: true
  26218. });
  26219. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  26220. /**
  26221. * Default image processing configuration used either in the rendering
  26222. * Forward main pass or through the imageProcessingPostProcess if present.
  26223. * As in the majority of the scene they are the same (exception for multi camera),
  26224. * this is easier to reference from here than from all the materials and post process.
  26225. *
  26226. * No setter as we it is a shared configuration, you can set the values instead.
  26227. */
  26228. get: function () {
  26229. return this._imageProcessingConfiguration;
  26230. },
  26231. enumerable: true,
  26232. configurable: true
  26233. });
  26234. Object.defineProperty(Scene.prototype, "forceWireframe", {
  26235. get: function () {
  26236. return this._forceWireframe;
  26237. },
  26238. /**
  26239. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  26240. */
  26241. set: function (value) {
  26242. if (this._forceWireframe === value) {
  26243. return;
  26244. }
  26245. this._forceWireframe = value;
  26246. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  26247. },
  26248. enumerable: true,
  26249. configurable: true
  26250. });
  26251. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  26252. get: function () {
  26253. return this._forcePointsCloud;
  26254. },
  26255. /**
  26256. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  26257. */
  26258. set: function (value) {
  26259. if (this._forcePointsCloud === value) {
  26260. return;
  26261. }
  26262. this._forcePointsCloud = value;
  26263. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  26264. },
  26265. enumerable: true,
  26266. configurable: true
  26267. });
  26268. Object.defineProperty(Scene.prototype, "animationPropertiesOverride", {
  26269. /**
  26270. * Gets or sets the animation properties override
  26271. */
  26272. get: function () {
  26273. return this._animationPropertiesOverride;
  26274. },
  26275. set: function (value) {
  26276. this._animationPropertiesOverride = value;
  26277. },
  26278. enumerable: true,
  26279. configurable: true
  26280. });
  26281. Object.defineProperty(Scene.prototype, "onDispose", {
  26282. /** Sets a function to be executed when this scene is disposed. */
  26283. set: function (callback) {
  26284. if (this._onDisposeObserver) {
  26285. this.onDisposeObservable.remove(this._onDisposeObserver);
  26286. }
  26287. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  26288. },
  26289. enumerable: true,
  26290. configurable: true
  26291. });
  26292. Object.defineProperty(Scene.prototype, "beforeRender", {
  26293. /** Sets a function to be executed before rendering this scene */
  26294. set: function (callback) {
  26295. if (this._onBeforeRenderObserver) {
  26296. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  26297. }
  26298. if (callback) {
  26299. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  26300. }
  26301. },
  26302. enumerable: true,
  26303. configurable: true
  26304. });
  26305. Object.defineProperty(Scene.prototype, "afterRender", {
  26306. /** Sets a function to be executed after rendering this scene */
  26307. set: function (callback) {
  26308. if (this._onAfterRenderObserver) {
  26309. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  26310. }
  26311. if (callback) {
  26312. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  26313. }
  26314. },
  26315. enumerable: true,
  26316. configurable: true
  26317. });
  26318. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  26319. /** Sets a function to be executed before rendering a camera*/
  26320. set: function (callback) {
  26321. if (this._onBeforeCameraRenderObserver) {
  26322. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  26323. }
  26324. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  26325. },
  26326. enumerable: true,
  26327. configurable: true
  26328. });
  26329. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  26330. /** Sets a function to be executed after rendering a camera*/
  26331. set: function (callback) {
  26332. if (this._onAfterCameraRenderObserver) {
  26333. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  26334. }
  26335. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  26336. },
  26337. enumerable: true,
  26338. configurable: true
  26339. });
  26340. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  26341. /**
  26342. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  26343. */
  26344. get: function () {
  26345. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  26346. },
  26347. enumerable: true,
  26348. configurable: true
  26349. });
  26350. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  26351. get: function () {
  26352. return this._useRightHandedSystem;
  26353. },
  26354. /**
  26355. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  26356. */
  26357. set: function (value) {
  26358. if (this._useRightHandedSystem === value) {
  26359. return;
  26360. }
  26361. this._useRightHandedSystem = value;
  26362. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  26363. },
  26364. enumerable: true,
  26365. configurable: true
  26366. });
  26367. /**
  26368. * Sets the step Id used by deterministic lock step
  26369. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  26370. * @param newStepId defines the step Id
  26371. */
  26372. Scene.prototype.setStepId = function (newStepId) {
  26373. this._currentStepId = newStepId;
  26374. };
  26375. /**
  26376. * Gets the step Id used by deterministic lock step
  26377. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  26378. * @returns the step Id
  26379. */
  26380. Scene.prototype.getStepId = function () {
  26381. return this._currentStepId;
  26382. };
  26383. /**
  26384. * Gets the internal step used by deterministic lock step
  26385. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  26386. * @returns the internal step
  26387. */
  26388. Scene.prototype.getInternalStep = function () {
  26389. return this._currentInternalStep;
  26390. };
  26391. Object.defineProperty(Scene.prototype, "fogEnabled", {
  26392. get: function () {
  26393. return this._fogEnabled;
  26394. },
  26395. /**
  26396. * Gets or sets a boolean indicating if fog is enabled on this scene
  26397. * @see http://doc.babylonjs.com/babylon101/environment#fog
  26398. * (Default is true)
  26399. */
  26400. set: function (value) {
  26401. if (this._fogEnabled === value) {
  26402. return;
  26403. }
  26404. this._fogEnabled = value;
  26405. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  26406. },
  26407. enumerable: true,
  26408. configurable: true
  26409. });
  26410. Object.defineProperty(Scene.prototype, "fogMode", {
  26411. get: function () {
  26412. return this._fogMode;
  26413. },
  26414. /**
  26415. * Gets or sets the fog mode to use
  26416. * @see http://doc.babylonjs.com/babylon101/environment#fog
  26417. * | mode | value |
  26418. * | --- | --- |
  26419. * | FOGMODE_NONE | 0 |
  26420. * | FOGMODE_EXP | 1 |
  26421. * | FOGMODE_EXP2 | 2 |
  26422. * | FOGMODE_LINEAR | 3 |
  26423. */
  26424. set: function (value) {
  26425. if (this._fogMode === value) {
  26426. return;
  26427. }
  26428. this._fogMode = value;
  26429. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  26430. },
  26431. enumerable: true,
  26432. configurable: true
  26433. });
  26434. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  26435. get: function () {
  26436. return this._shadowsEnabled;
  26437. },
  26438. /**
  26439. * Gets or sets a boolean indicating if shadows are enabled on this scene
  26440. */
  26441. set: function (value) {
  26442. if (this._shadowsEnabled === value) {
  26443. return;
  26444. }
  26445. this._shadowsEnabled = value;
  26446. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  26447. },
  26448. enumerable: true,
  26449. configurable: true
  26450. });
  26451. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  26452. get: function () {
  26453. return this._lightsEnabled;
  26454. },
  26455. /**
  26456. * Gets or sets a boolean indicating if lights are enabled on this scene
  26457. */
  26458. set: function (value) {
  26459. if (this._lightsEnabled === value) {
  26460. return;
  26461. }
  26462. this._lightsEnabled = value;
  26463. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  26464. },
  26465. enumerable: true,
  26466. configurable: true
  26467. });
  26468. Object.defineProperty(Scene.prototype, "activeCamera", {
  26469. /** Gets or sets the current active camera */
  26470. get: function () {
  26471. return this._activeCamera;
  26472. },
  26473. set: function (value) {
  26474. if (value === this._activeCamera) {
  26475. return;
  26476. }
  26477. this._activeCamera = value;
  26478. this.onActiveCameraChanged.notifyObservers(this);
  26479. },
  26480. enumerable: true,
  26481. configurable: true
  26482. });
  26483. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  26484. /** The default material used on meshes when no material is affected */
  26485. get: function () {
  26486. if (!this._defaultMaterial) {
  26487. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  26488. }
  26489. return this._defaultMaterial;
  26490. },
  26491. /** The default material used on meshes when no material is affected */
  26492. set: function (value) {
  26493. this._defaultMaterial = value;
  26494. },
  26495. enumerable: true,
  26496. configurable: true
  26497. });
  26498. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  26499. get: function () {
  26500. return this._texturesEnabled;
  26501. },
  26502. /**
  26503. * Gets or sets a boolean indicating if textures are enabled on this scene
  26504. */
  26505. set: function (value) {
  26506. if (this._texturesEnabled === value) {
  26507. return;
  26508. }
  26509. this._texturesEnabled = value;
  26510. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  26511. },
  26512. enumerable: true,
  26513. configurable: true
  26514. });
  26515. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  26516. get: function () {
  26517. return this._skeletonsEnabled;
  26518. },
  26519. /**
  26520. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  26521. */
  26522. set: function (value) {
  26523. if (this._skeletonsEnabled === value) {
  26524. return;
  26525. }
  26526. this._skeletonsEnabled = value;
  26527. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  26528. },
  26529. enumerable: true,
  26530. configurable: true
  26531. });
  26532. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  26533. /** @hidden */
  26534. get: function () {
  26535. return this._alternateRendering;
  26536. },
  26537. enumerable: true,
  26538. configurable: true
  26539. });
  26540. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  26541. /**
  26542. * Gets the list of frustum planes (built from the active camera)
  26543. */
  26544. get: function () {
  26545. return this._frustumPlanes;
  26546. },
  26547. enumerable: true,
  26548. configurable: true
  26549. });
  26550. /**
  26551. * Registers the transient components if needed.
  26552. */
  26553. Scene.prototype._registerTransientComponents = function () {
  26554. // Register components that have been associated lately to the scene.
  26555. if (this._transientComponents.length > 0) {
  26556. for (var _i = 0, _a = this._transientComponents; _i < _a.length; _i++) {
  26557. var component = _a[_i];
  26558. component.register();
  26559. }
  26560. this._transientComponents = [];
  26561. }
  26562. };
  26563. /**
  26564. * @hidden
  26565. * Add a component to the scene.
  26566. * Note that the ccomponent could be registered on th next frame if this is called after
  26567. * the register component stage.
  26568. * @param component Defines the component to add to the scene
  26569. */
  26570. Scene.prototype._addComponent = function (component) {
  26571. this._components.push(component);
  26572. this._transientComponents.push(component);
  26573. var serializableComponent = component;
  26574. if (serializableComponent.addFromContainer) {
  26575. this._serializableComponents.push(serializableComponent);
  26576. }
  26577. };
  26578. /**
  26579. * @hidden
  26580. * Gets a component from the scene.
  26581. * @param name defines the name of the component to retrieve
  26582. * @returns the component or null if not present
  26583. */
  26584. Scene.prototype._getComponent = function (name) {
  26585. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  26586. var component = _a[_i];
  26587. if (component.name === name) {
  26588. return component;
  26589. }
  26590. }
  26591. return null;
  26592. };
  26593. /**
  26594. * @hidden
  26595. */
  26596. Scene.prototype._getDefaultMeshCandidates = function () {
  26597. this._defaultMeshCandidates.data = this.meshes;
  26598. this._defaultMeshCandidates.length = this.meshes.length;
  26599. return this._defaultMeshCandidates;
  26600. };
  26601. /**
  26602. * @hidden
  26603. */
  26604. Scene.prototype._getDefaultSubMeshCandidates = function (mesh) {
  26605. this._defaultSubMeshCandidates.data = mesh.subMeshes;
  26606. this._defaultSubMeshCandidates.length = mesh.subMeshes.length;
  26607. return this._defaultSubMeshCandidates;
  26608. };
  26609. /**
  26610. * Sets the default candidate providers for the scene.
  26611. * This sets the getActiveMeshCandidates, getActiveSubMeshCandidates, getIntersectingSubMeshCandidates
  26612. * and getCollidingSubMeshCandidates to their default function
  26613. */
  26614. Scene.prototype.setDefaultCandidateProviders = function () {
  26615. this.getActiveMeshCandidates = this._getDefaultMeshCandidates.bind(this);
  26616. this.getActiveSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  26617. this.getIntersectingSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  26618. this.getCollidingSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  26619. };
  26620. Object.defineProperty(Scene.prototype, "workerCollisions", {
  26621. /**
  26622. * Gets a boolean indicating if collisions are processed on a web worker
  26623. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  26624. */
  26625. get: function () {
  26626. return this._workerCollisions;
  26627. },
  26628. set: function (enabled) {
  26629. if (!BABYLON.CollisionCoordinatorLegacy) {
  26630. return;
  26631. }
  26632. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  26633. this._workerCollisions = enabled;
  26634. if (this.collisionCoordinator) {
  26635. this.collisionCoordinator.destroy();
  26636. }
  26637. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  26638. this.collisionCoordinator.init(this);
  26639. },
  26640. enumerable: true,
  26641. configurable: true
  26642. });
  26643. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  26644. /**
  26645. * Gets the mesh that is currently under the pointer
  26646. */
  26647. get: function () {
  26648. return this._pointerOverMesh;
  26649. },
  26650. enumerable: true,
  26651. configurable: true
  26652. });
  26653. Object.defineProperty(Scene.prototype, "pointerX", {
  26654. /**
  26655. * Gets the current on-screen X position of the pointer
  26656. */
  26657. get: function () {
  26658. return this._pointerX;
  26659. },
  26660. enumerable: true,
  26661. configurable: true
  26662. });
  26663. Object.defineProperty(Scene.prototype, "pointerY", {
  26664. /**
  26665. * Gets the current on-screen Y position of the pointer
  26666. */
  26667. get: function () {
  26668. return this._pointerY;
  26669. },
  26670. enumerable: true,
  26671. configurable: true
  26672. });
  26673. /**
  26674. * Gets the cached material (ie. the latest rendered one)
  26675. * @returns the cached material
  26676. */
  26677. Scene.prototype.getCachedMaterial = function () {
  26678. return this._cachedMaterial;
  26679. };
  26680. /**
  26681. * Gets the cached effect (ie. the latest rendered one)
  26682. * @returns the cached effect
  26683. */
  26684. Scene.prototype.getCachedEffect = function () {
  26685. return this._cachedEffect;
  26686. };
  26687. /**
  26688. * Gets the cached visibility state (ie. the latest rendered one)
  26689. * @returns the cached visibility state
  26690. */
  26691. Scene.prototype.getCachedVisibility = function () {
  26692. return this._cachedVisibility;
  26693. };
  26694. /**
  26695. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  26696. * @param material defines the current material
  26697. * @param effect defines the current effect
  26698. * @param visibility defines the current visibility state
  26699. * @returns true if one parameter is not cached
  26700. */
  26701. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  26702. if (visibility === void 0) { visibility = 1; }
  26703. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  26704. };
  26705. /**
  26706. * Gets the engine associated with the scene
  26707. * @returns an Engine
  26708. */
  26709. Scene.prototype.getEngine = function () {
  26710. return this._engine;
  26711. };
  26712. /**
  26713. * Gets the total number of vertices rendered per frame
  26714. * @returns the total number of vertices rendered per frame
  26715. */
  26716. Scene.prototype.getTotalVertices = function () {
  26717. return this._totalVertices.current;
  26718. };
  26719. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  26720. /**
  26721. * Gets the performance counter for total vertices
  26722. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  26723. */
  26724. get: function () {
  26725. return this._totalVertices;
  26726. },
  26727. enumerable: true,
  26728. configurable: true
  26729. });
  26730. /**
  26731. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  26732. * @returns the total number of active indices rendered per frame
  26733. */
  26734. Scene.prototype.getActiveIndices = function () {
  26735. return this._activeIndices.current;
  26736. };
  26737. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  26738. /**
  26739. * Gets the performance counter for active indices
  26740. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  26741. */
  26742. get: function () {
  26743. return this._activeIndices;
  26744. },
  26745. enumerable: true,
  26746. configurable: true
  26747. });
  26748. /**
  26749. * Gets the total number of active particles rendered per frame
  26750. * @returns the total number of active particles rendered per frame
  26751. */
  26752. Scene.prototype.getActiveParticles = function () {
  26753. return this._activeParticles.current;
  26754. };
  26755. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  26756. /**
  26757. * Gets the performance counter for active particles
  26758. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  26759. */
  26760. get: function () {
  26761. return this._activeParticles;
  26762. },
  26763. enumerable: true,
  26764. configurable: true
  26765. });
  26766. /**
  26767. * Gets the total number of active bones rendered per frame
  26768. * @returns the total number of active bones rendered per frame
  26769. */
  26770. Scene.prototype.getActiveBones = function () {
  26771. return this._activeBones.current;
  26772. };
  26773. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  26774. /**
  26775. * Gets the performance counter for active bones
  26776. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  26777. */
  26778. get: function () {
  26779. return this._activeBones;
  26780. },
  26781. enumerable: true,
  26782. configurable: true
  26783. });
  26784. /**
  26785. * Gets the array of active meshes
  26786. * @returns an array of AbstractMesh
  26787. */
  26788. Scene.prototype.getActiveMeshes = function () {
  26789. return this._activeMeshes;
  26790. };
  26791. /**
  26792. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  26793. * @returns a number
  26794. */
  26795. Scene.prototype.getAnimationRatio = function () {
  26796. return this._animationRatio !== undefined ? this._animationRatio : 1;
  26797. };
  26798. /**
  26799. * Gets an unique Id for the current render phase
  26800. * @returns a number
  26801. */
  26802. Scene.prototype.getRenderId = function () {
  26803. return this._renderId;
  26804. };
  26805. /**
  26806. * Gets an unique Id for the current frame
  26807. * @returns a number
  26808. */
  26809. Scene.prototype.getFrameId = function () {
  26810. return this._frameId;
  26811. };
  26812. /** Call this function if you want to manually increment the render Id*/
  26813. Scene.prototype.incrementRenderId = function () {
  26814. this._renderId++;
  26815. };
  26816. Scene.prototype._updatePointerPosition = function (evt) {
  26817. var canvasRect = this._engine.getRenderingCanvasClientRect();
  26818. if (!canvasRect) {
  26819. return;
  26820. }
  26821. this._pointerX = evt.clientX - canvasRect.left;
  26822. this._pointerY = evt.clientY - canvasRect.top;
  26823. this._unTranslatedPointerX = this._pointerX;
  26824. this._unTranslatedPointerY = this._pointerY;
  26825. };
  26826. Scene.prototype._createUbo = function () {
  26827. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  26828. this._sceneUbo.addUniform("viewProjection", 16);
  26829. this._sceneUbo.addUniform("view", 16);
  26830. };
  26831. Scene.prototype._createAlternateUbo = function () {
  26832. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  26833. this._alternateSceneUbo.addUniform("viewProjection", 16);
  26834. this._alternateSceneUbo.addUniform("view", 16);
  26835. };
  26836. // Pointers handling
  26837. Scene.prototype._setRayOnPointerInfo = function (pointerInfo) {
  26838. if (pointerInfo.pickInfo) {
  26839. if (!pointerInfo.pickInfo.ray) {
  26840. pointerInfo.pickInfo.ray = this.createPickingRay(pointerInfo.event.offsetX, pointerInfo.event.offsetY, BABYLON.Matrix.Identity(), this.activeCamera);
  26841. }
  26842. }
  26843. };
  26844. /**
  26845. * Use this method to simulate a pointer move on a mesh
  26846. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  26847. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  26848. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  26849. * @returns the current scene
  26850. */
  26851. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  26852. var evt = new PointerEvent("pointermove", pointerEventInit);
  26853. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERMOVE)) {
  26854. return this;
  26855. }
  26856. return this._processPointerMove(pickResult, evt);
  26857. };
  26858. Scene.prototype._processPointerMove = function (pickResult, evt) {
  26859. var canvas = this._engine.getRenderingCanvas();
  26860. if (!canvas) {
  26861. return this;
  26862. }
  26863. // Restore pointer
  26864. canvas.style.cursor = this.defaultCursor;
  26865. var isMeshPicked = (pickResult && pickResult.hit && pickResult.pickedMesh) ? true : false;
  26866. if (isMeshPicked) {
  26867. this.setPointerOverMesh(pickResult.pickedMesh);
  26868. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  26869. if (this._pointerOverMesh.actionManager.hoverCursor) {
  26870. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  26871. }
  26872. else {
  26873. canvas.style.cursor = this.hoverCursor;
  26874. }
  26875. }
  26876. }
  26877. else {
  26878. this.setPointerOverMesh(null);
  26879. }
  26880. for (var _i = 0, _a = this._pointerMoveStage; _i < _a.length; _i++) {
  26881. var step = _a[_i];
  26882. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, isMeshPicked, canvas);
  26883. }
  26884. if (pickResult) {
  26885. var type = evt.type === this._wheelEventName ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  26886. if (this.onPointerMove) {
  26887. this.onPointerMove(evt, pickResult, type);
  26888. }
  26889. if (this.onPointerObservable.hasObservers()) {
  26890. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  26891. this._setRayOnPointerInfo(pi);
  26892. this.onPointerObservable.notifyObservers(pi, type);
  26893. }
  26894. }
  26895. return this;
  26896. };
  26897. Scene.prototype._checkPrePointerObservable = function (pickResult, evt, type) {
  26898. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  26899. if (pickResult) {
  26900. pi.ray = pickResult.ray;
  26901. }
  26902. this.onPrePointerObservable.notifyObservers(pi, type);
  26903. if (pi.skipOnPointerObservable) {
  26904. return true;
  26905. }
  26906. else {
  26907. return false;
  26908. }
  26909. };
  26910. /**
  26911. * Use this method to simulate a pointer down on a mesh
  26912. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  26913. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  26914. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  26915. * @returns the current scene
  26916. */
  26917. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  26918. var evt = new PointerEvent("pointerdown", pointerEventInit);
  26919. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  26920. return this;
  26921. }
  26922. return this._processPointerDown(pickResult, evt);
  26923. };
  26924. Scene.prototype._processPointerDown = function (pickResult, evt) {
  26925. var _this = this;
  26926. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  26927. this._pickedDownMesh = pickResult.pickedMesh;
  26928. var actionManager = pickResult.pickedMesh.actionManager;
  26929. if (actionManager) {
  26930. if (actionManager.hasPickTriggers) {
  26931. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26932. switch (evt.button) {
  26933. case 0:
  26934. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26935. break;
  26936. case 1:
  26937. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26938. break;
  26939. case 2:
  26940. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26941. break;
  26942. }
  26943. }
  26944. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  26945. window.setTimeout(function () {
  26946. 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);
  26947. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  26948. if (_this._totalPointersPressed !== 0 &&
  26949. ((Date.now() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  26950. !_this._isPointerSwiping()) {
  26951. _this._startingPointerTime = 0;
  26952. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26953. }
  26954. }
  26955. }, Scene.LongPressDelay);
  26956. }
  26957. }
  26958. }
  26959. else {
  26960. for (var _i = 0, _a = this._pointerDownStage; _i < _a.length; _i++) {
  26961. var step = _a[_i];
  26962. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, evt);
  26963. }
  26964. }
  26965. if (pickResult) {
  26966. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  26967. if (this.onPointerDown) {
  26968. this.onPointerDown(evt, pickResult, type);
  26969. }
  26970. if (this.onPointerObservable.hasObservers()) {
  26971. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  26972. this._setRayOnPointerInfo(pi);
  26973. this.onPointerObservable.notifyObservers(pi, type);
  26974. }
  26975. }
  26976. return this;
  26977. };
  26978. /**
  26979. * Use this method to simulate a pointer up on a mesh
  26980. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  26981. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  26982. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  26983. * @param doubleTap indicates that the pointer up event should be considered as part of a double click (false by default)
  26984. * @returns the current scene
  26985. */
  26986. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit, doubleTap) {
  26987. var evt = new PointerEvent("pointerup", pointerEventInit);
  26988. var clickInfo = new ClickInfo();
  26989. if (doubleTap) {
  26990. clickInfo.doubleClick = true;
  26991. }
  26992. else {
  26993. clickInfo.singleClick = true;
  26994. }
  26995. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  26996. return this;
  26997. }
  26998. return this._processPointerUp(pickResult, evt, clickInfo);
  26999. };
  27000. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  27001. if (pickResult && pickResult && pickResult.pickedMesh) {
  27002. this._pickedUpMesh = pickResult.pickedMesh;
  27003. if (this._pickedDownMesh === this._pickedUpMesh) {
  27004. if (this.onPointerPick) {
  27005. this.onPointerPick(evt, pickResult);
  27006. }
  27007. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  27008. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  27009. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  27010. this._setRayOnPointerInfo(pi);
  27011. this.onPointerObservable.notifyObservers(pi, type_1);
  27012. }
  27013. }
  27014. if (pickResult.pickedMesh.actionManager && !clickInfo.ignore) {
  27015. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  27016. if (!clickInfo.hasSwiped && clickInfo.singleClick) {
  27017. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  27018. }
  27019. if (clickInfo.doubleClick && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  27020. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  27021. }
  27022. }
  27023. }
  27024. else {
  27025. if (!clickInfo.ignore) {
  27026. for (var _i = 0, _a = this._pointerUpStage; _i < _a.length; _i++) {
  27027. var step = _a[_i];
  27028. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, evt);
  27029. }
  27030. }
  27031. }
  27032. if (this._pickedDownMesh &&
  27033. this._pickedDownMesh.actionManager &&
  27034. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  27035. this._pickedDownMesh !== this._pickedUpMesh) {
  27036. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  27037. }
  27038. var type = 0;
  27039. if (this.onPointerObservable.hasObservers()) {
  27040. if (!clickInfo.ignore && !clickInfo.hasSwiped) {
  27041. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  27042. type = BABYLON.PointerEventTypes.POINTERTAP;
  27043. }
  27044. else if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  27045. type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  27046. }
  27047. if (type) {
  27048. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  27049. this._setRayOnPointerInfo(pi);
  27050. this.onPointerObservable.notifyObservers(pi, type);
  27051. }
  27052. }
  27053. if (!clickInfo.ignore) {
  27054. type = BABYLON.PointerEventTypes.POINTERUP;
  27055. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  27056. this._setRayOnPointerInfo(pi);
  27057. this.onPointerObservable.notifyObservers(pi, type);
  27058. }
  27059. }
  27060. if (this.onPointerUp && !clickInfo.ignore) {
  27061. this.onPointerUp(evt, pickResult, type);
  27062. }
  27063. return this;
  27064. };
  27065. /**
  27066. * Gets a boolean indicating if the current pointer event is captured (meaning that the scene has already handled the pointer down)
  27067. * @param pointerId defines the pointer id to use in a multi-touch scenario (0 by default)
  27068. * @returns true if the pointer was captured
  27069. */
  27070. Scene.prototype.isPointerCaptured = function (pointerId) {
  27071. if (pointerId === void 0) { pointerId = 0; }
  27072. return this._pointerCaptures[pointerId];
  27073. };
  27074. /** @hidden */
  27075. Scene.prototype._isPointerSwiping = function () {
  27076. return Math.abs(this._startingPointerPosition.x - this._pointerX) > Scene.DragMovementThreshold ||
  27077. Math.abs(this._startingPointerPosition.y - this._pointerY) > Scene.DragMovementThreshold;
  27078. };
  27079. /**
  27080. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  27081. * @param attachUp defines if you want to attach events to pointerup
  27082. * @param attachDown defines if you want to attach events to pointerdown
  27083. * @param attachMove defines if you want to attach events to pointermove
  27084. */
  27085. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  27086. var _this = this;
  27087. if (attachUp === void 0) { attachUp = true; }
  27088. if (attachDown === void 0) { attachDown = true; }
  27089. if (attachMove === void 0) { attachMove = true; }
  27090. this._initActionManager = function (act, clickInfo) {
  27091. if (!_this._meshPickProceed) {
  27092. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  27093. _this._currentPickResult = pickResult;
  27094. if (pickResult) {
  27095. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  27096. }
  27097. _this._meshPickProceed = true;
  27098. }
  27099. return act;
  27100. };
  27101. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  27102. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  27103. if ((Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  27104. btn !== _this._previousButtonPressed) {
  27105. _this._doubleClickOccured = false;
  27106. clickInfo.singleClick = true;
  27107. clickInfo.ignore = false;
  27108. cb(clickInfo, _this._currentPickResult);
  27109. }
  27110. };
  27111. this._initClickEvent = function (obs1, obs2, evt, cb) {
  27112. var clickInfo = new ClickInfo();
  27113. _this._currentPickResult = null;
  27114. var act = null;
  27115. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  27116. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  27117. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  27118. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  27119. act = _this._initActionManager(act, clickInfo);
  27120. if (act) {
  27121. checkPicking = act.hasPickTriggers;
  27122. }
  27123. }
  27124. var needToIgnoreNext = false;
  27125. if (checkPicking) {
  27126. var btn = evt.button;
  27127. clickInfo.hasSwiped = _this._isPointerSwiping();
  27128. if (!clickInfo.hasSwiped) {
  27129. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  27130. if (!checkSingleClickImmediately) {
  27131. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  27132. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  27133. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  27134. act = _this._initActionManager(act, clickInfo);
  27135. if (act) {
  27136. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  27137. }
  27138. }
  27139. }
  27140. if (checkSingleClickImmediately) {
  27141. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  27142. if (Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  27143. btn !== _this._previousButtonPressed) {
  27144. clickInfo.singleClick = true;
  27145. cb(clickInfo, _this._currentPickResult);
  27146. needToIgnoreNext = true;
  27147. }
  27148. }
  27149. // at least one double click is required to be check and exclusive double click is enabled
  27150. else {
  27151. // wait that no double click has been raised during the double click delay
  27152. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  27153. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  27154. }
  27155. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  27156. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  27157. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  27158. act = _this._initActionManager(act, clickInfo);
  27159. if (act) {
  27160. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  27161. }
  27162. }
  27163. if (checkDoubleClick) {
  27164. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  27165. if (btn === _this._previousButtonPressed &&
  27166. Date.now() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  27167. !_this._doubleClickOccured) {
  27168. // pointer has not moved for 2 clicks, it's a double click
  27169. if (!clickInfo.hasSwiped &&
  27170. !_this._isPointerSwiping()) {
  27171. _this._previousStartingPointerTime = 0;
  27172. _this._doubleClickOccured = true;
  27173. clickInfo.doubleClick = true;
  27174. clickInfo.ignore = false;
  27175. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  27176. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  27177. }
  27178. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  27179. cb(clickInfo, _this._currentPickResult);
  27180. }
  27181. // if the two successive clicks are too far, it's just two simple clicks
  27182. else {
  27183. _this._doubleClickOccured = false;
  27184. _this._previousStartingPointerTime = _this._startingPointerTime;
  27185. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  27186. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  27187. _this._previousButtonPressed = btn;
  27188. if (Scene.ExclusiveDoubleClickMode) {
  27189. if (_this._previousDelayedSimpleClickTimeout) {
  27190. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  27191. }
  27192. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  27193. cb(clickInfo, _this._previousPickResult);
  27194. }
  27195. else {
  27196. cb(clickInfo, _this._currentPickResult);
  27197. }
  27198. }
  27199. needToIgnoreNext = true;
  27200. }
  27201. // just the first click of the double has been raised
  27202. else {
  27203. _this._doubleClickOccured = false;
  27204. _this._previousStartingPointerTime = _this._startingPointerTime;
  27205. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  27206. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  27207. _this._previousButtonPressed = btn;
  27208. }
  27209. }
  27210. }
  27211. }
  27212. if (!needToIgnoreNext) {
  27213. cb(clickInfo, _this._currentPickResult);
  27214. }
  27215. };
  27216. this._onPointerMove = function (evt) {
  27217. _this._updatePointerPosition(evt);
  27218. // PreObservable support
  27219. if (_this._checkPrePointerObservable(null, evt, evt.type === _this._wheelEventName ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE)) {
  27220. return;
  27221. }
  27222. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  27223. return;
  27224. }
  27225. if (!_this.pointerMovePredicate) {
  27226. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  27227. }
  27228. // Meshes
  27229. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  27230. _this._processPointerMove(pickResult, evt);
  27231. };
  27232. this._onPointerDown = function (evt) {
  27233. _this._totalPointersPressed++;
  27234. _this._pickedDownMesh = null;
  27235. _this._meshPickProceed = false;
  27236. _this._updatePointerPosition(evt);
  27237. if (_this.preventDefaultOnPointerDown && canvas) {
  27238. evt.preventDefault();
  27239. canvas.focus();
  27240. }
  27241. _this._startingPointerPosition.x = _this._pointerX;
  27242. _this._startingPointerPosition.y = _this._pointerY;
  27243. _this._startingPointerTime = Date.now();
  27244. // PreObservable support
  27245. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  27246. return;
  27247. }
  27248. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  27249. return;
  27250. }
  27251. _this._pointerCaptures[evt.pointerId] = true;
  27252. if (!_this.pointerDownPredicate) {
  27253. _this.pointerDownPredicate = function (mesh) {
  27254. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  27255. };
  27256. }
  27257. // Meshes
  27258. _this._pickedDownMesh = null;
  27259. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  27260. _this._processPointerDown(pickResult, evt);
  27261. };
  27262. this._onPointerUp = function (evt) {
  27263. if (_this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  27264. return; // So we need to test it the pointer down was pressed before.
  27265. }
  27266. _this._totalPointersPressed--;
  27267. _this._pickedUpMesh = null;
  27268. _this._meshPickProceed = false;
  27269. _this._updatePointerPosition(evt);
  27270. if (_this.preventDefaultOnPointerUp && canvas) {
  27271. evt.preventDefault();
  27272. canvas.focus();
  27273. }
  27274. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  27275. _this._pointerCaptures[evt.pointerId] = false;
  27276. // PreObservable support
  27277. if (_this.onPrePointerObservable.hasObservers()) {
  27278. if (!clickInfo.ignore) {
  27279. if (!clickInfo.hasSwiped) {
  27280. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  27281. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERTAP)) {
  27282. return;
  27283. }
  27284. }
  27285. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  27286. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  27287. return;
  27288. }
  27289. }
  27290. }
  27291. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  27292. return;
  27293. }
  27294. }
  27295. }
  27296. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  27297. return;
  27298. }
  27299. if (!_this.pointerUpPredicate) {
  27300. _this.pointerUpPredicate = function (mesh) {
  27301. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  27302. };
  27303. }
  27304. // Meshes
  27305. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  27306. _this._initActionManager(null, clickInfo);
  27307. }
  27308. if (!pickResult) {
  27309. pickResult = _this._currentPickResult;
  27310. }
  27311. _this._processPointerUp(pickResult, evt, clickInfo);
  27312. _this._previousPickResult = _this._currentPickResult;
  27313. });
  27314. };
  27315. this._onKeyDown = function (evt) {
  27316. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  27317. if (_this.onPreKeyboardObservable.hasObservers()) {
  27318. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  27319. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  27320. if (pi.skipOnPointerObservable) {
  27321. return;
  27322. }
  27323. }
  27324. if (_this.onKeyboardObservable.hasObservers()) {
  27325. var pi = new BABYLON.KeyboardInfo(type, evt);
  27326. _this.onKeyboardObservable.notifyObservers(pi, type);
  27327. }
  27328. if (_this.actionManager) {
  27329. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  27330. }
  27331. };
  27332. this._onKeyUp = function (evt) {
  27333. var type = BABYLON.KeyboardEventTypes.KEYUP;
  27334. if (_this.onPreKeyboardObservable.hasObservers()) {
  27335. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  27336. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  27337. if (pi.skipOnPointerObservable) {
  27338. return;
  27339. }
  27340. }
  27341. if (_this.onKeyboardObservable.hasObservers()) {
  27342. var pi = new BABYLON.KeyboardInfo(type, evt);
  27343. _this.onKeyboardObservable.notifyObservers(pi, type);
  27344. }
  27345. if (_this.actionManager) {
  27346. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  27347. }
  27348. };
  27349. var engine = this.getEngine();
  27350. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  27351. if (!canvas) {
  27352. return;
  27353. }
  27354. canvas.addEventListener("keydown", _this._onKeyDown, false);
  27355. canvas.addEventListener("keyup", _this._onKeyUp, false);
  27356. });
  27357. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  27358. if (!canvas) {
  27359. return;
  27360. }
  27361. canvas.removeEventListener("keydown", _this._onKeyDown);
  27362. canvas.removeEventListener("keyup", _this._onKeyUp);
  27363. });
  27364. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  27365. var canvas = this._engine.getRenderingCanvas();
  27366. if (!canvas) {
  27367. return;
  27368. }
  27369. if (attachMove) {
  27370. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  27371. // Wheel
  27372. this._wheelEventName = "onwheel" in document.createElement("div") ? "wheel" : // Modern browsers support "wheel"
  27373. document.onmousewheel !== undefined ? "mousewheel" : // Webkit and IE support at least "mousewheel"
  27374. "DOMMouseScroll"; // let's assume that remaining browsers are older Firefox
  27375. canvas.addEventListener(this._wheelEventName, this._onPointerMove, false);
  27376. }
  27377. if (attachDown) {
  27378. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  27379. }
  27380. if (attachUp) {
  27381. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  27382. }
  27383. canvas.tabIndex = 1;
  27384. };
  27385. /** Detaches all event handlers*/
  27386. Scene.prototype.detachControl = function () {
  27387. var engine = this.getEngine();
  27388. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  27389. var canvas = engine.getRenderingCanvas();
  27390. if (!canvas) {
  27391. return;
  27392. }
  27393. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  27394. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  27395. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  27396. if (this._onCanvasBlurObserver) {
  27397. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  27398. }
  27399. if (this._onCanvasFocusObserver) {
  27400. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  27401. }
  27402. // Wheel
  27403. canvas.removeEventListener(this._wheelEventName, this._onPointerMove);
  27404. // Keyboard
  27405. canvas.removeEventListener("keydown", this._onKeyDown);
  27406. canvas.removeEventListener("keyup", this._onKeyUp);
  27407. // Observables
  27408. this.onKeyboardObservable.clear();
  27409. this.onPreKeyboardObservable.clear();
  27410. this.onPointerObservable.clear();
  27411. this.onPrePointerObservable.clear();
  27412. };
  27413. /**
  27414. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  27415. * Delay loaded resources are not taking in account
  27416. * @return true if all required resources are ready
  27417. */
  27418. Scene.prototype.isReady = function () {
  27419. if (this._isDisposed) {
  27420. return false;
  27421. }
  27422. var index;
  27423. var engine = this.getEngine();
  27424. // Effects
  27425. if (!engine.areAllEffectsReady()) {
  27426. return false;
  27427. }
  27428. // Pending data
  27429. if (this._pendingData.length > 0) {
  27430. return false;
  27431. }
  27432. // Meshes
  27433. for (index = 0; index < this.meshes.length; index++) {
  27434. var mesh = this.meshes[index];
  27435. if (!mesh.isEnabled()) {
  27436. continue;
  27437. }
  27438. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  27439. continue;
  27440. }
  27441. if (!mesh.isReady(true)) {
  27442. return false;
  27443. }
  27444. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || mesh.getClassName() === "InstancedLinesMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  27445. // Is Ready For Mesh
  27446. for (var _i = 0, _a = this._isReadyForMeshStage; _i < _a.length; _i++) {
  27447. var step = _a[_i];
  27448. if (!step.action(mesh, hardwareInstancedRendering)) {
  27449. return false;
  27450. }
  27451. }
  27452. }
  27453. // Geometries
  27454. for (index = 0; index < this.geometries.length; index++) {
  27455. var geometry = this.geometries[index];
  27456. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  27457. return false;
  27458. }
  27459. }
  27460. // Post-processes
  27461. if (this.activeCameras && this.activeCameras.length > 0) {
  27462. for (var _b = 0, _c = this.activeCameras; _b < _c.length; _b++) {
  27463. var camera = _c[_b];
  27464. if (!camera.isReady(true)) {
  27465. return false;
  27466. }
  27467. }
  27468. }
  27469. else if (this.activeCamera) {
  27470. if (!this.activeCamera.isReady(true)) {
  27471. return false;
  27472. }
  27473. }
  27474. // Particles
  27475. for (var _d = 0, _e = this.particleSystems; _d < _e.length; _d++) {
  27476. var particleSystem = _e[_d];
  27477. if (!particleSystem.isReady()) {
  27478. return false;
  27479. }
  27480. }
  27481. return true;
  27482. };
  27483. /** Resets all cached information relative to material (including effect and visibility) */
  27484. Scene.prototype.resetCachedMaterial = function () {
  27485. this._cachedMaterial = null;
  27486. this._cachedEffect = null;
  27487. this._cachedVisibility = null;
  27488. };
  27489. /**
  27490. * Registers a function to be called before every frame render
  27491. * @param func defines the function to register
  27492. */
  27493. Scene.prototype.registerBeforeRender = function (func) {
  27494. this.onBeforeRenderObservable.add(func);
  27495. };
  27496. /**
  27497. * Unregisters a function called before every frame render
  27498. * @param func defines the function to unregister
  27499. */
  27500. Scene.prototype.unregisterBeforeRender = function (func) {
  27501. this.onBeforeRenderObservable.removeCallback(func);
  27502. };
  27503. /**
  27504. * Registers a function to be called after every frame render
  27505. * @param func defines the function to register
  27506. */
  27507. Scene.prototype.registerAfterRender = function (func) {
  27508. this.onAfterRenderObservable.add(func);
  27509. };
  27510. /**
  27511. * Unregisters a function called after every frame render
  27512. * @param func defines the function to unregister
  27513. */
  27514. Scene.prototype.unregisterAfterRender = function (func) {
  27515. this.onAfterRenderObservable.removeCallback(func);
  27516. };
  27517. Scene.prototype._executeOnceBeforeRender = function (func) {
  27518. var _this = this;
  27519. var execFunc = function () {
  27520. func();
  27521. setTimeout(function () {
  27522. _this.unregisterBeforeRender(execFunc);
  27523. });
  27524. };
  27525. this.registerBeforeRender(execFunc);
  27526. };
  27527. /**
  27528. * The provided function will run before render once and will be disposed afterwards.
  27529. * A timeout delay can be provided so that the function will be executed in N ms.
  27530. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  27531. * @param func The function to be executed.
  27532. * @param timeout optional delay in ms
  27533. */
  27534. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  27535. var _this = this;
  27536. if (timeout !== undefined) {
  27537. setTimeout(function () {
  27538. _this._executeOnceBeforeRender(func);
  27539. }, timeout);
  27540. }
  27541. else {
  27542. this._executeOnceBeforeRender(func);
  27543. }
  27544. };
  27545. /** @hidden */
  27546. Scene.prototype._addPendingData = function (data) {
  27547. this._pendingData.push(data);
  27548. };
  27549. /** @hidden */
  27550. Scene.prototype._removePendingData = function (data) {
  27551. var wasLoading = this.isLoading;
  27552. var index = this._pendingData.indexOf(data);
  27553. if (index !== -1) {
  27554. this._pendingData.splice(index, 1);
  27555. }
  27556. if (wasLoading && !this.isLoading) {
  27557. this.onDataLoadedObservable.notifyObservers(this);
  27558. }
  27559. };
  27560. /**
  27561. * Returns the number of items waiting to be loaded
  27562. * @returns the number of items waiting to be loaded
  27563. */
  27564. Scene.prototype.getWaitingItemsCount = function () {
  27565. return this._pendingData.length;
  27566. };
  27567. Object.defineProperty(Scene.prototype, "isLoading", {
  27568. /**
  27569. * Returns a boolean indicating if the scene is still loading data
  27570. */
  27571. get: function () {
  27572. return this._pendingData.length > 0;
  27573. },
  27574. enumerable: true,
  27575. configurable: true
  27576. });
  27577. /**
  27578. * Registers a function to be executed when the scene is ready
  27579. * @param {Function} func - the function to be executed
  27580. */
  27581. Scene.prototype.executeWhenReady = function (func) {
  27582. var _this = this;
  27583. this.onReadyObservable.add(func);
  27584. if (this._executeWhenReadyTimeoutId !== -1) {
  27585. return;
  27586. }
  27587. this._executeWhenReadyTimeoutId = setTimeout(function () {
  27588. _this._checkIsReady();
  27589. }, 150);
  27590. };
  27591. /**
  27592. * Returns a promise that resolves when the scene is ready
  27593. * @returns A promise that resolves when the scene is ready
  27594. */
  27595. Scene.prototype.whenReadyAsync = function () {
  27596. var _this = this;
  27597. return new Promise(function (resolve) {
  27598. _this.executeWhenReady(function () {
  27599. resolve();
  27600. });
  27601. });
  27602. };
  27603. /** @hidden */
  27604. Scene.prototype._checkIsReady = function () {
  27605. var _this = this;
  27606. this._registerTransientComponents();
  27607. if (this.isReady()) {
  27608. this.onReadyObservable.notifyObservers(this);
  27609. this.onReadyObservable.clear();
  27610. this._executeWhenReadyTimeoutId = -1;
  27611. return;
  27612. }
  27613. this._executeWhenReadyTimeoutId = setTimeout(function () {
  27614. _this._checkIsReady();
  27615. }, 150);
  27616. };
  27617. // Animations
  27618. /**
  27619. * Will start the animation sequence of a given target
  27620. * @param target defines the target
  27621. * @param from defines from which frame should animation start
  27622. * @param to defines until which frame should animation run.
  27623. * @param weight defines the weight to apply to the animation (1.0 by default)
  27624. * @param loop defines if the animation loops
  27625. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  27626. * @param onAnimationEnd defines the function to be executed when the animation ends
  27627. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  27628. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  27629. * @returns the animatable object created for this animation
  27630. */
  27631. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable, targetMask) {
  27632. if (weight === void 0) { weight = 1.0; }
  27633. if (speedRatio === void 0) { speedRatio = 1.0; }
  27634. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false, targetMask);
  27635. returnedAnimatable.weight = weight;
  27636. return returnedAnimatable;
  27637. };
  27638. /**
  27639. * Will start the animation sequence of a given target
  27640. * @param target defines the target
  27641. * @param from defines from which frame should animation start
  27642. * @param to defines until which frame should animation run.
  27643. * @param loop defines if the animation loops
  27644. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  27645. * @param onAnimationEnd defines the function to be executed when the animation ends
  27646. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  27647. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  27648. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  27649. * @returns the animatable object created for this animation
  27650. */
  27651. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask) {
  27652. if (speedRatio === void 0) { speedRatio = 1.0; }
  27653. if (stopCurrent === void 0) { stopCurrent = true; }
  27654. if (from > to && speedRatio > 0) {
  27655. speedRatio *= -1;
  27656. }
  27657. if (stopCurrent) {
  27658. this.stopAnimation(target, undefined, targetMask);
  27659. }
  27660. if (!animatable) {
  27661. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  27662. }
  27663. var shouldRunTargetAnimations = targetMask ? targetMask(target) : true;
  27664. // Local animations
  27665. if (target.animations && shouldRunTargetAnimations) {
  27666. animatable.appendAnimations(target, target.animations);
  27667. }
  27668. // Children animations
  27669. if (target.getAnimatables) {
  27670. var animatables = target.getAnimatables();
  27671. for (var index = 0; index < animatables.length; index++) {
  27672. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask);
  27673. }
  27674. }
  27675. animatable.reset();
  27676. return animatable;
  27677. };
  27678. /**
  27679. * Will start the animation sequence of a given target and its hierarchy
  27680. * @param target defines the target
  27681. * @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.
  27682. * @param from defines from which frame should animation start
  27683. * @param to defines until which frame should animation run.
  27684. * @param loop defines if the animation loops
  27685. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  27686. * @param onAnimationEnd defines the function to be executed when the animation ends
  27687. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  27688. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  27689. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  27690. * @returns the list of created animatables
  27691. */
  27692. Scene.prototype.beginHierarchyAnimation = function (target, directDescendantsOnly, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask) {
  27693. if (speedRatio === void 0) { speedRatio = 1.0; }
  27694. if (stopCurrent === void 0) { stopCurrent = true; }
  27695. var children = target.getDescendants(directDescendantsOnly);
  27696. var result = [];
  27697. result.push(this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask));
  27698. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  27699. var child = children_1[_i];
  27700. result.push(this.beginAnimation(child, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask));
  27701. }
  27702. return result;
  27703. };
  27704. /**
  27705. * Begin a new animation on a given node
  27706. * @param target defines the target where the animation will take place
  27707. * @param animations defines the list of animations to start
  27708. * @param from defines the initial value
  27709. * @param to defines the final value
  27710. * @param loop defines if you want animation to loop (off by default)
  27711. * @param speedRatio defines the speed ratio to apply to all animations
  27712. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  27713. * @returns the list of created animatables
  27714. */
  27715. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  27716. if (speedRatio === undefined) {
  27717. speedRatio = 1.0;
  27718. }
  27719. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  27720. return animatable;
  27721. };
  27722. /**
  27723. * Begin a new animation on a given node and its hierarchy
  27724. * @param target defines the root node where the animation will take place
  27725. * @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.
  27726. * @param animations defines the list of animations to start
  27727. * @param from defines the initial value
  27728. * @param to defines the final value
  27729. * @param loop defines if you want animation to loop (off by default)
  27730. * @param speedRatio defines the speed ratio to apply to all animations
  27731. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  27732. * @returns the list of animatables created for all nodes
  27733. */
  27734. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  27735. var children = target.getDescendants(directDescendantsOnly);
  27736. var result = [];
  27737. result.push(this.beginDirectAnimation(target, animations, from, to, loop, speedRatio, onAnimationEnd));
  27738. for (var _i = 0, children_2 = children; _i < children_2.length; _i++) {
  27739. var child = children_2[_i];
  27740. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  27741. }
  27742. return result;
  27743. };
  27744. /**
  27745. * Gets the animatable associated with a specific target
  27746. * @param target defines the target of the animatable
  27747. * @returns the required animatable if found
  27748. */
  27749. Scene.prototype.getAnimatableByTarget = function (target) {
  27750. for (var index = 0; index < this._activeAnimatables.length; index++) {
  27751. if (this._activeAnimatables[index].target === target) {
  27752. return this._activeAnimatables[index];
  27753. }
  27754. }
  27755. return null;
  27756. };
  27757. /**
  27758. * Gets all animatables associated with a given target
  27759. * @param target defines the target to look animatables for
  27760. * @returns an array of Animatables
  27761. */
  27762. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  27763. var result = [];
  27764. for (var index = 0; index < this._activeAnimatables.length; index++) {
  27765. if (this._activeAnimatables[index].target === target) {
  27766. result.push(this._activeAnimatables[index]);
  27767. }
  27768. }
  27769. return result;
  27770. };
  27771. Object.defineProperty(Scene.prototype, "animatables", {
  27772. /**
  27773. * Gets all animatable attached to the scene
  27774. */
  27775. get: function () {
  27776. return this._activeAnimatables;
  27777. },
  27778. enumerable: true,
  27779. configurable: true
  27780. });
  27781. /**
  27782. * Will stop the animation of the given target
  27783. * @param target - the target
  27784. * @param animationName - the name of the animation to stop (all animations will be stopped if both this and targetMask are empty)
  27785. * @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)
  27786. */
  27787. Scene.prototype.stopAnimation = function (target, animationName, targetMask) {
  27788. var animatables = this.getAllAnimatablesByTarget(target);
  27789. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  27790. var animatable = animatables_1[_i];
  27791. animatable.stop(animationName, targetMask);
  27792. }
  27793. };
  27794. /**
  27795. * Stops and removes all animations that have been applied to the scene
  27796. */
  27797. Scene.prototype.stopAllAnimations = function () {
  27798. if (this._activeAnimatables) {
  27799. for (var i = 0; i < this._activeAnimatables.length; i++) {
  27800. this._activeAnimatables[i].stop();
  27801. }
  27802. this._activeAnimatables = [];
  27803. }
  27804. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  27805. var group = _a[_i];
  27806. group.stop();
  27807. }
  27808. };
  27809. Scene.prototype._animate = function () {
  27810. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  27811. return;
  27812. }
  27813. // Getting time
  27814. var now = BABYLON.Tools.Now;
  27815. if (!this._animationTimeLast) {
  27816. if (this._pendingData.length > 0) {
  27817. return;
  27818. }
  27819. this._animationTimeLast = now;
  27820. }
  27821. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  27822. this._animationTime += deltaTime;
  27823. this._animationTimeLast = now;
  27824. for (var index = 0; index < this._activeAnimatables.length; index++) {
  27825. this._activeAnimatables[index]._animate(this._animationTime);
  27826. }
  27827. // Late animation bindings
  27828. this._processLateAnimationBindings();
  27829. };
  27830. /** @hidden */
  27831. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation, originalValue) {
  27832. var target = runtimeAnimation.target;
  27833. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  27834. if (!target._lateAnimationHolders) {
  27835. target._lateAnimationHolders = {};
  27836. }
  27837. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  27838. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  27839. totalWeight: 0,
  27840. animations: [],
  27841. originalValue: originalValue
  27842. };
  27843. }
  27844. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  27845. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  27846. };
  27847. Scene.prototype._processLateAnimationBindingsForMatrices = function (holder) {
  27848. var normalizer = 1.0;
  27849. var finalPosition = BABYLON.Tmp.Vector3[0];
  27850. var finalScaling = BABYLON.Tmp.Vector3[1];
  27851. var finalQuaternion = BABYLON.Tmp.Quaternion[0];
  27852. var startIndex = 0;
  27853. var originalAnimation = holder.animations[0];
  27854. var originalValue = holder.originalValue;
  27855. var scale = 1;
  27856. if (holder.totalWeight < 1.0) {
  27857. // We need to mix the original value in
  27858. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  27859. scale = 1.0 - holder.totalWeight;
  27860. }
  27861. else {
  27862. startIndex = 1;
  27863. // We need to normalize the weights
  27864. normalizer = holder.totalWeight;
  27865. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  27866. scale = originalAnimation.weight / normalizer;
  27867. if (scale == 1) {
  27868. return originalAnimation.currentValue;
  27869. }
  27870. }
  27871. finalScaling.scaleInPlace(scale);
  27872. finalPosition.scaleInPlace(scale);
  27873. finalQuaternion.scaleInPlace(scale);
  27874. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  27875. var runtimeAnimation = holder.animations[animIndex];
  27876. var scale = runtimeAnimation.weight / normalizer;
  27877. var currentPosition = BABYLON.Tmp.Vector3[2];
  27878. var currentScaling = BABYLON.Tmp.Vector3[3];
  27879. var currentQuaternion = BABYLON.Tmp.Quaternion[1];
  27880. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  27881. currentScaling.scaleAndAddToRef(scale, finalScaling);
  27882. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  27883. currentPosition.scaleAndAddToRef(scale, finalPosition);
  27884. }
  27885. BABYLON.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
  27886. return originalAnimation._workValue;
  27887. };
  27888. Scene.prototype._processLateAnimationBindingsForQuaternions = function (holder, refQuaternion) {
  27889. var originalAnimation = holder.animations[0];
  27890. var originalValue = holder.originalValue;
  27891. if (holder.animations.length === 1) {
  27892. BABYLON.Quaternion.SlerpToRef(originalValue, originalAnimation.currentValue, Math.min(1.0, holder.totalWeight), refQuaternion);
  27893. return refQuaternion;
  27894. }
  27895. var normalizer = 1.0;
  27896. var quaternions;
  27897. var weights;
  27898. if (holder.totalWeight < 1.0) {
  27899. var scale = 1.0 - holder.totalWeight;
  27900. quaternions = [];
  27901. weights = [];
  27902. quaternions.push(originalValue);
  27903. weights.push(scale);
  27904. }
  27905. else {
  27906. if (holder.animations.length === 2) { // Slerp as soon as we can
  27907. BABYLON.Quaternion.SlerpToRef(holder.animations[0].currentValue, holder.animations[1].currentValue, holder.animations[1].weight / holder.totalWeight, refQuaternion);
  27908. return refQuaternion;
  27909. }
  27910. quaternions = [];
  27911. weights = [];
  27912. normalizer = holder.totalWeight;
  27913. }
  27914. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  27915. var runtimeAnimation = holder.animations[animIndex];
  27916. quaternions.push(runtimeAnimation.currentValue);
  27917. weights.push(runtimeAnimation.weight / normalizer);
  27918. }
  27919. // https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions
  27920. var cumulativeAmount = 0;
  27921. var cumulativeQuaternion = null;
  27922. for (var index = 0; index < quaternions.length;) {
  27923. if (!cumulativeQuaternion) {
  27924. BABYLON.Quaternion.SlerpToRef(quaternions[index], quaternions[index + 1], weights[index + 1] / (weights[index] + weights[index + 1]), refQuaternion);
  27925. cumulativeQuaternion = refQuaternion;
  27926. cumulativeAmount = weights[index] + weights[index + 1];
  27927. index += 2;
  27928. continue;
  27929. }
  27930. cumulativeAmount += weights[index];
  27931. BABYLON.Quaternion.SlerpToRef(cumulativeQuaternion, quaternions[index], weights[index] / cumulativeAmount, cumulativeQuaternion);
  27932. index++;
  27933. }
  27934. return cumulativeQuaternion;
  27935. };
  27936. Scene.prototype._processLateAnimationBindings = function () {
  27937. if (!this._registeredForLateAnimationBindings.length) {
  27938. return;
  27939. }
  27940. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  27941. var target = this._registeredForLateAnimationBindings.data[index];
  27942. for (var path in target._lateAnimationHolders) {
  27943. var holder = target._lateAnimationHolders[path];
  27944. var originalAnimation = holder.animations[0];
  27945. var originalValue = holder.originalValue;
  27946. var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  27947. var finalValue = target[path];
  27948. if (matrixDecomposeMode) {
  27949. finalValue = this._processLateAnimationBindingsForMatrices(holder);
  27950. }
  27951. else {
  27952. var quaternionMode = originalValue.w !== undefined;
  27953. if (quaternionMode) {
  27954. finalValue = this._processLateAnimationBindingsForQuaternions(holder, finalValue || BABYLON.Quaternion.Identity());
  27955. }
  27956. else {
  27957. var startIndex = 0;
  27958. var normalizer = 1.0;
  27959. if (holder.totalWeight < 1.0) {
  27960. // We need to mix the original value in
  27961. if (originalValue.scale) {
  27962. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  27963. }
  27964. else {
  27965. finalValue = originalValue * (1.0 - holder.totalWeight);
  27966. }
  27967. }
  27968. else {
  27969. // We need to normalize the weights
  27970. normalizer = holder.totalWeight;
  27971. var scale_1 = originalAnimation.weight / normalizer;
  27972. if (scale_1 !== 1) {
  27973. if (originalAnimation.currentValue.scale) {
  27974. finalValue = originalAnimation.currentValue.scale(scale_1);
  27975. }
  27976. else {
  27977. finalValue = originalAnimation.currentValue * scale_1;
  27978. }
  27979. }
  27980. else {
  27981. finalValue = originalAnimation.currentValue;
  27982. }
  27983. startIndex = 1;
  27984. }
  27985. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  27986. var runtimeAnimation = holder.animations[animIndex];
  27987. var scale = runtimeAnimation.weight / normalizer;
  27988. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  27989. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  27990. }
  27991. else {
  27992. finalValue += runtimeAnimation.currentValue * scale;
  27993. }
  27994. }
  27995. }
  27996. }
  27997. target[path] = finalValue;
  27998. }
  27999. target._lateAnimationHolders = {};
  28000. }
  28001. this._registeredForLateAnimationBindings.reset();
  28002. };
  28003. // Matrix
  28004. /** @hidden */
  28005. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  28006. this._useAlternateCameraConfiguration = active;
  28007. };
  28008. /**
  28009. * Gets the current view matrix
  28010. * @returns a Matrix
  28011. */
  28012. Scene.prototype.getViewMatrix = function () {
  28013. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  28014. };
  28015. /**
  28016. * Gets the current projection matrix
  28017. * @returns a Matrix
  28018. */
  28019. Scene.prototype.getProjectionMatrix = function () {
  28020. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  28021. };
  28022. /**
  28023. * Gets the current transform matrix
  28024. * @returns a Matrix made of View * Projection
  28025. */
  28026. Scene.prototype.getTransformMatrix = function () {
  28027. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  28028. };
  28029. /**
  28030. * Sets the current transform matrix
  28031. * @param view defines the View matrix to use
  28032. * @param projection defines the Projection matrix to use
  28033. */
  28034. Scene.prototype.setTransformMatrix = function (view, projection) {
  28035. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  28036. return;
  28037. }
  28038. this._viewUpdateFlag = view.updateFlag;
  28039. this._projectionUpdateFlag = projection.updateFlag;
  28040. this._viewMatrix = view;
  28041. this._projectionMatrix = projection;
  28042. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  28043. // Update frustum
  28044. if (!this._frustumPlanes) {
  28045. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  28046. }
  28047. else {
  28048. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  28049. }
  28050. if (this.activeCamera && this.activeCamera._alternateCamera) {
  28051. var otherCamera = this.activeCamera._alternateCamera;
  28052. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  28053. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  28054. }
  28055. if (this._sceneUbo.useUbo) {
  28056. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  28057. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  28058. this._sceneUbo.update();
  28059. }
  28060. };
  28061. /** @hidden */
  28062. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  28063. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  28064. return;
  28065. }
  28066. this._alternateViewUpdateFlag = view.updateFlag;
  28067. this._alternateProjectionUpdateFlag = projection.updateFlag;
  28068. this._alternateViewMatrix = view;
  28069. this._alternateProjectionMatrix = projection;
  28070. if (!this._alternateTransformMatrix) {
  28071. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  28072. }
  28073. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  28074. if (!this._alternateSceneUbo) {
  28075. this._createAlternateUbo();
  28076. }
  28077. if (this._alternateSceneUbo.useUbo) {
  28078. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  28079. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  28080. this._alternateSceneUbo.update();
  28081. }
  28082. };
  28083. /**
  28084. * Gets the uniform buffer used to store scene data
  28085. * @returns a UniformBuffer
  28086. */
  28087. Scene.prototype.getSceneUniformBuffer = function () {
  28088. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  28089. };
  28090. /**
  28091. * Gets an unique (relatively to the current scene) Id
  28092. * @returns an unique number for the scene
  28093. */
  28094. Scene.prototype.getUniqueId = function () {
  28095. var result = Scene._uniqueIdCounter;
  28096. Scene._uniqueIdCounter++;
  28097. return result;
  28098. };
  28099. /**
  28100. * Add a mesh to the list of scene's meshes
  28101. * @param newMesh defines the mesh to add
  28102. * @param recursive if all child meshes should also be added to the scene
  28103. */
  28104. Scene.prototype.addMesh = function (newMesh, recursive) {
  28105. var _this = this;
  28106. if (recursive === void 0) { recursive = false; }
  28107. this.meshes.push(newMesh);
  28108. //notify the collision coordinator
  28109. if (this.collisionCoordinator) {
  28110. this.collisionCoordinator.onMeshAdded(newMesh);
  28111. }
  28112. newMesh._resyncLightSources();
  28113. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  28114. if (recursive) {
  28115. newMesh.getChildMeshes().forEach(function (m) {
  28116. _this.addMesh(m);
  28117. });
  28118. }
  28119. };
  28120. /**
  28121. * Remove a mesh for the list of scene's meshes
  28122. * @param toRemove defines the mesh to remove
  28123. * @param recursive if all child meshes should also be removed from the scene
  28124. * @returns the index where the mesh was in the mesh list
  28125. */
  28126. Scene.prototype.removeMesh = function (toRemove, recursive) {
  28127. var _this = this;
  28128. if (recursive === void 0) { recursive = false; }
  28129. var index = this.meshes.indexOf(toRemove);
  28130. if (index !== -1) {
  28131. // Remove from the scene if mesh found
  28132. this.meshes[index] = this.meshes[this.meshes.length - 1];
  28133. this.meshes.pop();
  28134. }
  28135. this.onMeshRemovedObservable.notifyObservers(toRemove);
  28136. if (recursive) {
  28137. toRemove.getChildMeshes().forEach(function (m) {
  28138. _this.removeMesh(m);
  28139. });
  28140. }
  28141. return index;
  28142. };
  28143. /**
  28144. * Add a transform node to the list of scene's transform nodes
  28145. * @param newTransformNode defines the transform node to add
  28146. */
  28147. Scene.prototype.addTransformNode = function (newTransformNode) {
  28148. newTransformNode._indexInSceneTransformNodesArray = this.transformNodes.length;
  28149. this.transformNodes.push(newTransformNode);
  28150. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  28151. };
  28152. /**
  28153. * Remove a transform node for the list of scene's transform nodes
  28154. * @param toRemove defines the transform node to remove
  28155. * @returns the index where the transform node was in the transform node list
  28156. */
  28157. Scene.prototype.removeTransformNode = function (toRemove) {
  28158. var index = toRemove._indexInSceneTransformNodesArray;
  28159. if (index !== -1) {
  28160. if (index !== this.transformNodes.length - 1) {
  28161. var lastNode = this.transformNodes[this.transformNodes.length - 1];
  28162. this.transformNodes[index] = lastNode;
  28163. lastNode._indexInSceneTransformNodesArray = index;
  28164. }
  28165. toRemove._indexInSceneTransformNodesArray = -1;
  28166. this.transformNodes.pop();
  28167. }
  28168. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  28169. return index;
  28170. };
  28171. /**
  28172. * Remove a skeleton for the list of scene's skeletons
  28173. * @param toRemove defines the skeleton to remove
  28174. * @returns the index where the skeleton was in the skeleton list
  28175. */
  28176. Scene.prototype.removeSkeleton = function (toRemove) {
  28177. var index = this.skeletons.indexOf(toRemove);
  28178. if (index !== -1) {
  28179. // Remove from the scene if found
  28180. this.skeletons.splice(index, 1);
  28181. }
  28182. return index;
  28183. };
  28184. /**
  28185. * Remove a morph target for the list of scene's morph targets
  28186. * @param toRemove defines the morph target to remove
  28187. * @returns the index where the morph target was in the morph target list
  28188. */
  28189. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  28190. var index = this.morphTargetManagers.indexOf(toRemove);
  28191. if (index !== -1) {
  28192. // Remove from the scene if found
  28193. this.morphTargetManagers.splice(index, 1);
  28194. }
  28195. return index;
  28196. };
  28197. /**
  28198. * Remove a light for the list of scene's lights
  28199. * @param toRemove defines the light to remove
  28200. * @returns the index where the light was in the light list
  28201. */
  28202. Scene.prototype.removeLight = function (toRemove) {
  28203. var index = this.lights.indexOf(toRemove);
  28204. if (index !== -1) {
  28205. // Remove from meshes
  28206. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  28207. var mesh = _a[_i];
  28208. mesh._removeLightSource(toRemove);
  28209. }
  28210. // Remove from the scene if mesh found
  28211. this.lights.splice(index, 1);
  28212. this.sortLightsByPriority();
  28213. }
  28214. this.onLightRemovedObservable.notifyObservers(toRemove);
  28215. return index;
  28216. };
  28217. /**
  28218. * Remove a camera for the list of scene's cameras
  28219. * @param toRemove defines the camera to remove
  28220. * @returns the index where the camera was in the camera list
  28221. */
  28222. Scene.prototype.removeCamera = function (toRemove) {
  28223. var index = this.cameras.indexOf(toRemove);
  28224. if (index !== -1) {
  28225. // Remove from the scene if mesh found
  28226. this.cameras.splice(index, 1);
  28227. }
  28228. // Remove from activeCameras
  28229. var index2 = this.activeCameras.indexOf(toRemove);
  28230. if (index2 !== -1) {
  28231. // Remove from the scene if mesh found
  28232. this.activeCameras.splice(index2, 1);
  28233. }
  28234. // Reset the activeCamera
  28235. if (this.activeCamera === toRemove) {
  28236. if (this.cameras.length > 0) {
  28237. this.activeCamera = this.cameras[0];
  28238. }
  28239. else {
  28240. this.activeCamera = null;
  28241. }
  28242. }
  28243. this.onCameraRemovedObservable.notifyObservers(toRemove);
  28244. return index;
  28245. };
  28246. /**
  28247. * Remove a particle system for the list of scene's particle systems
  28248. * @param toRemove defines the particle system to remove
  28249. * @returns the index where the particle system was in the particle system list
  28250. */
  28251. Scene.prototype.removeParticleSystem = function (toRemove) {
  28252. var index = this.particleSystems.indexOf(toRemove);
  28253. if (index !== -1) {
  28254. this.particleSystems.splice(index, 1);
  28255. }
  28256. return index;
  28257. };
  28258. /**
  28259. * Remove a animation for the list of scene's animations
  28260. * @param toRemove defines the animation to remove
  28261. * @returns the index where the animation was in the animation list
  28262. */
  28263. Scene.prototype.removeAnimation = function (toRemove) {
  28264. var index = this.animations.indexOf(toRemove);
  28265. if (index !== -1) {
  28266. this.animations.splice(index, 1);
  28267. }
  28268. return index;
  28269. };
  28270. /**
  28271. * Removes the given animation group from this scene.
  28272. * @param toRemove The animation group to remove
  28273. * @returns The index of the removed animation group
  28274. */
  28275. Scene.prototype.removeAnimationGroup = function (toRemove) {
  28276. var index = this.animationGroups.indexOf(toRemove);
  28277. if (index !== -1) {
  28278. this.animationGroups.splice(index, 1);
  28279. }
  28280. return index;
  28281. };
  28282. /**
  28283. * Removes the given multi-material from this scene.
  28284. * @param toRemove The multi-material to remove
  28285. * @returns The index of the removed multi-material
  28286. */
  28287. Scene.prototype.removeMultiMaterial = function (toRemove) {
  28288. var index = this.multiMaterials.indexOf(toRemove);
  28289. if (index !== -1) {
  28290. this.multiMaterials.splice(index, 1);
  28291. }
  28292. return index;
  28293. };
  28294. /**
  28295. * Removes the given material from this scene.
  28296. * @param toRemove The material to remove
  28297. * @returns The index of the removed material
  28298. */
  28299. Scene.prototype.removeMaterial = function (toRemove) {
  28300. var index = toRemove._indexInSceneMaterialArray;
  28301. if (index !== -1) {
  28302. if (index !== this.materials.length - 1) {
  28303. var lastMaterial = this.materials[this.materials.length - 1];
  28304. this.materials[index] = lastMaterial;
  28305. lastMaterial._indexInSceneMaterialArray = index;
  28306. }
  28307. toRemove._indexInSceneMaterialArray = -1;
  28308. this.materials.pop();
  28309. }
  28310. this.onMaterialRemovedObservable.notifyObservers(toRemove);
  28311. return index;
  28312. };
  28313. /**
  28314. * Removes the given action manager from this scene.
  28315. * @param toRemove The action manager to remove
  28316. * @returns The index of the removed action manager
  28317. */
  28318. Scene.prototype.removeActionManager = function (toRemove) {
  28319. var index = this.actionManagers.indexOf(toRemove);
  28320. if (index !== -1) {
  28321. this.actionManagers.splice(index, 1);
  28322. }
  28323. return index;
  28324. };
  28325. /**
  28326. * Removes the given texture from this scene.
  28327. * @param toRemove The texture to remove
  28328. * @returns The index of the removed texture
  28329. */
  28330. Scene.prototype.removeTexture = function (toRemove) {
  28331. var index = this.textures.indexOf(toRemove);
  28332. if (index !== -1) {
  28333. this.textures.splice(index, 1);
  28334. }
  28335. this.onTextureRemovedObservable.notifyObservers(toRemove);
  28336. return index;
  28337. };
  28338. /**
  28339. * Adds the given light to this scene
  28340. * @param newLight The light to add
  28341. */
  28342. Scene.prototype.addLight = function (newLight) {
  28343. this.lights.push(newLight);
  28344. this.sortLightsByPriority();
  28345. // Add light to all meshes (To support if the light is removed and then readded)
  28346. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  28347. var mesh = _a[_i];
  28348. if (mesh._lightSources.indexOf(newLight) === -1) {
  28349. mesh._lightSources.push(newLight);
  28350. mesh._resyncLightSources();
  28351. }
  28352. }
  28353. this.onNewLightAddedObservable.notifyObservers(newLight);
  28354. };
  28355. /**
  28356. * Sorts the list list based on light priorities
  28357. */
  28358. Scene.prototype.sortLightsByPriority = function () {
  28359. if (this.requireLightSorting) {
  28360. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  28361. }
  28362. };
  28363. /**
  28364. * Adds the given camera to this scene
  28365. * @param newCamera The camera to add
  28366. */
  28367. Scene.prototype.addCamera = function (newCamera) {
  28368. this.cameras.push(newCamera);
  28369. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  28370. };
  28371. /**
  28372. * Adds the given skeleton to this scene
  28373. * @param newSkeleton The skeleton to add
  28374. */
  28375. Scene.prototype.addSkeleton = function (newSkeleton) {
  28376. this.skeletons.push(newSkeleton);
  28377. };
  28378. /**
  28379. * Adds the given particle system to this scene
  28380. * @param newParticleSystem The particle system to add
  28381. */
  28382. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  28383. this.particleSystems.push(newParticleSystem);
  28384. };
  28385. /**
  28386. * Adds the given animation to this scene
  28387. * @param newAnimation The animation to add
  28388. */
  28389. Scene.prototype.addAnimation = function (newAnimation) {
  28390. this.animations.push(newAnimation);
  28391. };
  28392. /**
  28393. * Adds the given animation group to this scene.
  28394. * @param newAnimationGroup The animation group to add
  28395. */
  28396. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  28397. this.animationGroups.push(newAnimationGroup);
  28398. };
  28399. /**
  28400. * Adds the given multi-material to this scene
  28401. * @param newMultiMaterial The multi-material to add
  28402. */
  28403. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  28404. this.multiMaterials.push(newMultiMaterial);
  28405. };
  28406. /**
  28407. * Adds the given material to this scene
  28408. * @param newMaterial The material to add
  28409. */
  28410. Scene.prototype.addMaterial = function (newMaterial) {
  28411. newMaterial._indexInSceneMaterialArray = this.materials.length;
  28412. this.materials.push(newMaterial);
  28413. this.onNewMaterialAddedObservable.notifyObservers(newMaterial);
  28414. };
  28415. /**
  28416. * Adds the given morph target to this scene
  28417. * @param newMorphTargetManager The morph target to add
  28418. */
  28419. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  28420. this.morphTargetManagers.push(newMorphTargetManager);
  28421. };
  28422. /**
  28423. * Adds the given geometry to this scene
  28424. * @param newGeometry The geometry to add
  28425. */
  28426. Scene.prototype.addGeometry = function (newGeometry) {
  28427. if (this.geometriesById) {
  28428. this.geometriesById[newGeometry.id] = this.geometries.length;
  28429. }
  28430. this.geometries.push(newGeometry);
  28431. };
  28432. /**
  28433. * Adds the given action manager to this scene
  28434. * @param newActionManager The action manager to add
  28435. */
  28436. Scene.prototype.addActionManager = function (newActionManager) {
  28437. this.actionManagers.push(newActionManager);
  28438. };
  28439. /**
  28440. * Adds the given texture to this scene.
  28441. * @param newTexture The texture to add
  28442. */
  28443. Scene.prototype.addTexture = function (newTexture) {
  28444. this.textures.push(newTexture);
  28445. this.onNewTextureAddedObservable.notifyObservers(newTexture);
  28446. };
  28447. /**
  28448. * Switch active camera
  28449. * @param newCamera defines the new active camera
  28450. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  28451. */
  28452. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  28453. if (attachControl === void 0) { attachControl = true; }
  28454. var canvas = this._engine.getRenderingCanvas();
  28455. if (!canvas) {
  28456. return;
  28457. }
  28458. if (this.activeCamera) {
  28459. this.activeCamera.detachControl(canvas);
  28460. }
  28461. this.activeCamera = newCamera;
  28462. if (attachControl) {
  28463. newCamera.attachControl(canvas);
  28464. }
  28465. };
  28466. /**
  28467. * sets the active camera of the scene using its ID
  28468. * @param id defines the camera's ID
  28469. * @return the new active camera or null if none found.
  28470. */
  28471. Scene.prototype.setActiveCameraByID = function (id) {
  28472. var camera = this.getCameraByID(id);
  28473. if (camera) {
  28474. this.activeCamera = camera;
  28475. return camera;
  28476. }
  28477. return null;
  28478. };
  28479. /**
  28480. * sets the active camera of the scene using its name
  28481. * @param name defines the camera's name
  28482. * @returns the new active camera or null if none found.
  28483. */
  28484. Scene.prototype.setActiveCameraByName = function (name) {
  28485. var camera = this.getCameraByName(name);
  28486. if (camera) {
  28487. this.activeCamera = camera;
  28488. return camera;
  28489. }
  28490. return null;
  28491. };
  28492. /**
  28493. * get an animation group using its name
  28494. * @param name defines the material's name
  28495. * @return the animation group or null if none found.
  28496. */
  28497. Scene.prototype.getAnimationGroupByName = function (name) {
  28498. for (var index = 0; index < this.animationGroups.length; index++) {
  28499. if (this.animationGroups[index].name === name) {
  28500. return this.animationGroups[index];
  28501. }
  28502. }
  28503. return null;
  28504. };
  28505. /**
  28506. * get a material using its id
  28507. * @param id defines the material's ID
  28508. * @return the material or null if none found.
  28509. */
  28510. Scene.prototype.getMaterialByID = function (id) {
  28511. for (var index = 0; index < this.materials.length; index++) {
  28512. if (this.materials[index].id === id) {
  28513. return this.materials[index];
  28514. }
  28515. }
  28516. return null;
  28517. };
  28518. /**
  28519. * Gets a material using its name
  28520. * @param name defines the material's name
  28521. * @return the material or null if none found.
  28522. */
  28523. Scene.prototype.getMaterialByName = function (name) {
  28524. for (var index = 0; index < this.materials.length; index++) {
  28525. if (this.materials[index].name === name) {
  28526. return this.materials[index];
  28527. }
  28528. }
  28529. return null;
  28530. };
  28531. /**
  28532. * Gets a camera using its id
  28533. * @param id defines the id to look for
  28534. * @returns the camera or null if not found
  28535. */
  28536. Scene.prototype.getCameraByID = function (id) {
  28537. for (var index = 0; index < this.cameras.length; index++) {
  28538. if (this.cameras[index].id === id) {
  28539. return this.cameras[index];
  28540. }
  28541. }
  28542. return null;
  28543. };
  28544. /**
  28545. * Gets a camera using its unique id
  28546. * @param uniqueId defines the unique id to look for
  28547. * @returns the camera or null if not found
  28548. */
  28549. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  28550. for (var index = 0; index < this.cameras.length; index++) {
  28551. if (this.cameras[index].uniqueId === uniqueId) {
  28552. return this.cameras[index];
  28553. }
  28554. }
  28555. return null;
  28556. };
  28557. /**
  28558. * Gets a camera using its name
  28559. * @param name defines the camera's name
  28560. * @return the camera or null if none found.
  28561. */
  28562. Scene.prototype.getCameraByName = function (name) {
  28563. for (var index = 0; index < this.cameras.length; index++) {
  28564. if (this.cameras[index].name === name) {
  28565. return this.cameras[index];
  28566. }
  28567. }
  28568. return null;
  28569. };
  28570. /**
  28571. * Gets a bone using its id
  28572. * @param id defines the bone's id
  28573. * @return the bone or null if not found
  28574. */
  28575. Scene.prototype.getBoneByID = function (id) {
  28576. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  28577. var skeleton = this.skeletons[skeletonIndex];
  28578. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  28579. if (skeleton.bones[boneIndex].id === id) {
  28580. return skeleton.bones[boneIndex];
  28581. }
  28582. }
  28583. }
  28584. return null;
  28585. };
  28586. /**
  28587. * Gets a bone using its id
  28588. * @param name defines the bone's name
  28589. * @return the bone or null if not found
  28590. */
  28591. Scene.prototype.getBoneByName = function (name) {
  28592. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  28593. var skeleton = this.skeletons[skeletonIndex];
  28594. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  28595. if (skeleton.bones[boneIndex].name === name) {
  28596. return skeleton.bones[boneIndex];
  28597. }
  28598. }
  28599. }
  28600. return null;
  28601. };
  28602. /**
  28603. * Gets a light node using its name
  28604. * @param name defines the the light's name
  28605. * @return the light or null if none found.
  28606. */
  28607. Scene.prototype.getLightByName = function (name) {
  28608. for (var index = 0; index < this.lights.length; index++) {
  28609. if (this.lights[index].name === name) {
  28610. return this.lights[index];
  28611. }
  28612. }
  28613. return null;
  28614. };
  28615. /**
  28616. * Gets a light node using its id
  28617. * @param id defines the light's id
  28618. * @return the light or null if none found.
  28619. */
  28620. Scene.prototype.getLightByID = function (id) {
  28621. for (var index = 0; index < this.lights.length; index++) {
  28622. if (this.lights[index].id === id) {
  28623. return this.lights[index];
  28624. }
  28625. }
  28626. return null;
  28627. };
  28628. /**
  28629. * Gets a light node using its scene-generated unique ID
  28630. * @param uniqueId defines the light's unique id
  28631. * @return the light or null if none found.
  28632. */
  28633. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  28634. for (var index = 0; index < this.lights.length; index++) {
  28635. if (this.lights[index].uniqueId === uniqueId) {
  28636. return this.lights[index];
  28637. }
  28638. }
  28639. return null;
  28640. };
  28641. /**
  28642. * Gets a particle system by id
  28643. * @param id defines the particle system id
  28644. * @return the corresponding system or null if none found
  28645. */
  28646. Scene.prototype.getParticleSystemByID = function (id) {
  28647. for (var index = 0; index < this.particleSystems.length; index++) {
  28648. if (this.particleSystems[index].id === id) {
  28649. return this.particleSystems[index];
  28650. }
  28651. }
  28652. return null;
  28653. };
  28654. /**
  28655. * Gets a geometry using its ID
  28656. * @param id defines the geometry's id
  28657. * @return the geometry or null if none found.
  28658. */
  28659. Scene.prototype.getGeometryByID = function (id) {
  28660. if (this.geometriesById) {
  28661. var index_1 = this.geometriesById[id];
  28662. if (index_1 !== undefined) {
  28663. return this.geometries[index_1];
  28664. }
  28665. }
  28666. else {
  28667. for (var index = 0; index < this.geometries.length; index++) {
  28668. if (this.geometries[index].id === id) {
  28669. return this.geometries[index];
  28670. }
  28671. }
  28672. }
  28673. return null;
  28674. };
  28675. Scene.prototype._getGeometryByUniqueID = function (id) {
  28676. for (var index = 0; index < this.geometries.length; index++) {
  28677. if (this.geometries[index].uniqueId === id) {
  28678. return this.geometries[index];
  28679. }
  28680. }
  28681. return null;
  28682. };
  28683. /**
  28684. * Add a new geometry to this scene
  28685. * @param geometry defines the geometry to be added to the scene.
  28686. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  28687. * @return a boolean defining if the geometry was added or not
  28688. */
  28689. Scene.prototype.pushGeometry = function (geometry, force) {
  28690. if (!force && this._getGeometryByUniqueID(geometry.uniqueId)) {
  28691. return false;
  28692. }
  28693. this.addGeometry(geometry);
  28694. //notify the collision coordinator
  28695. if (this.collisionCoordinator) {
  28696. this.collisionCoordinator.onGeometryAdded(geometry);
  28697. }
  28698. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  28699. return true;
  28700. };
  28701. /**
  28702. * Removes an existing geometry
  28703. * @param geometry defines the geometry to be removed from the scene
  28704. * @return a boolean defining if the geometry was removed or not
  28705. */
  28706. Scene.prototype.removeGeometry = function (geometry) {
  28707. var index;
  28708. if (this.geometriesById) {
  28709. index = this.geometriesById[geometry.id];
  28710. if (index === undefined) {
  28711. return false;
  28712. }
  28713. }
  28714. else {
  28715. index = this.geometries.indexOf(geometry);
  28716. if (index < 0) {
  28717. return false;
  28718. }
  28719. }
  28720. if (index !== this.geometries.length - 1) {
  28721. var lastGeometry = this.geometries[this.geometries.length - 1];
  28722. this.geometries[index] = lastGeometry;
  28723. if (this.geometriesById) {
  28724. this.geometriesById[lastGeometry.id] = index;
  28725. this.geometriesById[geometry.id] = undefined;
  28726. }
  28727. }
  28728. this.geometries.pop();
  28729. //notify the collision coordinator
  28730. if (this.collisionCoordinator) {
  28731. this.collisionCoordinator.onGeometryDeleted(geometry);
  28732. }
  28733. this.onGeometryRemovedObservable.notifyObservers(geometry);
  28734. return true;
  28735. };
  28736. /**
  28737. * Gets the list of geometries attached to the scene
  28738. * @returns an array of Geometry
  28739. */
  28740. Scene.prototype.getGeometries = function () {
  28741. return this.geometries;
  28742. };
  28743. /**
  28744. * Gets the first added mesh found of a given ID
  28745. * @param id defines the id to search for
  28746. * @return the mesh found or null if not found at all
  28747. */
  28748. Scene.prototype.getMeshByID = function (id) {
  28749. for (var index = 0; index < this.meshes.length; index++) {
  28750. if (this.meshes[index].id === id) {
  28751. return this.meshes[index];
  28752. }
  28753. }
  28754. return null;
  28755. };
  28756. /**
  28757. * Gets a list of meshes using their id
  28758. * @param id defines the id to search for
  28759. * @returns a list of meshes
  28760. */
  28761. Scene.prototype.getMeshesByID = function (id) {
  28762. return this.meshes.filter(function (m) {
  28763. return m.id === id;
  28764. });
  28765. };
  28766. /**
  28767. * Gets the first added transform node found of a given ID
  28768. * @param id defines the id to search for
  28769. * @return the found transform node or null if not found at all.
  28770. */
  28771. Scene.prototype.getTransformNodeByID = function (id) {
  28772. for (var index = 0; index < this.transformNodes.length; index++) {
  28773. if (this.transformNodes[index].id === id) {
  28774. return this.transformNodes[index];
  28775. }
  28776. }
  28777. return null;
  28778. };
  28779. /**
  28780. * Gets a list of transform nodes using their id
  28781. * @param id defines the id to search for
  28782. * @returns a list of transform nodes
  28783. */
  28784. Scene.prototype.getTransformNodesByID = function (id) {
  28785. return this.transformNodes.filter(function (m) {
  28786. return m.id === id;
  28787. });
  28788. };
  28789. /**
  28790. * Gets a mesh with its auto-generated unique id
  28791. * @param uniqueId defines the unique id to search for
  28792. * @return the found mesh or null if not found at all.
  28793. */
  28794. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  28795. for (var index = 0; index < this.meshes.length; index++) {
  28796. if (this.meshes[index].uniqueId === uniqueId) {
  28797. return this.meshes[index];
  28798. }
  28799. }
  28800. return null;
  28801. };
  28802. /**
  28803. * Gets a the last added mesh using a given id
  28804. * @param id defines the id to search for
  28805. * @return the found mesh or null if not found at all.
  28806. */
  28807. Scene.prototype.getLastMeshByID = function (id) {
  28808. for (var index = this.meshes.length - 1; index >= 0; index--) {
  28809. if (this.meshes[index].id === id) {
  28810. return this.meshes[index];
  28811. }
  28812. }
  28813. return null;
  28814. };
  28815. /**
  28816. * Gets a the last added node (Mesh, Camera, Light) using a given id
  28817. * @param id defines the id to search for
  28818. * @return the found node or null if not found at all
  28819. */
  28820. Scene.prototype.getLastEntryByID = function (id) {
  28821. var index;
  28822. for (index = this.meshes.length - 1; index >= 0; index--) {
  28823. if (this.meshes[index].id === id) {
  28824. return this.meshes[index];
  28825. }
  28826. }
  28827. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  28828. if (this.transformNodes[index].id === id) {
  28829. return this.transformNodes[index];
  28830. }
  28831. }
  28832. for (index = this.cameras.length - 1; index >= 0; index--) {
  28833. if (this.cameras[index].id === id) {
  28834. return this.cameras[index];
  28835. }
  28836. }
  28837. for (index = this.lights.length - 1; index >= 0; index--) {
  28838. if (this.lights[index].id === id) {
  28839. return this.lights[index];
  28840. }
  28841. }
  28842. return null;
  28843. };
  28844. /**
  28845. * Gets a node (Mesh, Camera, Light) using a given id
  28846. * @param id defines the id to search for
  28847. * @return the found node or null if not found at all
  28848. */
  28849. Scene.prototype.getNodeByID = function (id) {
  28850. var mesh = this.getMeshByID(id);
  28851. if (mesh) {
  28852. return mesh;
  28853. }
  28854. var transformNode = this.getTransformNodeByID(id);
  28855. if (transformNode) {
  28856. return transformNode;
  28857. }
  28858. var light = this.getLightByID(id);
  28859. if (light) {
  28860. return light;
  28861. }
  28862. var camera = this.getCameraByID(id);
  28863. if (camera) {
  28864. return camera;
  28865. }
  28866. var bone = this.getBoneByID(id);
  28867. if (bone) {
  28868. return bone;
  28869. }
  28870. return null;
  28871. };
  28872. /**
  28873. * Gets a node (Mesh, Camera, Light) using a given name
  28874. * @param name defines the name to search for
  28875. * @return the found node or null if not found at all.
  28876. */
  28877. Scene.prototype.getNodeByName = function (name) {
  28878. var mesh = this.getMeshByName(name);
  28879. if (mesh) {
  28880. return mesh;
  28881. }
  28882. var transformNode = this.getTransformNodeByName(name);
  28883. if (transformNode) {
  28884. return transformNode;
  28885. }
  28886. var light = this.getLightByName(name);
  28887. if (light) {
  28888. return light;
  28889. }
  28890. var camera = this.getCameraByName(name);
  28891. if (camera) {
  28892. return camera;
  28893. }
  28894. var bone = this.getBoneByName(name);
  28895. if (bone) {
  28896. return bone;
  28897. }
  28898. return null;
  28899. };
  28900. /**
  28901. * Gets a mesh using a given name
  28902. * @param name defines the name to search for
  28903. * @return the found mesh or null if not found at all.
  28904. */
  28905. Scene.prototype.getMeshByName = function (name) {
  28906. for (var index = 0; index < this.meshes.length; index++) {
  28907. if (this.meshes[index].name === name) {
  28908. return this.meshes[index];
  28909. }
  28910. }
  28911. return null;
  28912. };
  28913. /**
  28914. * Gets a transform node using a given name
  28915. * @param name defines the name to search for
  28916. * @return the found transform node or null if not found at all.
  28917. */
  28918. Scene.prototype.getTransformNodeByName = function (name) {
  28919. for (var index = 0; index < this.transformNodes.length; index++) {
  28920. if (this.transformNodes[index].name === name) {
  28921. return this.transformNodes[index];
  28922. }
  28923. }
  28924. return null;
  28925. };
  28926. /**
  28927. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  28928. * @param id defines the id to search for
  28929. * @return the found skeleton or null if not found at all.
  28930. */
  28931. Scene.prototype.getLastSkeletonByID = function (id) {
  28932. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  28933. if (this.skeletons[index].id === id) {
  28934. return this.skeletons[index];
  28935. }
  28936. }
  28937. return null;
  28938. };
  28939. /**
  28940. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  28941. * @param id defines the id to search for
  28942. * @return the found skeleton or null if not found at all.
  28943. */
  28944. Scene.prototype.getSkeletonById = function (id) {
  28945. for (var index = 0; index < this.skeletons.length; index++) {
  28946. if (this.skeletons[index].id === id) {
  28947. return this.skeletons[index];
  28948. }
  28949. }
  28950. return null;
  28951. };
  28952. /**
  28953. * Gets a skeleton using a given name
  28954. * @param name defines the name to search for
  28955. * @return the found skeleton or null if not found at all.
  28956. */
  28957. Scene.prototype.getSkeletonByName = function (name) {
  28958. for (var index = 0; index < this.skeletons.length; index++) {
  28959. if (this.skeletons[index].name === name) {
  28960. return this.skeletons[index];
  28961. }
  28962. }
  28963. return null;
  28964. };
  28965. /**
  28966. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  28967. * @param id defines the id to search for
  28968. * @return the found morph target manager or null if not found at all.
  28969. */
  28970. Scene.prototype.getMorphTargetManagerById = function (id) {
  28971. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  28972. if (this.morphTargetManagers[index].uniqueId === id) {
  28973. return this.morphTargetManagers[index];
  28974. }
  28975. }
  28976. return null;
  28977. };
  28978. /**
  28979. * Gets a morph target using a given id (if many are found, this function will pick the first one)
  28980. * @param id defines the id to search for
  28981. * @return the found morph target or null if not found at all.
  28982. */
  28983. Scene.prototype.getMorphTargetById = function (id) {
  28984. for (var managerIndex = 0; managerIndex < this.morphTargetManagers.length; ++managerIndex) {
  28985. var morphTargetManager = this.morphTargetManagers[managerIndex];
  28986. for (var index = 0; index < morphTargetManager.numTargets; ++index) {
  28987. var target = morphTargetManager.getTarget(index);
  28988. if (target.id === id) {
  28989. return target;
  28990. }
  28991. }
  28992. }
  28993. return null;
  28994. };
  28995. /**
  28996. * Gets a boolean indicating if the given mesh is active
  28997. * @param mesh defines the mesh to look for
  28998. * @returns true if the mesh is in the active list
  28999. */
  29000. Scene.prototype.isActiveMesh = function (mesh) {
  29001. return (this._activeMeshes.indexOf(mesh) !== -1);
  29002. };
  29003. Object.defineProperty(Scene.prototype, "uid", {
  29004. /**
  29005. * Return a unique id as a string which can serve as an identifier for the scene
  29006. */
  29007. get: function () {
  29008. if (!this._uid) {
  29009. this._uid = BABYLON.Tools.RandomId();
  29010. }
  29011. return this._uid;
  29012. },
  29013. enumerable: true,
  29014. configurable: true
  29015. });
  29016. /**
  29017. * Add an externaly attached data from its key.
  29018. * This method call will fail and return false, if such key already exists.
  29019. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  29020. * @param key the unique key that identifies the data
  29021. * @param data the data object to associate to the key for this Engine instance
  29022. * @return true if no such key were already present and the data was added successfully, false otherwise
  29023. */
  29024. Scene.prototype.addExternalData = function (key, data) {
  29025. if (!this._externalData) {
  29026. this._externalData = new BABYLON.StringDictionary();
  29027. }
  29028. return this._externalData.add(key, data);
  29029. };
  29030. /**
  29031. * Get an externaly attached data from its key
  29032. * @param key the unique key that identifies the data
  29033. * @return the associated data, if present (can be null), or undefined if not present
  29034. */
  29035. Scene.prototype.getExternalData = function (key) {
  29036. if (!this._externalData) {
  29037. return null;
  29038. }
  29039. return this._externalData.get(key);
  29040. };
  29041. /**
  29042. * Get an externaly attached data from its key, create it using a factory if it's not already present
  29043. * @param key the unique key that identifies the data
  29044. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  29045. * @return the associated data, can be null if the factory returned null.
  29046. */
  29047. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  29048. if (!this._externalData) {
  29049. this._externalData = new BABYLON.StringDictionary();
  29050. }
  29051. return this._externalData.getOrAddWithFactory(key, factory);
  29052. };
  29053. /**
  29054. * Remove an externaly attached data from the Engine instance
  29055. * @param key the unique key that identifies the data
  29056. * @return true if the data was successfully removed, false if it doesn't exist
  29057. */
  29058. Scene.prototype.removeExternalData = function (key) {
  29059. return this._externalData.remove(key);
  29060. };
  29061. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  29062. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  29063. for (var _i = 0, _a = this._evaluateSubMeshStage; _i < _a.length; _i++) {
  29064. var step = _a[_i];
  29065. step.action(mesh, subMesh);
  29066. }
  29067. var material = subMesh.getMaterial();
  29068. if (material !== null && material !== undefined) {
  29069. // Render targets
  29070. if (material.hasRenderTargetTextures && material.getRenderTargetTextures !== undefined) {
  29071. if (this._processedMaterials.indexOf(material) === -1) {
  29072. this._processedMaterials.push(material);
  29073. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  29074. }
  29075. }
  29076. // Dispatch
  29077. this._activeIndices.addCount(subMesh.indexCount, false);
  29078. this._renderingManager.dispatch(subMesh, mesh, material);
  29079. }
  29080. }
  29081. };
  29082. /**
  29083. * Clear the processed materials smart array preventing retention point in material dispose.
  29084. */
  29085. Scene.prototype.freeProcessedMaterials = function () {
  29086. this._processedMaterials.dispose();
  29087. };
  29088. Object.defineProperty(Scene.prototype, "blockfreeActiveMeshesAndRenderingGroups", {
  29089. /** Gets or sets a boolean blocking all the calls to freeActiveMeshes and freeRenderingGroups
  29090. * It can be used in order to prevent going through methods freeRenderingGroups and freeActiveMeshes several times to improve performance
  29091. * when disposing several meshes in a row or a hierarchy of meshes.
  29092. * When used, it is the responsability of the user to blockfreeActiveMeshesAndRenderingGroups back to false.
  29093. */
  29094. get: function () {
  29095. return this._preventFreeActiveMeshesAndRenderingGroups;
  29096. },
  29097. set: function (value) {
  29098. if (this._preventFreeActiveMeshesAndRenderingGroups === value) {
  29099. return;
  29100. }
  29101. if (value) {
  29102. this.freeActiveMeshes();
  29103. this.freeRenderingGroups();
  29104. }
  29105. this._preventFreeActiveMeshesAndRenderingGroups = value;
  29106. },
  29107. enumerable: true,
  29108. configurable: true
  29109. });
  29110. /**
  29111. * Clear the active meshes smart array preventing retention point in mesh dispose.
  29112. */
  29113. Scene.prototype.freeActiveMeshes = function () {
  29114. if (this.blockfreeActiveMeshesAndRenderingGroups) {
  29115. return;
  29116. }
  29117. this._activeMeshes.dispose();
  29118. if (this.activeCamera && this.activeCamera._activeMeshes) {
  29119. this.activeCamera._activeMeshes.dispose();
  29120. }
  29121. if (this.activeCameras) {
  29122. for (var i = 0; i < this.activeCameras.length; i++) {
  29123. var activeCamera = this.activeCameras[i];
  29124. if (activeCamera && activeCamera._activeMeshes) {
  29125. activeCamera._activeMeshes.dispose();
  29126. }
  29127. }
  29128. }
  29129. };
  29130. /**
  29131. * Clear the info related to rendering groups preventing retention points during dispose.
  29132. */
  29133. Scene.prototype.freeRenderingGroups = function () {
  29134. if (this.blockfreeActiveMeshesAndRenderingGroups) {
  29135. return;
  29136. }
  29137. if (this._renderingManager) {
  29138. this._renderingManager.freeRenderingGroups();
  29139. }
  29140. if (this.textures) {
  29141. for (var i = 0; i < this.textures.length; i++) {
  29142. var texture = this.textures[i];
  29143. if (texture && texture.renderList) {
  29144. texture.freeRenderingGroups();
  29145. }
  29146. }
  29147. }
  29148. };
  29149. /** @hidden */
  29150. Scene.prototype._isInIntermediateRendering = function () {
  29151. return this._intermediateRendering;
  29152. };
  29153. /**
  29154. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  29155. * @returns the current scene
  29156. */
  29157. Scene.prototype.freezeActiveMeshes = function () {
  29158. if (!this.activeCamera) {
  29159. return this;
  29160. }
  29161. if (!this._frustumPlanes) {
  29162. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  29163. }
  29164. this._evaluateActiveMeshes();
  29165. this._activeMeshesFrozen = true;
  29166. return this;
  29167. };
  29168. /**
  29169. * Use this function to restart evaluating active meshes on every frame
  29170. * @returns the current scene
  29171. */
  29172. Scene.prototype.unfreezeActiveMeshes = function () {
  29173. this._activeMeshesFrozen = false;
  29174. return this;
  29175. };
  29176. Scene.prototype._evaluateActiveMeshes = function () {
  29177. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  29178. return;
  29179. }
  29180. if (!this.activeCamera) {
  29181. return;
  29182. }
  29183. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  29184. this.activeCamera._activeMeshes.reset();
  29185. this._activeMeshes.reset();
  29186. this._renderingManager.reset();
  29187. this._processedMaterials.reset();
  29188. this._activeParticleSystems.reset();
  29189. this._activeSkeletons.reset();
  29190. this._softwareSkinnedMeshes.reset();
  29191. for (var _i = 0, _a = this._beforeEvaluateActiveMeshStage; _i < _a.length; _i++) {
  29192. var step = _a[_i];
  29193. step.action();
  29194. }
  29195. // Determine mesh candidates
  29196. var meshes = this.getActiveMeshCandidates();
  29197. // Check each mesh
  29198. var len = meshes.length;
  29199. for (var i = 0; i < len; i++) {
  29200. var mesh = meshes.data[i];
  29201. if (mesh.isBlocked) {
  29202. continue;
  29203. }
  29204. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  29205. if (!mesh.isReady() || !mesh.isEnabled()) {
  29206. continue;
  29207. }
  29208. mesh.computeWorldMatrix();
  29209. // Intersections
  29210. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers2(BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger)) {
  29211. this._meshesForIntersections.pushNoDuplicate(mesh);
  29212. }
  29213. // Switch to current LOD
  29214. var meshLOD = mesh.getLOD(this.activeCamera);
  29215. if (meshLOD === undefined || meshLOD === null) {
  29216. continue;
  29217. }
  29218. mesh._preActivate();
  29219. if (mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && (mesh.alwaysSelectAsActiveMesh || mesh.isInFrustum(this._frustumPlanes))) {
  29220. this._activeMeshes.push(mesh);
  29221. this.activeCamera._activeMeshes.push(mesh);
  29222. mesh._activate(this._renderId);
  29223. if (meshLOD !== mesh) {
  29224. meshLOD._activate(this._renderId);
  29225. }
  29226. this._activeMesh(mesh, meshLOD);
  29227. }
  29228. }
  29229. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  29230. // Particle systems
  29231. if (this.particlesEnabled) {
  29232. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  29233. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  29234. var particleSystem = this.particleSystems[particleIndex];
  29235. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  29236. continue;
  29237. }
  29238. var emitter = particleSystem.emitter;
  29239. if (!emitter.position || emitter.isEnabled()) {
  29240. this._activeParticleSystems.push(particleSystem);
  29241. particleSystem.animate();
  29242. this._renderingManager.dispatchParticles(particleSystem);
  29243. }
  29244. }
  29245. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  29246. }
  29247. };
  29248. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  29249. if (this._skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  29250. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  29251. mesh.skeleton.prepare();
  29252. }
  29253. if (!mesh.computeBonesUsingShaders) {
  29254. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  29255. }
  29256. }
  29257. for (var _i = 0, _a = this._activeMeshStage; _i < _a.length; _i++) {
  29258. var step = _a[_i];
  29259. step.action(sourceMesh, mesh);
  29260. }
  29261. if (mesh !== undefined && mesh !== null
  29262. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  29263. var subMeshes = this.getActiveSubMeshCandidates(mesh);
  29264. var len = subMeshes.length;
  29265. for (var i = 0; i < len; i++) {
  29266. var subMesh = subMeshes.data[i];
  29267. this._evaluateSubMesh(subMesh, mesh);
  29268. }
  29269. }
  29270. };
  29271. /**
  29272. * Update the transform matrix to update from the current active camera
  29273. * @param force defines a boolean used to force the update even if cache is up to date
  29274. */
  29275. Scene.prototype.updateTransformMatrix = function (force) {
  29276. if (!this.activeCamera) {
  29277. return;
  29278. }
  29279. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  29280. };
  29281. /**
  29282. * 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)
  29283. * @param alternateCamera defines the camera to use
  29284. */
  29285. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  29286. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  29287. };
  29288. Scene.prototype._renderForCamera = function (camera, rigParent) {
  29289. if (camera && camera._skipRendering) {
  29290. return;
  29291. }
  29292. var engine = this._engine;
  29293. this.activeCamera = camera;
  29294. if (!this.activeCamera) {
  29295. throw new Error("Active camera not set");
  29296. }
  29297. // Viewport
  29298. engine.setViewport(this.activeCamera.viewport);
  29299. // Camera
  29300. this.resetCachedMaterial();
  29301. this._renderId++;
  29302. this.updateTransformMatrix();
  29303. if (camera._alternateCamera) {
  29304. this.updateAlternateTransformMatrix(camera._alternateCamera);
  29305. this._alternateRendering = true;
  29306. }
  29307. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  29308. // Meshes
  29309. this._evaluateActiveMeshes();
  29310. // Software skinning
  29311. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  29312. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  29313. mesh.applySkeleton(mesh.skeleton);
  29314. }
  29315. // Render targets
  29316. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  29317. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  29318. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  29319. }
  29320. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  29321. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  29322. }
  29323. // Collects render targets from external components.
  29324. for (var _i = 0, _a = this._gatherActiveCameraRenderTargetsStage; _i < _a.length; _i++) {
  29325. var step = _a[_i];
  29326. step.action(this._renderTargets);
  29327. }
  29328. if (this.renderTargetsEnabled) {
  29329. this._intermediateRendering = true;
  29330. if (this._renderTargets.length > 0) {
  29331. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  29332. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  29333. var renderTarget = this._renderTargets.data[renderIndex];
  29334. if (renderTarget._shouldRender()) {
  29335. this._renderId++;
  29336. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  29337. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  29338. }
  29339. }
  29340. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  29341. this._renderId++;
  29342. }
  29343. for (var _b = 0, _c = this._cameraDrawRenderTargetStage; _b < _c.length; _b++) {
  29344. var step = _c[_b];
  29345. step.action(this.activeCamera);
  29346. }
  29347. this._intermediateRendering = false;
  29348. if (this.activeCamera.outputRenderTarget) {
  29349. var internalTexture = this.activeCamera.outputRenderTarget.getInternalTexture();
  29350. if (internalTexture) {
  29351. engine.bindFramebuffer(internalTexture);
  29352. }
  29353. else {
  29354. BABYLON.Tools.Error("Camera contains invalid customDefaultRenderTarget");
  29355. }
  29356. }
  29357. else {
  29358. engine.restoreDefaultFramebuffer(); // Restore back buffer if needed
  29359. }
  29360. }
  29361. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  29362. // Prepare Frame
  29363. if (this.postProcessManager) {
  29364. this.postProcessManager._prepareFrame();
  29365. }
  29366. // Before Camera Draw
  29367. for (var _d = 0, _e = this._beforeCameraDrawStage; _d < _e.length; _d++) {
  29368. var step = _e[_d];
  29369. step.action(this.activeCamera);
  29370. }
  29371. // Render
  29372. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  29373. this._renderingManager.render(null, null, true, true);
  29374. this.onAfterDrawPhaseObservable.notifyObservers(this);
  29375. // After Camera Draw
  29376. for (var _f = 0, _g = this._afterCameraDrawStage; _f < _g.length; _f++) {
  29377. var step = _g[_f];
  29378. step.action(this.activeCamera);
  29379. }
  29380. // Finalize frame
  29381. if (this.postProcessManager) {
  29382. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  29383. }
  29384. // Reset some special arrays
  29385. this._renderTargets.reset();
  29386. this._alternateRendering = false;
  29387. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  29388. };
  29389. Scene.prototype._processSubCameras = function (camera) {
  29390. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  29391. this._renderForCamera(camera);
  29392. return;
  29393. }
  29394. // rig cameras
  29395. for (var index = 0; index < camera._rigCameras.length; index++) {
  29396. this._renderForCamera(camera._rigCameras[index], camera);
  29397. }
  29398. this.activeCamera = camera;
  29399. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  29400. };
  29401. Scene.prototype._checkIntersections = function () {
  29402. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  29403. var sourceMesh = this._meshesForIntersections.data[index];
  29404. if (!sourceMesh.actionManager) {
  29405. continue;
  29406. }
  29407. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  29408. var action = sourceMesh.actionManager.actions[actionIndex];
  29409. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  29410. var parameters = action.getTriggerParameter();
  29411. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  29412. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  29413. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  29414. if (areIntersecting && currentIntersectionInProgress === -1) {
  29415. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  29416. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  29417. sourceMesh._intersectionsInProgress.push(otherMesh);
  29418. }
  29419. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  29420. sourceMesh._intersectionsInProgress.push(otherMesh);
  29421. }
  29422. }
  29423. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  29424. //They intersected, and now they don't.
  29425. //is this trigger an exit trigger? execute an event.
  29426. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  29427. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  29428. }
  29429. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  29430. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
  29431. var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
  29432. return otherMesh === parameterMesh;
  29433. }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  29434. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  29435. }
  29436. }
  29437. }
  29438. }
  29439. }
  29440. };
  29441. /** @hidden */
  29442. Scene.prototype._advancePhysicsEngineStep = function (step) {
  29443. // Do nothing. Code will be replaced if physics engine component is referenced
  29444. };
  29445. /**
  29446. * Render the scene
  29447. * @param updateCameras defines a boolean indicating if cameras must update according to their inputs (true by default)
  29448. */
  29449. Scene.prototype.render = function (updateCameras) {
  29450. if (updateCameras === void 0) { updateCameras = true; }
  29451. if (this.isDisposed) {
  29452. return;
  29453. }
  29454. this._frameId++;
  29455. // Register components that have been associated lately to the scene.
  29456. this._registerTransientComponents();
  29457. this._activeParticles.fetchNewFrame();
  29458. this._totalVertices.fetchNewFrame();
  29459. this._activeIndices.fetchNewFrame();
  29460. this._activeBones.fetchNewFrame();
  29461. this._meshesForIntersections.reset();
  29462. this.resetCachedMaterial();
  29463. this.onBeforeAnimationsObservable.notifyObservers(this);
  29464. // Actions
  29465. if (this.actionManager) {
  29466. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  29467. }
  29468. if (this._engine.isDeterministicLockStep()) {
  29469. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  29470. var defaultFPS = (60.0 / 1000.0);
  29471. var defaultFrameTime = this.getDeterministicFrameTime();
  29472. var stepsTaken = 0;
  29473. var maxSubSteps = this._engine.getLockstepMaxSteps();
  29474. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  29475. internalSteps = Math.min(internalSteps, maxSubSteps);
  29476. do {
  29477. this.onBeforeStepObservable.notifyObservers(this);
  29478. // Animations
  29479. this._animationRatio = defaultFrameTime * defaultFPS;
  29480. this._animate();
  29481. this.onAfterAnimationsObservable.notifyObservers(this);
  29482. // Physics
  29483. this._advancePhysicsEngineStep(defaultFrameTime);
  29484. this.onAfterStepObservable.notifyObservers(this);
  29485. this._currentStepId++;
  29486. stepsTaken++;
  29487. deltaTime -= defaultFrameTime;
  29488. } while (deltaTime > 0 && stepsTaken < internalSteps);
  29489. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  29490. }
  29491. else {
  29492. // Animations
  29493. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  29494. this._animationRatio = deltaTime * (60.0 / 1000.0);
  29495. this._animate();
  29496. this.onAfterAnimationsObservable.notifyObservers(this);
  29497. // Physics
  29498. this._advancePhysicsEngineStep(deltaTime);
  29499. }
  29500. // Before camera update steps
  29501. for (var _i = 0, _a = this._beforeCameraUpdateStage; _i < _a.length; _i++) {
  29502. var step = _a[_i];
  29503. step.action();
  29504. }
  29505. // Update Cameras
  29506. if (updateCameras) {
  29507. if (this.activeCameras.length > 0) {
  29508. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  29509. var camera = this.activeCameras[cameraIndex];
  29510. camera.update();
  29511. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  29512. // rig cameras
  29513. for (var index = 0; index < camera._rigCameras.length; index++) {
  29514. camera._rigCameras[index].update();
  29515. }
  29516. }
  29517. }
  29518. }
  29519. else if (this.activeCamera) {
  29520. this.activeCamera.update();
  29521. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  29522. // rig cameras
  29523. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  29524. this.activeCamera._rigCameras[index].update();
  29525. }
  29526. }
  29527. }
  29528. }
  29529. // Before render
  29530. this.onBeforeRenderObservable.notifyObservers(this);
  29531. // Customs render targets
  29532. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  29533. var engine = this.getEngine();
  29534. var currentActiveCamera = this.activeCamera;
  29535. if (this.renderTargetsEnabled) {
  29536. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  29537. this._intermediateRendering = true;
  29538. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  29539. var renderTarget = this.customRenderTargets[customIndex];
  29540. if (renderTarget._shouldRender()) {
  29541. this._renderId++;
  29542. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  29543. if (!this.activeCamera) {
  29544. throw new Error("Active camera not set");
  29545. }
  29546. // Viewport
  29547. engine.setViewport(this.activeCamera.viewport);
  29548. // Camera
  29549. this.updateTransformMatrix();
  29550. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  29551. }
  29552. }
  29553. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  29554. this._intermediateRendering = false;
  29555. this._renderId++;
  29556. }
  29557. // Restore back buffer
  29558. if (this.customRenderTargets.length > 0) {
  29559. engine.restoreDefaultFramebuffer();
  29560. }
  29561. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  29562. this.activeCamera = currentActiveCamera;
  29563. for (var _b = 0, _c = this._beforeClearStage; _b < _c.length; _b++) {
  29564. var step = _c[_b];
  29565. step.action();
  29566. }
  29567. // Clear
  29568. if (this.autoClearDepthAndStencil || this.autoClear) {
  29569. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  29570. }
  29571. // Collects render targets from external components.
  29572. for (var _d = 0, _e = this._gatherRenderTargetsStage; _d < _e.length; _d++) {
  29573. var step = _e[_d];
  29574. step.action(this._renderTargets);
  29575. }
  29576. // Multi-cameras?
  29577. if (this.activeCameras.length > 0) {
  29578. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  29579. if (cameraIndex > 0) {
  29580. this._engine.clear(null, false, true, true);
  29581. }
  29582. this._processSubCameras(this.activeCameras[cameraIndex]);
  29583. }
  29584. }
  29585. else {
  29586. if (!this.activeCamera) {
  29587. throw new Error("No camera defined");
  29588. }
  29589. this._processSubCameras(this.activeCamera);
  29590. }
  29591. // Intersection checks
  29592. this._checkIntersections();
  29593. // Executes the after render stage actions.
  29594. for (var _f = 0, _g = this._afterRenderStage; _f < _g.length; _f++) {
  29595. var step = _g[_f];
  29596. step.action();
  29597. }
  29598. // After render
  29599. if (this.afterRender) {
  29600. this.afterRender();
  29601. }
  29602. this.onAfterRenderObservable.notifyObservers(this);
  29603. // Cleaning
  29604. if (this._toBeDisposed.length) {
  29605. for (var index = 0; index < this._toBeDisposed.length; index++) {
  29606. var data = this._toBeDisposed[index];
  29607. if (data) {
  29608. data.dispose();
  29609. }
  29610. }
  29611. this._toBeDisposed = [];
  29612. }
  29613. if (this.dumpNextRenderTargets) {
  29614. this.dumpNextRenderTargets = false;
  29615. }
  29616. this._activeBones.addCount(0, true);
  29617. this._activeIndices.addCount(0, true);
  29618. this._activeParticles.addCount(0, true);
  29619. };
  29620. /**
  29621. * Freeze all materials
  29622. * A frozen material will not be updatable but should be faster to render
  29623. */
  29624. Scene.prototype.freezeMaterials = function () {
  29625. for (var i = 0; i < this.materials.length; i++) {
  29626. this.materials[i].freeze();
  29627. }
  29628. };
  29629. /**
  29630. * Unfreeze all materials
  29631. * A frozen material will not be updatable but should be faster to render
  29632. */
  29633. Scene.prototype.unfreezeMaterials = function () {
  29634. for (var i = 0; i < this.materials.length; i++) {
  29635. this.materials[i].unfreeze();
  29636. }
  29637. };
  29638. /**
  29639. * Releases all held ressources
  29640. */
  29641. Scene.prototype.dispose = function () {
  29642. this.beforeRender = null;
  29643. this.afterRender = null;
  29644. this.skeletons = [];
  29645. this.morphTargetManagers = [];
  29646. this._transientComponents = [];
  29647. this._isReadyForMeshStage.clear();
  29648. this._beforeEvaluateActiveMeshStage.clear();
  29649. this._evaluateSubMeshStage.clear();
  29650. this._activeMeshStage.clear();
  29651. this._cameraDrawRenderTargetStage.clear();
  29652. this._beforeCameraDrawStage.clear();
  29653. this._beforeRenderTargetDrawStage.clear();
  29654. this._beforeRenderingGroupDrawStage.clear();
  29655. this._beforeRenderingMeshStage.clear();
  29656. this._afterRenderingMeshStage.clear();
  29657. this._afterRenderingGroupDrawStage.clear();
  29658. this._afterCameraDrawStage.clear();
  29659. this._afterRenderTargetDrawStage.clear();
  29660. this._afterRenderStage.clear();
  29661. this._beforeCameraUpdateStage.clear();
  29662. this._beforeClearStage.clear();
  29663. this._gatherRenderTargetsStage.clear();
  29664. this._gatherActiveCameraRenderTargetsStage.clear();
  29665. this._pointerMoveStage.clear();
  29666. this._pointerDownStage.clear();
  29667. this._pointerUpStage.clear();
  29668. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  29669. var component = _a[_i];
  29670. component.dispose();
  29671. }
  29672. this.importedMeshesFiles = new Array();
  29673. this.stopAllAnimations();
  29674. this.resetCachedMaterial();
  29675. // Smart arrays
  29676. if (this.activeCamera) {
  29677. this.activeCamera._activeMeshes.dispose();
  29678. this.activeCamera = null;
  29679. }
  29680. this._activeMeshes.dispose();
  29681. this._renderingManager.dispose();
  29682. this._processedMaterials.dispose();
  29683. this._activeParticleSystems.dispose();
  29684. this._activeSkeletons.dispose();
  29685. this._softwareSkinnedMeshes.dispose();
  29686. this._renderTargets.dispose();
  29687. this._registeredForLateAnimationBindings.dispose();
  29688. this._meshesForIntersections.dispose();
  29689. this._toBeDisposed = [];
  29690. // Abort active requests
  29691. for (var _b = 0, _c = this._activeRequests; _b < _c.length; _b++) {
  29692. var request = _c[_b];
  29693. request.abort();
  29694. }
  29695. // Events
  29696. this.onDisposeObservable.notifyObservers(this);
  29697. this.onDisposeObservable.clear();
  29698. this.onBeforeRenderObservable.clear();
  29699. this.onAfterRenderObservable.clear();
  29700. this.onBeforeRenderTargetsRenderObservable.clear();
  29701. this.onAfterRenderTargetsRenderObservable.clear();
  29702. this.onAfterStepObservable.clear();
  29703. this.onBeforeStepObservable.clear();
  29704. this.onBeforeActiveMeshesEvaluationObservable.clear();
  29705. this.onAfterActiveMeshesEvaluationObservable.clear();
  29706. this.onBeforeParticlesRenderingObservable.clear();
  29707. this.onAfterParticlesRenderingObservable.clear();
  29708. this.onBeforeDrawPhaseObservable.clear();
  29709. this.onAfterDrawPhaseObservable.clear();
  29710. this.onBeforeAnimationsObservable.clear();
  29711. this.onAfterAnimationsObservable.clear();
  29712. this.onDataLoadedObservable.clear();
  29713. this.onBeforeRenderingGroupObservable.clear();
  29714. this.onAfterRenderingGroupObservable.clear();
  29715. this.onMeshImportedObservable.clear();
  29716. this.onBeforeCameraRenderObservable.clear();
  29717. this.onAfterCameraRenderObservable.clear();
  29718. this.onReadyObservable.clear();
  29719. this.onNewCameraAddedObservable.clear();
  29720. this.onCameraRemovedObservable.clear();
  29721. this.onNewLightAddedObservable.clear();
  29722. this.onLightRemovedObservable.clear();
  29723. this.onNewGeometryAddedObservable.clear();
  29724. this.onGeometryRemovedObservable.clear();
  29725. this.onNewTransformNodeAddedObservable.clear();
  29726. this.onTransformNodeRemovedObservable.clear();
  29727. this.onNewMeshAddedObservable.clear();
  29728. this.onMeshRemovedObservable.clear();
  29729. this.onNewMaterialAddedObservable.clear();
  29730. this.onMaterialRemovedObservable.clear();
  29731. this.onNewTextureAddedObservable.clear();
  29732. this.onTextureRemovedObservable.clear();
  29733. this.onPrePointerObservable.clear();
  29734. this.onPointerObservable.clear();
  29735. this.onPreKeyboardObservable.clear();
  29736. this.onKeyboardObservable.clear();
  29737. this.onActiveCameraChanged.clear();
  29738. this.detachControl();
  29739. // Detach cameras
  29740. var canvas = this._engine.getRenderingCanvas();
  29741. if (canvas) {
  29742. var index;
  29743. for (index = 0; index < this.cameras.length; index++) {
  29744. this.cameras[index].detachControl(canvas);
  29745. }
  29746. }
  29747. // Release animation groups
  29748. while (this.animationGroups.length) {
  29749. this.animationGroups[0].dispose();
  29750. }
  29751. // Release lights
  29752. while (this.lights.length) {
  29753. this.lights[0].dispose();
  29754. }
  29755. // Release meshes
  29756. while (this.meshes.length) {
  29757. this.meshes[0].dispose(true);
  29758. }
  29759. while (this.transformNodes.length) {
  29760. this.removeTransformNode(this.transformNodes[0]);
  29761. }
  29762. // Release cameras
  29763. while (this.cameras.length) {
  29764. this.cameras[0].dispose();
  29765. }
  29766. // Release materials
  29767. if (this.defaultMaterial) {
  29768. this.defaultMaterial.dispose();
  29769. }
  29770. while (this.multiMaterials.length) {
  29771. this.multiMaterials[0].dispose();
  29772. }
  29773. while (this.materials.length) {
  29774. this.materials[0].dispose();
  29775. }
  29776. // Release particles
  29777. while (this.particleSystems.length) {
  29778. this.particleSystems[0].dispose();
  29779. }
  29780. // Release postProcesses
  29781. while (this.postProcesses.length) {
  29782. this.postProcesses[0].dispose();
  29783. }
  29784. // Release textures
  29785. while (this.textures.length) {
  29786. this.textures[0].dispose();
  29787. }
  29788. // Release UBO
  29789. this._sceneUbo.dispose();
  29790. if (this._alternateSceneUbo) {
  29791. this._alternateSceneUbo.dispose();
  29792. }
  29793. // Post-processes
  29794. this.postProcessManager.dispose();
  29795. // Remove from engine
  29796. index = this._engine.scenes.indexOf(this);
  29797. if (index > -1) {
  29798. this._engine.scenes.splice(index, 1);
  29799. }
  29800. this._engine.wipeCaches(true);
  29801. this._isDisposed = true;
  29802. };
  29803. Object.defineProperty(Scene.prototype, "isDisposed", {
  29804. /**
  29805. * Gets if the scene is already disposed
  29806. */
  29807. get: function () {
  29808. return this._isDisposed;
  29809. },
  29810. enumerable: true,
  29811. configurable: true
  29812. });
  29813. /**
  29814. * Call this function to reduce memory footprint of the scene.
  29815. * Vertex buffers will not store CPU data anymore (this will prevent picking, collisions or physics to work correctly)
  29816. */
  29817. Scene.prototype.clearCachedVertexData = function () {
  29818. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  29819. var mesh = this.meshes[meshIndex];
  29820. var geometry = mesh.geometry;
  29821. if (geometry) {
  29822. geometry._indices = [];
  29823. for (var vbName in geometry._vertexBuffers) {
  29824. if (!geometry._vertexBuffers.hasOwnProperty(vbName)) {
  29825. continue;
  29826. }
  29827. geometry._vertexBuffers[vbName]._buffer._data = null;
  29828. }
  29829. }
  29830. }
  29831. };
  29832. /**
  29833. * This function will remove the local cached buffer data from texture.
  29834. * It will save memory but will prevent the texture from being rebuilt
  29835. */
  29836. Scene.prototype.cleanCachedTextureBuffer = function () {
  29837. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  29838. var baseTexture = _a[_i];
  29839. var buffer = baseTexture._buffer;
  29840. if (buffer) {
  29841. baseTexture._buffer = null;
  29842. }
  29843. }
  29844. };
  29845. /**
  29846. * Get the world extend vectors with an optional filter
  29847. *
  29848. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  29849. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  29850. */
  29851. Scene.prototype.getWorldExtends = function (filterPredicate) {
  29852. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  29853. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  29854. filterPredicate = filterPredicate || (function () { return true; });
  29855. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  29856. mesh.computeWorldMatrix(true);
  29857. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  29858. return;
  29859. }
  29860. var boundingInfo = mesh.getBoundingInfo();
  29861. var minBox = boundingInfo.boundingBox.minimumWorld;
  29862. var maxBox = boundingInfo.boundingBox.maximumWorld;
  29863. BABYLON.Tools.CheckExtends(minBox, min, max);
  29864. BABYLON.Tools.CheckExtends(maxBox, min, max);
  29865. });
  29866. return {
  29867. min: min,
  29868. max: max
  29869. };
  29870. };
  29871. // Picking
  29872. /**
  29873. * Creates a ray that can be used to pick in the scene
  29874. * @param x defines the x coordinate of the origin (on-screen)
  29875. * @param y defines the y coordinate of the origin (on-screen)
  29876. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  29877. * @param camera defines the camera to use for the picking
  29878. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  29879. * @returns a Ray
  29880. */
  29881. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  29882. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  29883. var result = BABYLON.Ray.Zero();
  29884. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  29885. return result;
  29886. };
  29887. /**
  29888. * Creates a ray that can be used to pick in the scene
  29889. * @param x defines the x coordinate of the origin (on-screen)
  29890. * @param y defines the y coordinate of the origin (on-screen)
  29891. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  29892. * @param result defines the ray where to store the picking ray
  29893. * @param camera defines the camera to use for the picking
  29894. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  29895. * @returns the current scene
  29896. */
  29897. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  29898. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  29899. var engine = this._engine;
  29900. if (!camera) {
  29901. if (!this.activeCamera) {
  29902. throw new Error("Active camera not set");
  29903. }
  29904. camera = this.activeCamera;
  29905. }
  29906. var cameraViewport = camera.viewport;
  29907. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  29908. // Moving coordinates to local viewport world
  29909. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  29910. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  29911. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.IdentityReadOnly, cameraViewSpace ? BABYLON.Matrix.IdentityReadOnly : camera.getViewMatrix(), camera.getProjectionMatrix());
  29912. return this;
  29913. };
  29914. /**
  29915. * Creates a ray that can be used to pick in the scene
  29916. * @param x defines the x coordinate of the origin (on-screen)
  29917. * @param y defines the y coordinate of the origin (on-screen)
  29918. * @param camera defines the camera to use for the picking
  29919. * @returns a Ray
  29920. */
  29921. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  29922. var result = BABYLON.Ray.Zero();
  29923. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  29924. return result;
  29925. };
  29926. /**
  29927. * Creates a ray that can be used to pick in the scene
  29928. * @param x defines the x coordinate of the origin (on-screen)
  29929. * @param y defines the y coordinate of the origin (on-screen)
  29930. * @param result defines the ray where to store the picking ray
  29931. * @param camera defines the camera to use for the picking
  29932. * @returns the current scene
  29933. */
  29934. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  29935. if (!BABYLON.PickingInfo) {
  29936. return this;
  29937. }
  29938. var engine = this._engine;
  29939. if (!camera) {
  29940. if (!this.activeCamera) {
  29941. throw new Error("Active camera not set");
  29942. }
  29943. camera = this.activeCamera;
  29944. }
  29945. var cameraViewport = camera.viewport;
  29946. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  29947. var identity = BABYLON.Matrix.Identity();
  29948. // Moving coordinates to local viewport world
  29949. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  29950. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  29951. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  29952. return this;
  29953. };
  29954. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  29955. if (!BABYLON.PickingInfo) {
  29956. return null;
  29957. }
  29958. var pickingInfo = null;
  29959. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  29960. var mesh = this.meshes[meshIndex];
  29961. if (predicate) {
  29962. if (!predicate(mesh)) {
  29963. continue;
  29964. }
  29965. }
  29966. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  29967. continue;
  29968. }
  29969. var world = mesh.getWorldMatrix();
  29970. var ray = rayFunction(world);
  29971. var result = mesh.intersects(ray, fastCheck);
  29972. if (!result || !result.hit) {
  29973. continue;
  29974. }
  29975. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance) {
  29976. continue;
  29977. }
  29978. pickingInfo = result;
  29979. if (fastCheck) {
  29980. break;
  29981. }
  29982. }
  29983. return pickingInfo || new BABYLON.PickingInfo();
  29984. };
  29985. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  29986. if (!BABYLON.PickingInfo) {
  29987. return null;
  29988. }
  29989. var pickingInfos = new Array();
  29990. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  29991. var mesh = this.meshes[meshIndex];
  29992. if (predicate) {
  29993. if (!predicate(mesh)) {
  29994. continue;
  29995. }
  29996. }
  29997. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  29998. continue;
  29999. }
  30000. var world = mesh.getWorldMatrix();
  30001. var ray = rayFunction(world);
  30002. var result = mesh.intersects(ray, false);
  30003. if (!result || !result.hit) {
  30004. continue;
  30005. }
  30006. pickingInfos.push(result);
  30007. }
  30008. return pickingInfos;
  30009. };
  30010. /** Launch a ray to try to pick a mesh in the scene
  30011. * @param x position on screen
  30012. * @param y position on screen
  30013. * @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
  30014. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  30015. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  30016. * @returns a PickingInfo
  30017. */
  30018. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  30019. var _this = this;
  30020. if (!BABYLON.PickingInfo) {
  30021. return null;
  30022. }
  30023. var result = this._internalPick(function (world) {
  30024. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  30025. return _this._tempPickingRay;
  30026. }, predicate, fastCheck);
  30027. if (result) {
  30028. result.ray = this.createPickingRay(x, y, BABYLON.Matrix.Identity(), camera || null);
  30029. }
  30030. return result;
  30031. };
  30032. /** Use the given ray to pick a mesh in the scene
  30033. * @param ray The ray to use to pick meshes
  30034. * @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
  30035. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  30036. * @returns a PickingInfo
  30037. */
  30038. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  30039. var _this = this;
  30040. var result = this._internalPick(function (world) {
  30041. if (!_this._pickWithRayInverseMatrix) {
  30042. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  30043. }
  30044. world.invertToRef(_this._pickWithRayInverseMatrix);
  30045. if (!_this._cachedRayForTransform) {
  30046. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  30047. }
  30048. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  30049. return _this._cachedRayForTransform;
  30050. }, predicate, fastCheck);
  30051. if (result) {
  30052. result.ray = ray;
  30053. }
  30054. return result;
  30055. };
  30056. /**
  30057. * Launch a ray to try to pick a mesh in the scene
  30058. * @param x X position on screen
  30059. * @param y Y position on screen
  30060. * @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
  30061. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  30062. * @returns an array of PickingInfo
  30063. */
  30064. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  30065. var _this = this;
  30066. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  30067. };
  30068. /**
  30069. * Launch a ray to try to pick a mesh in the scene
  30070. * @param ray Ray to use
  30071. * @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
  30072. * @returns an array of PickingInfo
  30073. */
  30074. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  30075. var _this = this;
  30076. return this._internalMultiPick(function (world) {
  30077. if (!_this._pickWithRayInverseMatrix) {
  30078. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  30079. }
  30080. world.invertToRef(_this._pickWithRayInverseMatrix);
  30081. if (!_this._cachedRayForTransform) {
  30082. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  30083. }
  30084. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  30085. return _this._cachedRayForTransform;
  30086. }, predicate);
  30087. };
  30088. /**
  30089. * Force the value of meshUnderPointer
  30090. * @param mesh defines the mesh to use
  30091. */
  30092. Scene.prototype.setPointerOverMesh = function (mesh) {
  30093. if (this._pointerOverMesh === mesh) {
  30094. return;
  30095. }
  30096. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  30097. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  30098. }
  30099. this._pointerOverMesh = mesh;
  30100. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  30101. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  30102. }
  30103. };
  30104. /**
  30105. * Gets the mesh under the pointer
  30106. * @returns a Mesh or null if no mesh is under the pointer
  30107. */
  30108. Scene.prototype.getPointerOverMesh = function () {
  30109. return this._pointerOverMesh;
  30110. };
  30111. // Misc.
  30112. /** @hidden */
  30113. Scene.prototype._rebuildGeometries = function () {
  30114. for (var _i = 0, _a = this.geometries; _i < _a.length; _i++) {
  30115. var geometry = _a[_i];
  30116. geometry._rebuild();
  30117. }
  30118. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  30119. var mesh = _c[_b];
  30120. mesh._rebuild();
  30121. }
  30122. if (this.postProcessManager) {
  30123. this.postProcessManager._rebuild();
  30124. }
  30125. for (var _d = 0, _e = this._components; _d < _e.length; _d++) {
  30126. var component = _e[_d];
  30127. component.rebuild();
  30128. }
  30129. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  30130. var system = _g[_f];
  30131. system.rebuild();
  30132. }
  30133. };
  30134. /** @hidden */
  30135. Scene.prototype._rebuildTextures = function () {
  30136. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  30137. var texture = _a[_i];
  30138. texture._rebuild();
  30139. }
  30140. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30141. };
  30142. // Tags
  30143. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  30144. if (tagsQuery === undefined) {
  30145. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  30146. return list;
  30147. }
  30148. var listByTags = [];
  30149. forEach = forEach || (function (item) { return; });
  30150. for (var i in list) {
  30151. var item = list[i];
  30152. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  30153. listByTags.push(item);
  30154. forEach(item);
  30155. }
  30156. }
  30157. return listByTags;
  30158. };
  30159. /**
  30160. * Get a list of meshes by tags
  30161. * @param tagsQuery defines the tags query to use
  30162. * @param forEach defines a predicate used to filter results
  30163. * @returns an array of Mesh
  30164. */
  30165. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  30166. return this._getByTags(this.meshes, tagsQuery, forEach);
  30167. };
  30168. /**
  30169. * Get a list of cameras by tags
  30170. * @param tagsQuery defines the tags query to use
  30171. * @param forEach defines a predicate used to filter results
  30172. * @returns an array of Camera
  30173. */
  30174. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  30175. return this._getByTags(this.cameras, tagsQuery, forEach);
  30176. };
  30177. /**
  30178. * Get a list of lights by tags
  30179. * @param tagsQuery defines the tags query to use
  30180. * @param forEach defines a predicate used to filter results
  30181. * @returns an array of Light
  30182. */
  30183. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  30184. return this._getByTags(this.lights, tagsQuery, forEach);
  30185. };
  30186. /**
  30187. * Get a list of materials by tags
  30188. * @param tagsQuery defines the tags query to use
  30189. * @param forEach defines a predicate used to filter results
  30190. * @returns an array of Material
  30191. */
  30192. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  30193. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  30194. };
  30195. /**
  30196. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  30197. * This allowed control for front to back rendering or reversly depending of the special needs.
  30198. *
  30199. * @param renderingGroupId The rendering group id corresponding to its index
  30200. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  30201. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  30202. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  30203. */
  30204. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  30205. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  30206. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  30207. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  30208. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  30209. };
  30210. /**
  30211. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  30212. *
  30213. * @param renderingGroupId The rendering group id corresponding to its index
  30214. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  30215. * @param depth Automatically clears depth between groups if true and autoClear is true.
  30216. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  30217. */
  30218. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  30219. if (depth === void 0) { depth = true; }
  30220. if (stencil === void 0) { stencil = true; }
  30221. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  30222. };
  30223. /**
  30224. * Gets the current auto clear configuration for one rendering group of the rendering
  30225. * manager.
  30226. * @param index the rendering group index to get the information for
  30227. * @returns The auto clear setup for the requested rendering group
  30228. */
  30229. Scene.prototype.getAutoClearDepthStencilSetup = function (index) {
  30230. return this._renderingManager.getAutoClearDepthStencilSetup(index);
  30231. };
  30232. Object.defineProperty(Scene.prototype, "blockMaterialDirtyMechanism", {
  30233. /** Gets or sets a boolean blocking all the calls to markAllMaterialsAsDirty (ie. the materials won't be updated if they are out of sync) */
  30234. get: function () {
  30235. return this._blockMaterialDirtyMechanism;
  30236. },
  30237. set: function (value) {
  30238. if (this._blockMaterialDirtyMechanism === value) {
  30239. return;
  30240. }
  30241. this._blockMaterialDirtyMechanism = value;
  30242. if (!value) { // Do a complete update
  30243. this.markAllMaterialsAsDirty(BABYLON.Material.AllDirtyFlag);
  30244. }
  30245. },
  30246. enumerable: true,
  30247. configurable: true
  30248. });
  30249. /**
  30250. * Will flag all materials as dirty to trigger new shader compilation
  30251. * @param flag defines the flag used to specify which material part must be marked as dirty
  30252. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  30253. */
  30254. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  30255. if (this._blockMaterialDirtyMechanism) {
  30256. return;
  30257. }
  30258. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  30259. var material = _a[_i];
  30260. if (predicate && !predicate(material)) {
  30261. continue;
  30262. }
  30263. material.markAsDirty(flag);
  30264. }
  30265. };
  30266. /** @hidden */
  30267. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useOfflineSupport, useArrayBuffer, onError) {
  30268. var _this = this;
  30269. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useOfflineSupport ? this.offlineProvider : undefined, useArrayBuffer, onError);
  30270. this._activeRequests.push(request);
  30271. request.onCompleteObservable.add(function (request) {
  30272. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  30273. });
  30274. return request;
  30275. };
  30276. /** @hidden */
  30277. Scene.prototype._loadFileAsync = function (url, useOfflineSupport, useArrayBuffer) {
  30278. var _this = this;
  30279. return new Promise(function (resolve, reject) {
  30280. _this._loadFile(url, function (data) {
  30281. resolve(data);
  30282. }, undefined, useOfflineSupport, useArrayBuffer, function (request, exception) {
  30283. reject(exception);
  30284. });
  30285. });
  30286. };
  30287. // Statics
  30288. Scene._uniqueIdCounter = 0;
  30289. /** The fog is deactivated */
  30290. Scene.FOGMODE_NONE = 0;
  30291. /** The fog density is following an exponential function */
  30292. Scene.FOGMODE_EXP = 1;
  30293. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  30294. Scene.FOGMODE_EXP2 = 2;
  30295. /** The fog density is following a linear function. */
  30296. Scene.FOGMODE_LINEAR = 3;
  30297. /**
  30298. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  30299. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  30300. */
  30301. Scene.MinDeltaTime = 1.0;
  30302. /**
  30303. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  30304. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  30305. */
  30306. Scene.MaxDeltaTime = 1000.0;
  30307. /** The distance in pixel that you have to move to prevent some events */
  30308. Scene.DragMovementThreshold = 10; // in pixels
  30309. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  30310. Scene.LongPressDelay = 500; // in milliseconds
  30311. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  30312. Scene.DoubleClickDelay = 300; // in milliseconds
  30313. /** If you need to check double click without raising a single click at first click, enable this flag */
  30314. Scene.ExclusiveDoubleClickMode = false;
  30315. return Scene;
  30316. }(BABYLON.AbstractScene));
  30317. BABYLON.Scene = Scene;
  30318. })(BABYLON || (BABYLON = {}));
  30319. //# sourceMappingURL=babylon.scene.js.map
  30320. var BABYLON;
  30321. (function (BABYLON) {
  30322. /**
  30323. * Set of assets to keep when moving a scene into an asset container.
  30324. */
  30325. var KeepAssets = /** @class */ (function (_super) {
  30326. __extends(KeepAssets, _super);
  30327. function KeepAssets() {
  30328. return _super !== null && _super.apply(this, arguments) || this;
  30329. }
  30330. return KeepAssets;
  30331. }(BABYLON.AbstractScene));
  30332. BABYLON.KeepAssets = KeepAssets;
  30333. /**
  30334. * Container with a set of assets that can be added or removed from a scene.
  30335. */
  30336. var AssetContainer = /** @class */ (function (_super) {
  30337. __extends(AssetContainer, _super);
  30338. /**
  30339. * Instantiates an AssetContainer.
  30340. * @param scene The scene the AssetContainer belongs to.
  30341. */
  30342. function AssetContainer(scene) {
  30343. var _this = _super.call(this) || this;
  30344. _this.scene = scene;
  30345. _this["sounds"] = [];
  30346. _this["effectLayers"] = [];
  30347. _this["layers"] = [];
  30348. _this["lensFlareSystems"] = [];
  30349. _this["proceduralTextures"] = [];
  30350. return _this;
  30351. }
  30352. /**
  30353. * Adds all the assets from the container to the scene.
  30354. */
  30355. AssetContainer.prototype.addAllToScene = function () {
  30356. var _this = this;
  30357. this.cameras.forEach(function (o) {
  30358. _this.scene.addCamera(o);
  30359. });
  30360. this.lights.forEach(function (o) {
  30361. _this.scene.addLight(o);
  30362. });
  30363. this.meshes.forEach(function (o) {
  30364. _this.scene.addMesh(o);
  30365. });
  30366. this.skeletons.forEach(function (o) {
  30367. _this.scene.addSkeleton(o);
  30368. });
  30369. this.animations.forEach(function (o) {
  30370. _this.scene.addAnimation(o);
  30371. });
  30372. this.animationGroups.forEach(function (o) {
  30373. _this.scene.addAnimationGroup(o);
  30374. });
  30375. this.multiMaterials.forEach(function (o) {
  30376. _this.scene.addMultiMaterial(o);
  30377. });
  30378. this.materials.forEach(function (o) {
  30379. _this.scene.addMaterial(o);
  30380. });
  30381. this.morphTargetManagers.forEach(function (o) {
  30382. _this.scene.addMorphTargetManager(o);
  30383. });
  30384. this.geometries.forEach(function (o) {
  30385. _this.scene.addGeometry(o);
  30386. });
  30387. this.transformNodes.forEach(function (o) {
  30388. _this.scene.addTransformNode(o);
  30389. });
  30390. this.actionManagers.forEach(function (o) {
  30391. _this.scene.addActionManager(o);
  30392. });
  30393. this.textures.forEach(function (o) {
  30394. _this.scene.addTexture(o);
  30395. });
  30396. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  30397. var component = _a[_i];
  30398. component.addFromContainer(this);
  30399. }
  30400. };
  30401. /**
  30402. * Removes all the assets in the container from the scene
  30403. */
  30404. AssetContainer.prototype.removeAllFromScene = function () {
  30405. var _this = this;
  30406. this.cameras.forEach(function (o) {
  30407. _this.scene.removeCamera(o);
  30408. });
  30409. this.lights.forEach(function (o) {
  30410. _this.scene.removeLight(o);
  30411. });
  30412. this.meshes.forEach(function (o) {
  30413. _this.scene.removeMesh(o);
  30414. });
  30415. this.skeletons.forEach(function (o) {
  30416. _this.scene.removeSkeleton(o);
  30417. });
  30418. this.animations.forEach(function (o) {
  30419. _this.scene.removeAnimation(o);
  30420. });
  30421. this.animationGroups.forEach(function (o) {
  30422. _this.scene.removeAnimationGroup(o);
  30423. });
  30424. this.multiMaterials.forEach(function (o) {
  30425. _this.scene.removeMultiMaterial(o);
  30426. });
  30427. this.materials.forEach(function (o) {
  30428. _this.scene.removeMaterial(o);
  30429. });
  30430. this.morphTargetManagers.forEach(function (o) {
  30431. _this.scene.removeMorphTargetManager(o);
  30432. });
  30433. this.geometries.forEach(function (o) {
  30434. _this.scene.removeGeometry(o);
  30435. });
  30436. this.transformNodes.forEach(function (o) {
  30437. _this.scene.removeTransformNode(o);
  30438. });
  30439. this.actionManagers.forEach(function (o) {
  30440. _this.scene.removeActionManager(o);
  30441. });
  30442. this.textures.forEach(function (o) {
  30443. _this.scene.removeTexture(o);
  30444. });
  30445. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  30446. var component = _a[_i];
  30447. component.removeFromContainer(this);
  30448. }
  30449. };
  30450. /**
  30451. * Disposes all the assets in the container
  30452. */
  30453. AssetContainer.prototype.dispose = function () {
  30454. this.cameras.forEach(function (o) {
  30455. o.dispose();
  30456. });
  30457. this.lights.forEach(function (o) {
  30458. o.dispose();
  30459. });
  30460. this.meshes.forEach(function (o) {
  30461. o.dispose();
  30462. });
  30463. this.skeletons.forEach(function (o) {
  30464. o.dispose();
  30465. });
  30466. this.animationGroups.forEach(function (o) {
  30467. o.dispose();
  30468. });
  30469. this.multiMaterials.forEach(function (o) {
  30470. o.dispose();
  30471. });
  30472. this.materials.forEach(function (o) {
  30473. o.dispose();
  30474. });
  30475. this.geometries.forEach(function (o) {
  30476. o.dispose();
  30477. });
  30478. this.transformNodes.forEach(function (o) {
  30479. o.dispose();
  30480. });
  30481. this.actionManagers.forEach(function (o) {
  30482. o.dispose();
  30483. });
  30484. this.textures.forEach(function (o) {
  30485. o.dispose();
  30486. });
  30487. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  30488. var component = _a[_i];
  30489. component.dispose();
  30490. }
  30491. };
  30492. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  30493. if (!sourceAssets) {
  30494. return;
  30495. }
  30496. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  30497. var asset = sourceAssets_1[_i];
  30498. var move = true;
  30499. if (keepAssets) {
  30500. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  30501. var keepAsset = keepAssets_1[_a];
  30502. if (asset === keepAsset) {
  30503. move = false;
  30504. break;
  30505. }
  30506. }
  30507. }
  30508. if (move) {
  30509. targetAssets.push(asset);
  30510. }
  30511. }
  30512. };
  30513. /**
  30514. * Removes all the assets contained in the scene and adds them to the container.
  30515. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  30516. */
  30517. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  30518. if (keepAssets === undefined) {
  30519. keepAssets = new KeepAssets();
  30520. }
  30521. for (var key in this) {
  30522. if (this.hasOwnProperty(key)) {
  30523. this[key] = this[key] || [];
  30524. this._moveAssets(this.scene[key], this[key], keepAssets[key]);
  30525. }
  30526. }
  30527. this.removeAllFromScene();
  30528. };
  30529. /**
  30530. * 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.
  30531. * @returns the root mesh
  30532. */
  30533. AssetContainer.prototype.createRootMesh = function () {
  30534. var rootMesh = new BABYLON.Mesh("assetContainerRootMesh", this.scene);
  30535. this.meshes.forEach(function (m) {
  30536. if (!m.parent) {
  30537. rootMesh.addChild(m);
  30538. }
  30539. });
  30540. this.meshes.unshift(rootMesh);
  30541. return rootMesh;
  30542. };
  30543. return AssetContainer;
  30544. }(BABYLON.AbstractScene));
  30545. BABYLON.AssetContainer = AssetContainer;
  30546. })(BABYLON || (BABYLON = {}));
  30547. //# sourceMappingURL=babylon.assetContainer.js.map
  30548. var BABYLON;
  30549. (function (BABYLON) {
  30550. /**
  30551. * Class used to store data that will be store in GPU memory
  30552. */
  30553. var Buffer = /** @class */ (function () {
  30554. /**
  30555. * Constructor
  30556. * @param engine the engine
  30557. * @param data the data to use for this buffer
  30558. * @param updatable whether the data is updatable
  30559. * @param stride the stride (optional)
  30560. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  30561. * @param instanced whether the buffer is instanced (optional)
  30562. * @param useBytes set to true if the stride in in bytes (optional)
  30563. */
  30564. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  30565. if (stride === void 0) { stride = 0; }
  30566. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  30567. if (instanced === void 0) { instanced = false; }
  30568. if (useBytes === void 0) { useBytes = false; }
  30569. if (engine instanceof BABYLON.Mesh) { // old versions of BABYLON.VertexBuffer accepted 'mesh' instead of 'engine'
  30570. this._engine = engine.getScene().getEngine();
  30571. }
  30572. else {
  30573. this._engine = engine;
  30574. }
  30575. this._updatable = updatable;
  30576. this._instanced = instanced;
  30577. this._data = data;
  30578. this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
  30579. if (!postponeInternalCreation) { // by default
  30580. this.create();
  30581. }
  30582. }
  30583. /**
  30584. * Create a new VertexBuffer based on the current buffer
  30585. * @param kind defines the vertex buffer kind (position, normal, etc.)
  30586. * @param offset defines offset in the buffer (0 by default)
  30587. * @param size defines the size in floats of attributes (position is 3 for instance)
  30588. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  30589. * @param instanced defines if the vertex buffer contains indexed data
  30590. * @param useBytes defines if the offset and stride are in bytes
  30591. * @returns the new vertex buffer
  30592. */
  30593. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  30594. if (useBytes === void 0) { useBytes = false; }
  30595. var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
  30596. var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
  30597. // a lot of these parameters are ignored as they are overriden by the buffer
  30598. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  30599. };
  30600. // Properties
  30601. /**
  30602. * Gets a boolean indicating if the Buffer is updatable?
  30603. * @returns true if the buffer is updatable
  30604. */
  30605. Buffer.prototype.isUpdatable = function () {
  30606. return this._updatable;
  30607. };
  30608. /**
  30609. * Gets current buffer's data
  30610. * @returns a DataArray or null
  30611. */
  30612. Buffer.prototype.getData = function () {
  30613. return this._data;
  30614. };
  30615. /**
  30616. * Gets underlying native buffer
  30617. * @returns underlying native buffer
  30618. */
  30619. Buffer.prototype.getBuffer = function () {
  30620. return this._buffer;
  30621. };
  30622. /**
  30623. * Gets the stride in float32 units (i.e. byte stride / 4).
  30624. * May not be an integer if the byte stride is not divisible by 4.
  30625. * DEPRECATED. Use byteStride instead.
  30626. * @returns the stride in float32 units
  30627. */
  30628. Buffer.prototype.getStrideSize = function () {
  30629. return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
  30630. };
  30631. // Methods
  30632. /**
  30633. * Store data into the buffer. If the buffer was already used it will be either recreated or updated depending on isUpdatable property
  30634. * @param data defines the data to store
  30635. */
  30636. Buffer.prototype.create = function (data) {
  30637. if (data === void 0) { data = null; }
  30638. if (!data && this._buffer) {
  30639. return; // nothing to do
  30640. }
  30641. data = data || this._data;
  30642. if (!data) {
  30643. return;
  30644. }
  30645. if (!this._buffer) { // create buffer
  30646. if (this._updatable) {
  30647. this._buffer = this._engine.createDynamicVertexBuffer(data);
  30648. this._data = data;
  30649. }
  30650. else {
  30651. this._buffer = this._engine.createVertexBuffer(data);
  30652. }
  30653. }
  30654. else if (this._updatable) { // update buffer
  30655. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  30656. this._data = data;
  30657. }
  30658. };
  30659. /** @hidden */
  30660. Buffer.prototype._rebuild = function () {
  30661. this._buffer = null;
  30662. this.create(this._data);
  30663. };
  30664. /**
  30665. * Update current buffer data
  30666. * @param data defines the data to store
  30667. */
  30668. Buffer.prototype.update = function (data) {
  30669. this.create(data);
  30670. };
  30671. /**
  30672. * Updates the data directly.
  30673. * @param data the new data
  30674. * @param offset the new offset
  30675. * @param vertexCount the vertex count (optional)
  30676. * @param useBytes set to true if the offset is in bytes
  30677. */
  30678. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  30679. if (useBytes === void 0) { useBytes = false; }
  30680. if (!this._buffer) {
  30681. return;
  30682. }
  30683. if (this._updatable) { // update buffer
  30684. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));
  30685. this._data = null;
  30686. }
  30687. };
  30688. /**
  30689. * Release all resources
  30690. */
  30691. Buffer.prototype.dispose = function () {
  30692. if (!this._buffer) {
  30693. return;
  30694. }
  30695. if (this._engine._releaseBuffer(this._buffer)) {
  30696. this._buffer = null;
  30697. }
  30698. };
  30699. return Buffer;
  30700. }());
  30701. BABYLON.Buffer = Buffer;
  30702. })(BABYLON || (BABYLON = {}));
  30703. //# sourceMappingURL=babylon.buffer.js.map
  30704. var BABYLON;
  30705. (function (BABYLON) {
  30706. /**
  30707. * Specialized buffer used to store vertex data
  30708. */
  30709. var VertexBuffer = /** @class */ (function () {
  30710. /**
  30711. * Constructor
  30712. * @param engine the engine
  30713. * @param data the data to use for this vertex buffer
  30714. * @param kind the vertex buffer kind
  30715. * @param updatable whether the data is updatable
  30716. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  30717. * @param stride the stride (optional)
  30718. * @param instanced whether the buffer is instanced (optional)
  30719. * @param offset the offset of the data (optional)
  30720. * @param size the number of components (optional)
  30721. * @param type the type of the component (optional)
  30722. * @param normalized whether the data contains normalized data (optional)
  30723. * @param useBytes set to true if stride and offset are in bytes (optional)
  30724. */
  30725. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  30726. if (normalized === void 0) { normalized = false; }
  30727. if (useBytes === void 0) { useBytes = false; }
  30728. if (data instanceof BABYLON.Buffer) {
  30729. this._buffer = data;
  30730. this._ownsBuffer = false;
  30731. }
  30732. else {
  30733. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  30734. this._ownsBuffer = true;
  30735. }
  30736. this._kind = kind;
  30737. if (type == undefined) {
  30738. var data_1 = this.getData();
  30739. this.type = VertexBuffer.FLOAT;
  30740. if (data_1 instanceof Int8Array) {
  30741. this.type = VertexBuffer.BYTE;
  30742. }
  30743. else if (data_1 instanceof Uint8Array) {
  30744. this.type = VertexBuffer.UNSIGNED_BYTE;
  30745. }
  30746. else if (data_1 instanceof Int16Array) {
  30747. this.type = VertexBuffer.SHORT;
  30748. }
  30749. else if (data_1 instanceof Uint16Array) {
  30750. this.type = VertexBuffer.UNSIGNED_SHORT;
  30751. }
  30752. else if (data_1 instanceof Int32Array) {
  30753. this.type = VertexBuffer.INT;
  30754. }
  30755. else if (data_1 instanceof Uint32Array) {
  30756. this.type = VertexBuffer.UNSIGNED_INT;
  30757. }
  30758. }
  30759. else {
  30760. this.type = type;
  30761. }
  30762. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  30763. if (useBytes) {
  30764. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  30765. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  30766. this.byteOffset = offset || 0;
  30767. }
  30768. else {
  30769. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  30770. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  30771. this.byteOffset = (offset || 0) * typeByteLength;
  30772. }
  30773. this.normalized = normalized;
  30774. this._instanced = instanced !== undefined ? instanced : false;
  30775. this._instanceDivisor = instanced ? 1 : 0;
  30776. }
  30777. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  30778. /**
  30779. * Gets or sets the instance divisor when in instanced mode
  30780. */
  30781. get: function () {
  30782. return this._instanceDivisor;
  30783. },
  30784. set: function (value) {
  30785. this._instanceDivisor = value;
  30786. if (value == 0) {
  30787. this._instanced = false;
  30788. }
  30789. else {
  30790. this._instanced = true;
  30791. }
  30792. },
  30793. enumerable: true,
  30794. configurable: true
  30795. });
  30796. /** @hidden */
  30797. VertexBuffer.prototype._rebuild = function () {
  30798. if (!this._buffer) {
  30799. return;
  30800. }
  30801. this._buffer._rebuild();
  30802. };
  30803. /**
  30804. * Returns the kind of the VertexBuffer (string)
  30805. * @returns a string
  30806. */
  30807. VertexBuffer.prototype.getKind = function () {
  30808. return this._kind;
  30809. };
  30810. // Properties
  30811. /**
  30812. * Gets a boolean indicating if the VertexBuffer is updatable?
  30813. * @returns true if the buffer is updatable
  30814. */
  30815. VertexBuffer.prototype.isUpdatable = function () {
  30816. return this._buffer.isUpdatable();
  30817. };
  30818. /**
  30819. * Gets current buffer's data
  30820. * @returns a DataArray or null
  30821. */
  30822. VertexBuffer.prototype.getData = function () {
  30823. return this._buffer.getData();
  30824. };
  30825. /**
  30826. * Gets underlying native buffer
  30827. * @returns underlying native buffer
  30828. */
  30829. VertexBuffer.prototype.getBuffer = function () {
  30830. return this._buffer.getBuffer();
  30831. };
  30832. /**
  30833. * Gets the stride in float32 units (i.e. byte stride / 4).
  30834. * May not be an integer if the byte stride is not divisible by 4.
  30835. * DEPRECATED. Use byteStride instead.
  30836. * @returns the stride in float32 units
  30837. */
  30838. VertexBuffer.prototype.getStrideSize = function () {
  30839. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  30840. };
  30841. /**
  30842. * Returns the offset as a multiple of the type byte length.
  30843. * DEPRECATED. Use byteOffset instead.
  30844. * @returns the offset in bytes
  30845. */
  30846. VertexBuffer.prototype.getOffset = function () {
  30847. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  30848. };
  30849. /**
  30850. * Returns the number of components per vertex attribute (integer)
  30851. * @returns the size in float
  30852. */
  30853. VertexBuffer.prototype.getSize = function () {
  30854. return this._size;
  30855. };
  30856. /**
  30857. * Gets a boolean indicating is the internal buffer of the VertexBuffer is instanced
  30858. * @returns true if this buffer is instanced
  30859. */
  30860. VertexBuffer.prototype.getIsInstanced = function () {
  30861. return this._instanced;
  30862. };
  30863. /**
  30864. * Returns the instancing divisor, zero for non-instanced (integer).
  30865. * @returns a number
  30866. */
  30867. VertexBuffer.prototype.getInstanceDivisor = function () {
  30868. return this._instanceDivisor;
  30869. };
  30870. // Methods
  30871. /**
  30872. * Store data into the buffer. If the buffer was already used it will be either recreated or updated depending on isUpdatable property
  30873. * @param data defines the data to store
  30874. */
  30875. VertexBuffer.prototype.create = function (data) {
  30876. this._buffer.create(data);
  30877. };
  30878. /**
  30879. * Updates the underlying buffer according to the passed numeric array or Float32Array.
  30880. * This function will create a new buffer if the current one is not updatable
  30881. * @param data defines the data to store
  30882. */
  30883. VertexBuffer.prototype.update = function (data) {
  30884. this._buffer.update(data);
  30885. };
  30886. /**
  30887. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  30888. * Returns the directly updated WebGLBuffer.
  30889. * @param data the new data
  30890. * @param offset the new offset
  30891. * @param useBytes set to true if the offset is in bytes
  30892. */
  30893. VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) {
  30894. if (useBytes === void 0) { useBytes = false; }
  30895. this._buffer.updateDirectly(data, offset, undefined, useBytes);
  30896. };
  30897. /**
  30898. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  30899. */
  30900. VertexBuffer.prototype.dispose = function () {
  30901. if (this._ownsBuffer) {
  30902. this._buffer.dispose();
  30903. }
  30904. };
  30905. /**
  30906. * Enumerates each value of this vertex buffer as numbers.
  30907. * @param count the number of values to enumerate
  30908. * @param callback the callback function called for each value
  30909. */
  30910. VertexBuffer.prototype.forEach = function (count, callback) {
  30911. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  30912. };
  30913. /**
  30914. * Deduces the stride given a kind.
  30915. * @param kind The kind string to deduce
  30916. * @returns The deduced stride
  30917. */
  30918. VertexBuffer.DeduceStride = function (kind) {
  30919. switch (kind) {
  30920. case VertexBuffer.UVKind:
  30921. case VertexBuffer.UV2Kind:
  30922. case VertexBuffer.UV3Kind:
  30923. case VertexBuffer.UV4Kind:
  30924. case VertexBuffer.UV5Kind:
  30925. case VertexBuffer.UV6Kind:
  30926. return 2;
  30927. case VertexBuffer.NormalKind:
  30928. case VertexBuffer.PositionKind:
  30929. return 3;
  30930. case VertexBuffer.ColorKind:
  30931. case VertexBuffer.MatricesIndicesKind:
  30932. case VertexBuffer.MatricesIndicesExtraKind:
  30933. case VertexBuffer.MatricesWeightsKind:
  30934. case VertexBuffer.MatricesWeightsExtraKind:
  30935. case VertexBuffer.TangentKind:
  30936. return 4;
  30937. default:
  30938. throw new Error("Invalid kind '" + kind + "'");
  30939. }
  30940. };
  30941. /**
  30942. * Gets the byte length of the given type.
  30943. * @param type the type
  30944. * @returns the number of bytes
  30945. */
  30946. VertexBuffer.GetTypeByteLength = function (type) {
  30947. switch (type) {
  30948. case VertexBuffer.BYTE:
  30949. case VertexBuffer.UNSIGNED_BYTE:
  30950. return 1;
  30951. case VertexBuffer.SHORT:
  30952. case VertexBuffer.UNSIGNED_SHORT:
  30953. return 2;
  30954. case VertexBuffer.INT:
  30955. case VertexBuffer.FLOAT:
  30956. return 4;
  30957. default:
  30958. throw new Error("Invalid type '" + type + "'");
  30959. }
  30960. };
  30961. /**
  30962. * Enumerates each value of the given parameters as numbers.
  30963. * @param data the data to enumerate
  30964. * @param byteOffset the byte offset of the data
  30965. * @param byteStride the byte stride of the data
  30966. * @param componentCount the number of components per element
  30967. * @param componentType the type of the component
  30968. * @param count the total number of components
  30969. * @param normalized whether the data is normalized
  30970. * @param callback the callback function called for each value
  30971. */
  30972. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  30973. if (data instanceof Array) {
  30974. var offset = byteOffset / 4;
  30975. var stride = byteStride / 4;
  30976. for (var index = 0; index < count; index += componentCount) {
  30977. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  30978. callback(data[offset + componentIndex], index + componentIndex);
  30979. }
  30980. offset += stride;
  30981. }
  30982. }
  30983. else {
  30984. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  30985. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  30986. for (var index = 0; index < count; index += componentCount) {
  30987. var componentByteOffset = byteOffset;
  30988. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  30989. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  30990. callback(value, index + componentIndex);
  30991. componentByteOffset += componentByteLength;
  30992. }
  30993. byteOffset += byteStride;
  30994. }
  30995. }
  30996. };
  30997. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  30998. switch (type) {
  30999. case VertexBuffer.BYTE: {
  31000. var value = dataView.getInt8(byteOffset);
  31001. if (normalized) {
  31002. value = Math.max(value / 127, -1);
  31003. }
  31004. return value;
  31005. }
  31006. case VertexBuffer.UNSIGNED_BYTE: {
  31007. var value = dataView.getUint8(byteOffset);
  31008. if (normalized) {
  31009. value = value / 255;
  31010. }
  31011. return value;
  31012. }
  31013. case VertexBuffer.SHORT: {
  31014. var value = dataView.getInt16(byteOffset, true);
  31015. if (normalized) {
  31016. value = Math.max(value / 16383, -1);
  31017. }
  31018. return value;
  31019. }
  31020. case VertexBuffer.UNSIGNED_SHORT: {
  31021. var value = dataView.getUint16(byteOffset, true);
  31022. if (normalized) {
  31023. value = value / 65535;
  31024. }
  31025. return value;
  31026. }
  31027. case VertexBuffer.FLOAT: {
  31028. return dataView.getFloat32(byteOffset, true);
  31029. }
  31030. default: {
  31031. throw new Error("Invalid component type " + type);
  31032. }
  31033. }
  31034. };
  31035. /**
  31036. * The byte type.
  31037. */
  31038. VertexBuffer.BYTE = 5120;
  31039. /**
  31040. * The unsigned byte type.
  31041. */
  31042. VertexBuffer.UNSIGNED_BYTE = 5121;
  31043. /**
  31044. * The short type.
  31045. */
  31046. VertexBuffer.SHORT = 5122;
  31047. /**
  31048. * The unsigned short type.
  31049. */
  31050. VertexBuffer.UNSIGNED_SHORT = 5123;
  31051. /**
  31052. * The integer type.
  31053. */
  31054. VertexBuffer.INT = 5124;
  31055. /**
  31056. * The unsigned integer type.
  31057. */
  31058. VertexBuffer.UNSIGNED_INT = 5125;
  31059. /**
  31060. * The float type.
  31061. */
  31062. VertexBuffer.FLOAT = 5126;
  31063. // Enums
  31064. /**
  31065. * Positions
  31066. */
  31067. VertexBuffer.PositionKind = "position";
  31068. /**
  31069. * Normals
  31070. */
  31071. VertexBuffer.NormalKind = "normal";
  31072. /**
  31073. * Tangents
  31074. */
  31075. VertexBuffer.TangentKind = "tangent";
  31076. /**
  31077. * Texture coordinates
  31078. */
  31079. VertexBuffer.UVKind = "uv";
  31080. /**
  31081. * Texture coordinates 2
  31082. */
  31083. VertexBuffer.UV2Kind = "uv2";
  31084. /**
  31085. * Texture coordinates 3
  31086. */
  31087. VertexBuffer.UV3Kind = "uv3";
  31088. /**
  31089. * Texture coordinates 4
  31090. */
  31091. VertexBuffer.UV4Kind = "uv4";
  31092. /**
  31093. * Texture coordinates 5
  31094. */
  31095. VertexBuffer.UV5Kind = "uv5";
  31096. /**
  31097. * Texture coordinates 6
  31098. */
  31099. VertexBuffer.UV6Kind = "uv6";
  31100. /**
  31101. * Colors
  31102. */
  31103. VertexBuffer.ColorKind = "color";
  31104. /**
  31105. * Matrix indices (for bones)
  31106. */
  31107. VertexBuffer.MatricesIndicesKind = "matricesIndices";
  31108. /**
  31109. * Matrix weights (for bones)
  31110. */
  31111. VertexBuffer.MatricesWeightsKind = "matricesWeights";
  31112. /**
  31113. * Additional matrix indices (for bones)
  31114. */
  31115. VertexBuffer.MatricesIndicesExtraKind = "matricesIndicesExtra";
  31116. /**
  31117. * Additional matrix weights (for bones)
  31118. */
  31119. VertexBuffer.MatricesWeightsExtraKind = "matricesWeightsExtra";
  31120. return VertexBuffer;
  31121. }());
  31122. BABYLON.VertexBuffer = VertexBuffer;
  31123. })(BABYLON || (BABYLON = {}));
  31124. //# sourceMappingURL=babylon.vertexBuffer.js.map
  31125. //# sourceMappingURL=babylon.internalTextureLoader.js.map
  31126. var BABYLON;
  31127. (function (BABYLON) {
  31128. /**
  31129. * Internal class used by the engine to get list of InternalTexture already bound to the GL context
  31130. */
  31131. var DummyInternalTextureTracker = /** @class */ (function () {
  31132. function DummyInternalTextureTracker() {
  31133. /**
  31134. * Gets or set the previous tracker in the list
  31135. */
  31136. this.previous = null;
  31137. /**
  31138. * Gets or set the next tracker in the list
  31139. */
  31140. this.next = null;
  31141. }
  31142. return DummyInternalTextureTracker;
  31143. }());
  31144. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  31145. })(BABYLON || (BABYLON = {}));
  31146. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  31147. var BABYLON;
  31148. (function (BABYLON) {
  31149. /**
  31150. * Class used to store data associated with WebGL texture data for the engine
  31151. * This class should not be used directly
  31152. */
  31153. var InternalTexture = /** @class */ (function () {
  31154. /**
  31155. * Creates a new InternalTexture
  31156. * @param engine defines the engine to use
  31157. * @param dataSource defines the type of data that will be used
  31158. * @param delayAllocation if the texture allocation should be delayed (default: false)
  31159. */
  31160. function InternalTexture(engine, dataSource, delayAllocation) {
  31161. if (delayAllocation === void 0) { delayAllocation = false; }
  31162. /**
  31163. * Observable called when the texture is loaded
  31164. */
  31165. this.onLoadedObservable = new BABYLON.Observable();
  31166. /**
  31167. * Gets or set the previous tracker in the list
  31168. */
  31169. this.previous = null;
  31170. /**
  31171. * Gets or set the next tracker in the list
  31172. */
  31173. this.next = null;
  31174. // Private
  31175. /** @hidden */
  31176. this._initialSlot = -1;
  31177. /** @hidden */
  31178. this._designatedSlot = -1;
  31179. /** @hidden */
  31180. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  31181. /** @hidden */
  31182. this._comparisonFunction = 0;
  31183. /** @hidden */
  31184. this._sphericalPolynomial = null;
  31185. /** @hidden */
  31186. this._lodGenerationScale = 0;
  31187. /** @hidden */
  31188. this._lodGenerationOffset = 0;
  31189. /** @hidden */
  31190. this._isRGBD = false;
  31191. /** @hidden */
  31192. this._references = 1;
  31193. this._engine = engine;
  31194. this._dataSource = dataSource;
  31195. if (!delayAllocation) {
  31196. this._webGLTexture = engine._createTexture();
  31197. }
  31198. }
  31199. /**
  31200. * Gets the Engine the texture belongs to.
  31201. * @returns The babylon engine
  31202. */
  31203. InternalTexture.prototype.getEngine = function () {
  31204. return this._engine;
  31205. };
  31206. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  31207. /**
  31208. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  31209. */
  31210. get: function () {
  31211. return this._dataSource;
  31212. },
  31213. enumerable: true,
  31214. configurable: true
  31215. });
  31216. /**
  31217. * Increments the number of references (ie. the number of Texture that point to it)
  31218. */
  31219. InternalTexture.prototype.incrementReferences = function () {
  31220. this._references++;
  31221. };
  31222. /**
  31223. * Change the size of the texture (not the size of the content)
  31224. * @param width defines the new width
  31225. * @param height defines the new height
  31226. * @param depth defines the new depth (1 by default)
  31227. */
  31228. InternalTexture.prototype.updateSize = function (width, height, depth) {
  31229. if (depth === void 0) { depth = 1; }
  31230. this.width = width;
  31231. this.height = height;
  31232. this.depth = depth;
  31233. this.baseWidth = width;
  31234. this.baseHeight = height;
  31235. this.baseDepth = depth;
  31236. this._size = width * height * depth;
  31237. };
  31238. /** @hidden */
  31239. InternalTexture.prototype._rebuild = function () {
  31240. var _this = this;
  31241. var proxy;
  31242. this.isReady = false;
  31243. this._cachedCoordinatesMode = null;
  31244. this._cachedWrapU = null;
  31245. this._cachedWrapV = null;
  31246. this._cachedAnisotropicFilteringLevel = null;
  31247. switch (this._dataSource) {
  31248. case InternalTexture.DATASOURCE_TEMP:
  31249. return;
  31250. case InternalTexture.DATASOURCE_URL:
  31251. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  31252. proxy._swapAndDie(_this);
  31253. _this.isReady = true;
  31254. }, null, this._buffer, undefined, this.format);
  31255. return;
  31256. case InternalTexture.DATASOURCE_RAW:
  31257. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  31258. proxy._swapAndDie(this);
  31259. this.isReady = true;
  31260. return;
  31261. case InternalTexture.DATASOURCE_RAW3D:
  31262. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  31263. proxy._swapAndDie(this);
  31264. this.isReady = true;
  31265. return;
  31266. case InternalTexture.DATASOURCE_DYNAMIC:
  31267. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  31268. proxy._swapAndDie(this);
  31269. this._engine.updateDynamicTexture(this, this._engine.getRenderingCanvas(), this.invertY, undefined, undefined, true);
  31270. // The engine will make sure to update content so no need to flag it as isReady = true
  31271. return;
  31272. case InternalTexture.DATASOURCE_RENDERTARGET:
  31273. var options = new BABYLON.RenderTargetCreationOptions();
  31274. options.generateDepthBuffer = this._generateDepthBuffer;
  31275. options.generateMipMaps = this.generateMipMaps;
  31276. options.generateStencilBuffer = this._generateStencilBuffer;
  31277. options.samplingMode = this.samplingMode;
  31278. options.type = this.type;
  31279. if (this.isCube) {
  31280. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  31281. }
  31282. else {
  31283. var size = {
  31284. width: this.width,
  31285. height: this.height
  31286. };
  31287. proxy = this._engine.createRenderTargetTexture(size, options);
  31288. }
  31289. proxy._swapAndDie(this);
  31290. this.isReady = true;
  31291. return;
  31292. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  31293. var depthTextureOptions = {
  31294. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  31295. comparisonFunction: this._comparisonFunction,
  31296. generateStencil: this._generateStencilBuffer,
  31297. isCube: this.isCube
  31298. };
  31299. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  31300. proxy._swapAndDie(this);
  31301. this.isReady = true;
  31302. return;
  31303. case InternalTexture.DATASOURCE_CUBE:
  31304. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  31305. proxy._swapAndDie(_this);
  31306. _this.isReady = true;
  31307. }, null, this.format, this._extension);
  31308. return;
  31309. case InternalTexture.DATASOURCE_CUBERAW:
  31310. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  31311. proxy._swapAndDie(this);
  31312. this.isReady = true;
  31313. return;
  31314. case InternalTexture.DATASOURCE_CUBERAW_RGBD:
  31315. proxy = this._engine.createRawCubeTexture(null, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  31316. BABYLON.RawCubeTexture._UpdateRGBDAsync(proxy, this._bufferViewArrayArray, this._sphericalPolynomial, this._lodGenerationScale, this._lodGenerationOffset).then(function () {
  31317. proxy._swapAndDie(_this);
  31318. _this.isReady = true;
  31319. });
  31320. return;
  31321. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  31322. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  31323. if (proxy) {
  31324. proxy._swapAndDie(_this);
  31325. }
  31326. _this.isReady = true;
  31327. }, null, this.format, this._extension);
  31328. proxy._sphericalPolynomial = this._sphericalPolynomial;
  31329. return;
  31330. }
  31331. };
  31332. /** @hidden */
  31333. InternalTexture.prototype._swapAndDie = function (target) {
  31334. target._webGLTexture = this._webGLTexture;
  31335. if (this._framebuffer) {
  31336. target._framebuffer = this._framebuffer;
  31337. }
  31338. if (this._depthStencilBuffer) {
  31339. target._depthStencilBuffer = this._depthStencilBuffer;
  31340. }
  31341. if (this._lodTextureHigh) {
  31342. if (target._lodTextureHigh) {
  31343. target._lodTextureHigh.dispose();
  31344. }
  31345. target._lodTextureHigh = this._lodTextureHigh;
  31346. }
  31347. if (this._lodTextureMid) {
  31348. if (target._lodTextureMid) {
  31349. target._lodTextureMid.dispose();
  31350. }
  31351. target._lodTextureMid = this._lodTextureMid;
  31352. }
  31353. if (this._lodTextureLow) {
  31354. if (target._lodTextureLow) {
  31355. target._lodTextureLow.dispose();
  31356. }
  31357. target._lodTextureLow = this._lodTextureLow;
  31358. }
  31359. var cache = this._engine.getLoadedTexturesCache();
  31360. var index = cache.indexOf(this);
  31361. if (index !== -1) {
  31362. cache.splice(index, 1);
  31363. }
  31364. };
  31365. /**
  31366. * Dispose the current allocated resources
  31367. */
  31368. InternalTexture.prototype.dispose = function () {
  31369. if (!this._webGLTexture) {
  31370. return;
  31371. }
  31372. this._references--;
  31373. if (this._references === 0) {
  31374. this._engine._releaseTexture(this);
  31375. this._webGLTexture = null;
  31376. this.previous = null;
  31377. this.next = null;
  31378. }
  31379. };
  31380. /**
  31381. * The source of the texture data is unknown
  31382. */
  31383. InternalTexture.DATASOURCE_UNKNOWN = 0;
  31384. /**
  31385. * Texture data comes from an URL
  31386. */
  31387. InternalTexture.DATASOURCE_URL = 1;
  31388. /**
  31389. * Texture data is only used for temporary storage
  31390. */
  31391. InternalTexture.DATASOURCE_TEMP = 2;
  31392. /**
  31393. * Texture data comes from raw data (ArrayBuffer)
  31394. */
  31395. InternalTexture.DATASOURCE_RAW = 3;
  31396. /**
  31397. * Texture content is dynamic (video or dynamic texture)
  31398. */
  31399. InternalTexture.DATASOURCE_DYNAMIC = 4;
  31400. /**
  31401. * Texture content is generated by rendering to it
  31402. */
  31403. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  31404. /**
  31405. * Texture content is part of a multi render target process
  31406. */
  31407. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  31408. /**
  31409. * Texture data comes from a cube data file
  31410. */
  31411. InternalTexture.DATASOURCE_CUBE = 7;
  31412. /**
  31413. * Texture data comes from a raw cube data
  31414. */
  31415. InternalTexture.DATASOURCE_CUBERAW = 8;
  31416. /**
  31417. * Texture data come from a prefiltered cube data file
  31418. */
  31419. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  31420. /**
  31421. * Texture content is raw 3D data
  31422. */
  31423. InternalTexture.DATASOURCE_RAW3D = 10;
  31424. /**
  31425. * Texture content is a depth texture
  31426. */
  31427. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  31428. /**
  31429. * Texture data comes from a raw cube data encoded with RGBD
  31430. */
  31431. InternalTexture.DATASOURCE_CUBERAW_RGBD = 12;
  31432. return InternalTexture;
  31433. }());
  31434. BABYLON.InternalTexture = InternalTexture;
  31435. })(BABYLON || (BABYLON = {}));
  31436. //# sourceMappingURL=babylon.internalTexture.js.map
  31437. var BABYLON;
  31438. (function (BABYLON) {
  31439. /**
  31440. * Base class of all the textures in babylon.
  31441. * It groups all the common properties the materials, post process, lights... might need
  31442. * in order to make a correct use of the texture.
  31443. */
  31444. var BaseTexture = /** @class */ (function () {
  31445. /**
  31446. * Instantiates a new BaseTexture.
  31447. * Base class of all the textures in babylon.
  31448. * It groups all the common properties the materials, post process, lights... might need
  31449. * in order to make a correct use of the texture.
  31450. * @param scene Define the scene the texture blongs to
  31451. */
  31452. function BaseTexture(scene) {
  31453. /**
  31454. * Gets or sets an object used to store user defined information.
  31455. */
  31456. this.metadata = null;
  31457. this._hasAlpha = false;
  31458. /**
  31459. * Defines if the alpha value should be determined via the rgb values.
  31460. * If true the luminance of the pixel might be used to find the corresponding alpha value.
  31461. */
  31462. this.getAlphaFromRGB = false;
  31463. /**
  31464. * Intensity or strength of the texture.
  31465. * It is commonly used by materials to fine tune the intensity of the texture
  31466. */
  31467. this.level = 1;
  31468. /**
  31469. * Define the UV chanel to use starting from 0 and defaulting to 0.
  31470. * This is part of the texture as textures usually maps to one uv set.
  31471. */
  31472. this.coordinatesIndex = 0;
  31473. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  31474. /**
  31475. * | Value | Type | Description |
  31476. * | ----- | ------------------ | ----------- |
  31477. * | 0 | CLAMP_ADDRESSMODE | |
  31478. * | 1 | WRAP_ADDRESSMODE | |
  31479. * | 2 | MIRROR_ADDRESSMODE | |
  31480. */
  31481. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  31482. /**
  31483. * | Value | Type | Description |
  31484. * | ----- | ------------------ | ----------- |
  31485. * | 0 | CLAMP_ADDRESSMODE | |
  31486. * | 1 | WRAP_ADDRESSMODE | |
  31487. * | 2 | MIRROR_ADDRESSMODE | |
  31488. */
  31489. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  31490. /**
  31491. * | Value | Type | Description |
  31492. * | ----- | ------------------ | ----------- |
  31493. * | 0 | CLAMP_ADDRESSMODE | |
  31494. * | 1 | WRAP_ADDRESSMODE | |
  31495. * | 2 | MIRROR_ADDRESSMODE | |
  31496. */
  31497. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  31498. /**
  31499. * With compliant hardware and browser (supporting anisotropic filtering)
  31500. * this defines the level of anisotropic filtering in the texture.
  31501. * The higher the better but the slower. This defaults to 4 as it seems to be the best tradeoff.
  31502. */
  31503. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  31504. /**
  31505. * Define if the texture is a cube texture or if false a 2d texture.
  31506. */
  31507. this.isCube = false;
  31508. /**
  31509. * Define if the texture is a 3d texture (webgl 2) or if false a 2d texture.
  31510. */
  31511. this.is3D = false;
  31512. /**
  31513. * Define if the texture contains data in gamma space (most of the png/jpg aside bump).
  31514. * HDR texture are usually stored in linear space.
  31515. * This only impacts the PBR and Background materials
  31516. */
  31517. this.gammaSpace = true;
  31518. /**
  31519. * Is Z inverted in the texture (useful in a cube texture).
  31520. */
  31521. this.invertZ = false;
  31522. /**
  31523. * @hidden
  31524. */
  31525. this.lodLevelInAlpha = false;
  31526. /**
  31527. * Define if the texture is a render target.
  31528. */
  31529. this.isRenderTarget = false;
  31530. /**
  31531. * Define the list of animation attached to the texture.
  31532. */
  31533. this.animations = new Array();
  31534. /**
  31535. * An event triggered when the texture is disposed.
  31536. */
  31537. this.onDisposeObservable = new BABYLON.Observable();
  31538. /**
  31539. * Define the current state of the loading sequence when in delayed load mode.
  31540. */
  31541. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  31542. this._cachedSize = BABYLON.Size.Zero();
  31543. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  31544. if (this._scene) {
  31545. this._scene.textures.push(this);
  31546. this._scene.onNewTextureAddedObservable.notifyObservers(this);
  31547. this.uniqueId = this._scene.getUniqueId();
  31548. }
  31549. this._uid = null;
  31550. }
  31551. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  31552. get: function () {
  31553. return this._hasAlpha;
  31554. },
  31555. /**
  31556. * Define if the texture is having a usable alpha value (can be use for transparency or glossiness for instance).
  31557. */
  31558. set: function (value) {
  31559. if (this._hasAlpha === value) {
  31560. return;
  31561. }
  31562. this._hasAlpha = value;
  31563. if (this._scene) {
  31564. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  31565. }
  31566. },
  31567. enumerable: true,
  31568. configurable: true
  31569. });
  31570. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  31571. get: function () {
  31572. return this._coordinatesMode;
  31573. },
  31574. /**
  31575. * How a texture is mapped.
  31576. *
  31577. * | Value | Type | Description |
  31578. * | ----- | ----------------------------------- | ----------- |
  31579. * | 0 | EXPLICIT_MODE | |
  31580. * | 1 | SPHERICAL_MODE | |
  31581. * | 2 | PLANAR_MODE | |
  31582. * | 3 | CUBIC_MODE | |
  31583. * | 4 | PROJECTION_MODE | |
  31584. * | 5 | SKYBOX_MODE | |
  31585. * | 6 | INVCUBIC_MODE | |
  31586. * | 7 | EQUIRECTANGULAR_MODE | |
  31587. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  31588. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  31589. */
  31590. set: function (value) {
  31591. if (this._coordinatesMode === value) {
  31592. return;
  31593. }
  31594. this._coordinatesMode = value;
  31595. if (this._scene) {
  31596. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31597. }
  31598. },
  31599. enumerable: true,
  31600. configurable: true
  31601. });
  31602. Object.defineProperty(BaseTexture.prototype, "isRGBD", {
  31603. /**
  31604. * Gets whether or not the texture contains RGBD data.
  31605. */
  31606. get: function () {
  31607. return this._texture != null && this._texture._isRGBD;
  31608. },
  31609. enumerable: true,
  31610. configurable: true
  31611. });
  31612. Object.defineProperty(BaseTexture.prototype, "lodGenerationOffset", {
  31613. /**
  31614. * With prefiltered texture, defined the offset used during the prefiltering steps.
  31615. */
  31616. get: function () {
  31617. if (this._texture) {
  31618. return this._texture._lodGenerationOffset;
  31619. }
  31620. return 0.0;
  31621. },
  31622. set: function (value) {
  31623. if (this._texture) {
  31624. this._texture._lodGenerationOffset = value;
  31625. }
  31626. },
  31627. enumerable: true,
  31628. configurable: true
  31629. });
  31630. Object.defineProperty(BaseTexture.prototype, "lodGenerationScale", {
  31631. /**
  31632. * With prefiltered texture, defined the scale used during the prefiltering steps.
  31633. */
  31634. get: function () {
  31635. if (this._texture) {
  31636. return this._texture._lodGenerationScale;
  31637. }
  31638. return 0.0;
  31639. },
  31640. set: function (value) {
  31641. if (this._texture) {
  31642. this._texture._lodGenerationScale = value;
  31643. }
  31644. },
  31645. enumerable: true,
  31646. configurable: true
  31647. });
  31648. Object.defineProperty(BaseTexture.prototype, "uid", {
  31649. /**
  31650. * Define the unique id of the texture in the scene.
  31651. */
  31652. get: function () {
  31653. if (!this._uid) {
  31654. this._uid = BABYLON.Tools.RandomId();
  31655. }
  31656. return this._uid;
  31657. },
  31658. enumerable: true,
  31659. configurable: true
  31660. });
  31661. /**
  31662. * Return a string representation of the texture.
  31663. * @returns the texture as a string
  31664. */
  31665. BaseTexture.prototype.toString = function () {
  31666. return this.name;
  31667. };
  31668. /**
  31669. * Get the class name of the texture.
  31670. * @returns "BaseTexture"
  31671. */
  31672. BaseTexture.prototype.getClassName = function () {
  31673. return "BaseTexture";
  31674. };
  31675. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  31676. /**
  31677. * Callback triggered when the texture has been disposed.
  31678. * Kept for back compatibility, you can use the onDisposeObservable instead.
  31679. */
  31680. set: function (callback) {
  31681. if (this._onDisposeObserver) {
  31682. this.onDisposeObservable.remove(this._onDisposeObserver);
  31683. }
  31684. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  31685. },
  31686. enumerable: true,
  31687. configurable: true
  31688. });
  31689. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  31690. /**
  31691. * Define if the texture is preventinga material to render or not.
  31692. * If not and the texture is not ready, the engine will use a default black texture instead.
  31693. */
  31694. get: function () {
  31695. return true;
  31696. },
  31697. enumerable: true,
  31698. configurable: true
  31699. });
  31700. /**
  31701. * Get the scene the texture belongs to.
  31702. * @returns the scene or null if undefined
  31703. */
  31704. BaseTexture.prototype.getScene = function () {
  31705. return this._scene;
  31706. };
  31707. /**
  31708. * Get the texture transform matrix used to offset tile the texture for istance.
  31709. * @returns the transformation matrix
  31710. */
  31711. BaseTexture.prototype.getTextureMatrix = function () {
  31712. return BABYLON.Matrix.IdentityReadOnly;
  31713. };
  31714. /**
  31715. * Get the texture reflection matrix used to rotate/transform the reflection.
  31716. * @returns the reflection matrix
  31717. */
  31718. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  31719. return BABYLON.Matrix.IdentityReadOnly;
  31720. };
  31721. /**
  31722. * Get the underlying lower level texture from Babylon.
  31723. * @returns the insternal texture
  31724. */
  31725. BaseTexture.prototype.getInternalTexture = function () {
  31726. return this._texture;
  31727. };
  31728. /**
  31729. * Get if the texture is ready to be consumed (either it is ready or it is not blocking)
  31730. * @returns true if ready or not blocking
  31731. */
  31732. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  31733. return !this.isBlocking || this.isReady();
  31734. };
  31735. /**
  31736. * Get if the texture is ready to be used (downloaded, converted, mip mapped...).
  31737. * @returns true if fully ready
  31738. */
  31739. BaseTexture.prototype.isReady = function () {
  31740. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  31741. this.delayLoad();
  31742. return false;
  31743. }
  31744. if (this._texture) {
  31745. return this._texture.isReady;
  31746. }
  31747. return false;
  31748. };
  31749. /**
  31750. * Get the size of the texture.
  31751. * @returns the texture size.
  31752. */
  31753. BaseTexture.prototype.getSize = function () {
  31754. if (this._texture) {
  31755. if (this._texture.width) {
  31756. this._cachedSize.width = this._texture.width;
  31757. this._cachedSize.height = this._texture.height;
  31758. return this._cachedSize;
  31759. }
  31760. if (this._texture._size) {
  31761. this._cachedSize.width = this._texture._size;
  31762. this._cachedSize.height = this._texture._size;
  31763. return this._cachedSize;
  31764. }
  31765. }
  31766. return this._cachedSize;
  31767. };
  31768. /**
  31769. * Get the base size of the texture.
  31770. * It can be different from the size if the texture has been resized for POT for instance
  31771. * @returns the base size
  31772. */
  31773. BaseTexture.prototype.getBaseSize = function () {
  31774. if (!this.isReady() || !this._texture) {
  31775. return BABYLON.Size.Zero();
  31776. }
  31777. if (this._texture._size) {
  31778. return new BABYLON.Size(this._texture._size, this._texture._size);
  31779. }
  31780. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  31781. };
  31782. /**
  31783. * Scales the texture if is `canRescale()`
  31784. * @param ratio the resize factor we want to use to rescale
  31785. */
  31786. BaseTexture.prototype.scale = function (ratio) {
  31787. };
  31788. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  31789. /**
  31790. * Get if the texture can rescale.
  31791. */
  31792. get: function () {
  31793. return false;
  31794. },
  31795. enumerable: true,
  31796. configurable: true
  31797. });
  31798. /** @hidden */
  31799. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  31800. if (!this._scene) {
  31801. return null;
  31802. }
  31803. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  31804. for (var index = 0; index < texturesCache.length; index++) {
  31805. var texturesCacheEntry = texturesCache[index];
  31806. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  31807. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  31808. texturesCacheEntry.incrementReferences();
  31809. return texturesCacheEntry;
  31810. }
  31811. }
  31812. }
  31813. return null;
  31814. };
  31815. /** @hidden */
  31816. BaseTexture.prototype._rebuild = function () {
  31817. };
  31818. /**
  31819. * Triggers the load sequence in delayed load mode.
  31820. */
  31821. BaseTexture.prototype.delayLoad = function () {
  31822. };
  31823. /**
  31824. * Clones the texture.
  31825. * @returns the cloned texture
  31826. */
  31827. BaseTexture.prototype.clone = function () {
  31828. return null;
  31829. };
  31830. Object.defineProperty(BaseTexture.prototype, "textureType", {
  31831. /**
  31832. * Get the texture underlying type (INT, FLOAT...)
  31833. */
  31834. get: function () {
  31835. if (!this._texture) {
  31836. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  31837. }
  31838. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  31839. },
  31840. enumerable: true,
  31841. configurable: true
  31842. });
  31843. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  31844. /**
  31845. * Get the texture underlying format (RGB, RGBA...)
  31846. */
  31847. get: function () {
  31848. if (!this._texture) {
  31849. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  31850. }
  31851. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  31852. },
  31853. enumerable: true,
  31854. configurable: true
  31855. });
  31856. /**
  31857. * Reads the pixels stored in the webgl texture and returns them as an ArrayBuffer.
  31858. * This will returns an RGBA array buffer containing either in values (0-255) or
  31859. * float values (0-1) depending of the underlying buffer type.
  31860. * @param faceIndex defines the face of the texture to read (in case of cube texture)
  31861. * @param level defines the LOD level of the texture to read (in case of Mip Maps)
  31862. * @param buffer defines a user defined buffer to fill with data (can be null)
  31863. * @returns The Array buffer containing the pixels data.
  31864. */
  31865. BaseTexture.prototype.readPixels = function (faceIndex, level, buffer) {
  31866. if (faceIndex === void 0) { faceIndex = 0; }
  31867. if (level === void 0) { level = 0; }
  31868. if (buffer === void 0) { buffer = null; }
  31869. if (!this._texture) {
  31870. return null;
  31871. }
  31872. var size = this.getSize();
  31873. var width = size.width;
  31874. var height = size.height;
  31875. var scene = this.getScene();
  31876. if (!scene) {
  31877. return null;
  31878. }
  31879. var engine = scene.getEngine();
  31880. if (level != 0) {
  31881. width = width / Math.pow(2, level);
  31882. height = height / Math.pow(2, level);
  31883. width = Math.round(width);
  31884. height = Math.round(height);
  31885. }
  31886. if (this._texture.isCube) {
  31887. return engine._readTexturePixels(this._texture, width, height, faceIndex, level, buffer);
  31888. }
  31889. return engine._readTexturePixels(this._texture, width, height, -1, level, buffer);
  31890. };
  31891. /**
  31892. * Release and destroy the underlying lower level texture aka internalTexture.
  31893. */
  31894. BaseTexture.prototype.releaseInternalTexture = function () {
  31895. if (this._texture) {
  31896. this._texture.dispose();
  31897. this._texture = null;
  31898. }
  31899. };
  31900. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  31901. /**
  31902. * Get the polynomial representation of the texture data.
  31903. * This is mainly use as a fast way to recover IBL Diffuse irradiance data.
  31904. * @see https://learnopengl.com/PBR/IBL/Diffuse-irradiance
  31905. */
  31906. get: function () {
  31907. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  31908. return null;
  31909. }
  31910. if (!this._texture._sphericalPolynomial) {
  31911. this._texture._sphericalPolynomial =
  31912. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  31913. }
  31914. return this._texture._sphericalPolynomial;
  31915. },
  31916. set: function (value) {
  31917. if (this._texture) {
  31918. this._texture._sphericalPolynomial = value;
  31919. }
  31920. },
  31921. enumerable: true,
  31922. configurable: true
  31923. });
  31924. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  31925. /** @hidden */
  31926. get: function () {
  31927. if (this._texture) {
  31928. return this._texture._lodTextureHigh;
  31929. }
  31930. return null;
  31931. },
  31932. enumerable: true,
  31933. configurable: true
  31934. });
  31935. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  31936. /** @hidden */
  31937. get: function () {
  31938. if (this._texture) {
  31939. return this._texture._lodTextureMid;
  31940. }
  31941. return null;
  31942. },
  31943. enumerable: true,
  31944. configurable: true
  31945. });
  31946. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  31947. /** @hidden */
  31948. get: function () {
  31949. if (this._texture) {
  31950. return this._texture._lodTextureLow;
  31951. }
  31952. return null;
  31953. },
  31954. enumerable: true,
  31955. configurable: true
  31956. });
  31957. /**
  31958. * Dispose the texture and release its associated resources.
  31959. */
  31960. BaseTexture.prototype.dispose = function () {
  31961. if (!this._scene) {
  31962. return;
  31963. }
  31964. // Animations
  31965. this._scene.stopAnimation(this);
  31966. // Remove from scene
  31967. this._scene._removePendingData(this);
  31968. var index = this._scene.textures.indexOf(this);
  31969. if (index >= 0) {
  31970. this._scene.textures.splice(index, 1);
  31971. }
  31972. this._scene.onTextureRemovedObservable.notifyObservers(this);
  31973. if (this._texture === undefined) {
  31974. return;
  31975. }
  31976. // Release
  31977. this.releaseInternalTexture();
  31978. // Callback
  31979. this.onDisposeObservable.notifyObservers(this);
  31980. this.onDisposeObservable.clear();
  31981. };
  31982. /**
  31983. * Serialize the texture into a JSON representation that can be parsed later on.
  31984. * @returns the JSON representation of the texture
  31985. */
  31986. BaseTexture.prototype.serialize = function () {
  31987. if (!this.name) {
  31988. return null;
  31989. }
  31990. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  31991. // Animations
  31992. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  31993. return serializationObject;
  31994. };
  31995. /**
  31996. * Helper function to be called back once a list of texture contains only ready textures.
  31997. * @param textures Define the list of textures to wait for
  31998. * @param callback Define the callback triggered once the entire list will be ready
  31999. */
  32000. BaseTexture.WhenAllReady = function (textures, callback) {
  32001. var numRemaining = textures.length;
  32002. if (numRemaining === 0) {
  32003. callback();
  32004. return;
  32005. }
  32006. var _loop_1 = function () {
  32007. texture = textures[i];
  32008. if (texture.isReady()) {
  32009. if (--numRemaining === 0) {
  32010. callback();
  32011. }
  32012. }
  32013. else {
  32014. onLoadObservable = texture.onLoadObservable;
  32015. var onLoadCallback_1 = function () {
  32016. onLoadObservable.removeCallback(onLoadCallback_1);
  32017. if (--numRemaining === 0) {
  32018. callback();
  32019. }
  32020. };
  32021. onLoadObservable.add(onLoadCallback_1);
  32022. }
  32023. };
  32024. var texture, onLoadObservable;
  32025. for (var i = 0; i < textures.length; i++) {
  32026. _loop_1();
  32027. }
  32028. };
  32029. /**
  32030. * Default anisotropic filtering level for the application.
  32031. * It is set to 4 as a good tradeoff between perf and quality.
  32032. */
  32033. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  32034. __decorate([
  32035. BABYLON.serialize()
  32036. ], BaseTexture.prototype, "uniqueId", void 0);
  32037. __decorate([
  32038. BABYLON.serialize()
  32039. ], BaseTexture.prototype, "name", void 0);
  32040. __decorate([
  32041. BABYLON.serialize()
  32042. ], BaseTexture.prototype, "metadata", void 0);
  32043. __decorate([
  32044. BABYLON.serialize("hasAlpha")
  32045. ], BaseTexture.prototype, "_hasAlpha", void 0);
  32046. __decorate([
  32047. BABYLON.serialize()
  32048. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  32049. __decorate([
  32050. BABYLON.serialize()
  32051. ], BaseTexture.prototype, "level", void 0);
  32052. __decorate([
  32053. BABYLON.serialize()
  32054. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  32055. __decorate([
  32056. BABYLON.serialize("coordinatesMode")
  32057. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  32058. __decorate([
  32059. BABYLON.serialize()
  32060. ], BaseTexture.prototype, "wrapU", void 0);
  32061. __decorate([
  32062. BABYLON.serialize()
  32063. ], BaseTexture.prototype, "wrapV", void 0);
  32064. __decorate([
  32065. BABYLON.serialize()
  32066. ], BaseTexture.prototype, "wrapR", void 0);
  32067. __decorate([
  32068. BABYLON.serialize()
  32069. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  32070. __decorate([
  32071. BABYLON.serialize()
  32072. ], BaseTexture.prototype, "isCube", void 0);
  32073. __decorate([
  32074. BABYLON.serialize()
  32075. ], BaseTexture.prototype, "is3D", void 0);
  32076. __decorate([
  32077. BABYLON.serialize()
  32078. ], BaseTexture.prototype, "gammaSpace", void 0);
  32079. __decorate([
  32080. BABYLON.serialize()
  32081. ], BaseTexture.prototype, "invertZ", void 0);
  32082. __decorate([
  32083. BABYLON.serialize()
  32084. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  32085. __decorate([
  32086. BABYLON.serialize()
  32087. ], BaseTexture.prototype, "lodGenerationOffset", null);
  32088. __decorate([
  32089. BABYLON.serialize()
  32090. ], BaseTexture.prototype, "lodGenerationScale", null);
  32091. __decorate([
  32092. BABYLON.serialize()
  32093. ], BaseTexture.prototype, "isRenderTarget", void 0);
  32094. return BaseTexture;
  32095. }());
  32096. BABYLON.BaseTexture = BaseTexture;
  32097. })(BABYLON || (BABYLON = {}));
  32098. //# sourceMappingURL=babylon.baseTexture.js.map
  32099. var BABYLON;
  32100. (function (BABYLON) {
  32101. /**
  32102. * This represents a texture in babylon. It can be easily loaded from a network, base64 or html input.
  32103. * @see http://doc.babylonjs.com/babylon101/materials#texture
  32104. */
  32105. var Texture = /** @class */ (function (_super) {
  32106. __extends(Texture, _super);
  32107. /**
  32108. * Instantiates a new texture.
  32109. * This represents a texture in babylon. It can be easily loaded from a network, base64 or html input.
  32110. * @see http://doc.babylonjs.com/babylon101/materials#texture
  32111. * @param url define the url of the picture to load as a texture
  32112. * @param scene define the scene the texture will belong to
  32113. * @param noMipmap define if the texture will require mip maps or not
  32114. * @param invertY define if the texture needs to be inverted on the y axis during loading
  32115. * @param samplingMode define the sampling mode we want for the texture while fectching from it (Texture.NEAREST_SAMPLINGMODE...)
  32116. * @param onLoad define a callback triggered when the texture has been loaded
  32117. * @param onError define a callback triggered when an error occurred during the loading session
  32118. * @param buffer define the buffer to load the texture from in case the texture is loaded from a buffer representation
  32119. * @param deleteBuffer define if the buffer we are loading the texture from should be deleted after load
  32120. * @param format define the format of the texture we are trying to load (Engine.TEXTUREFORMAT_RGBA...)
  32121. */
  32122. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  32123. if (noMipmap === void 0) { noMipmap = false; }
  32124. if (invertY === void 0) { invertY = true; }
  32125. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  32126. if (onLoad === void 0) { onLoad = null; }
  32127. if (onError === void 0) { onError = null; }
  32128. if (buffer === void 0) { buffer = null; }
  32129. if (deleteBuffer === void 0) { deleteBuffer = false; }
  32130. var _this = _super.call(this, scene) || this;
  32131. /**
  32132. * Define an offset on the texture to offset the u coordinates of the UVs
  32133. * @see http://doc.babylonjs.com/how_to/more_materials#offsetting
  32134. */
  32135. _this.uOffset = 0;
  32136. /**
  32137. * Define an offset on the texture to offset the v coordinates of the UVs
  32138. * @see http://doc.babylonjs.com/how_to/more_materials#offsetting
  32139. */
  32140. _this.vOffset = 0;
  32141. /**
  32142. * Define an offset on the texture to scale the u coordinates of the UVs
  32143. * @see http://doc.babylonjs.com/how_to/more_materials#tiling
  32144. */
  32145. _this.uScale = 1.0;
  32146. /**
  32147. * Define an offset on the texture to scale the v coordinates of the UVs
  32148. * @see http://doc.babylonjs.com/how_to/more_materials#tiling
  32149. */
  32150. _this.vScale = 1.0;
  32151. /**
  32152. * Define an offset on the texture to rotate around the u coordinates of the UVs
  32153. * @see http://doc.babylonjs.com/how_to/more_materials
  32154. */
  32155. _this.uAng = 0;
  32156. /**
  32157. * Define an offset on the texture to rotate around the v coordinates of the UVs
  32158. * @see http://doc.babylonjs.com/how_to/more_materials
  32159. */
  32160. _this.vAng = 0;
  32161. /**
  32162. * Define an offset on the texture to rotate around the w coordinates of the UVs (in case of 3d texture)
  32163. * @see http://doc.babylonjs.com/how_to/more_materials
  32164. */
  32165. _this.wAng = 0;
  32166. /**
  32167. * Defines the center of rotation (U)
  32168. */
  32169. _this.uRotationCenter = 0.5;
  32170. /**
  32171. * Defines the center of rotation (V)
  32172. */
  32173. _this.vRotationCenter = 0.5;
  32174. /**
  32175. * Defines the center of rotation (W)
  32176. */
  32177. _this.wRotationCenter = 0.5;
  32178. /**
  32179. * Observable triggered once the texture has been loaded.
  32180. */
  32181. _this.onLoadObservable = new BABYLON.Observable();
  32182. _this._isBlocking = true;
  32183. _this.name = url || "";
  32184. _this.url = url;
  32185. _this._noMipmap = noMipmap;
  32186. _this._invertY = invertY;
  32187. _this._samplingMode = samplingMode;
  32188. _this._buffer = buffer;
  32189. _this._deleteBuffer = deleteBuffer;
  32190. if (format) {
  32191. _this._format = format;
  32192. }
  32193. scene = _this.getScene();
  32194. if (!scene) {
  32195. return _this;
  32196. }
  32197. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  32198. var load = function () {
  32199. if (_this.onLoadObservable.hasObservers()) {
  32200. _this.onLoadObservable.notifyObservers(_this);
  32201. }
  32202. if (onLoad) {
  32203. onLoad();
  32204. }
  32205. if (!_this.isBlocking && scene) {
  32206. scene.resetCachedMaterial();
  32207. }
  32208. };
  32209. if (!_this.url) {
  32210. _this._delayedOnLoad = load;
  32211. _this._delayedOnError = onError;
  32212. return _this;
  32213. }
  32214. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  32215. if (!_this._texture) {
  32216. if (!scene.useDelayedTextureLoading) {
  32217. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  32218. if (deleteBuffer) {
  32219. delete _this._buffer;
  32220. }
  32221. }
  32222. else {
  32223. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  32224. _this._delayedOnLoad = load;
  32225. _this._delayedOnError = onError;
  32226. }
  32227. }
  32228. else {
  32229. if (_this._texture.isReady) {
  32230. BABYLON.Tools.SetImmediate(function () { return load(); });
  32231. }
  32232. else {
  32233. _this._texture.onLoadedObservable.add(load);
  32234. }
  32235. }
  32236. return _this;
  32237. }
  32238. Object.defineProperty(Texture.prototype, "noMipmap", {
  32239. /**
  32240. * Are mip maps generated for this texture or not.
  32241. */
  32242. get: function () {
  32243. return this._noMipmap;
  32244. },
  32245. enumerable: true,
  32246. configurable: true
  32247. });
  32248. Object.defineProperty(Texture.prototype, "isBlocking", {
  32249. get: function () {
  32250. return this._isBlocking;
  32251. },
  32252. /**
  32253. * Is the texture preventing material to render while loading.
  32254. * If false, a default texture will be used instead of the loading one during the preparation step.
  32255. */
  32256. set: function (value) {
  32257. this._isBlocking = value;
  32258. },
  32259. enumerable: true,
  32260. configurable: true
  32261. });
  32262. Object.defineProperty(Texture.prototype, "samplingMode", {
  32263. /**
  32264. * Get the current sampling mode associated with the texture.
  32265. */
  32266. get: function () {
  32267. return this._samplingMode;
  32268. },
  32269. enumerable: true,
  32270. configurable: true
  32271. });
  32272. Object.defineProperty(Texture.prototype, "invertY", {
  32273. /**
  32274. * Gets a boolean indicating if the texture needs to be inverted on the y axis during loading
  32275. */
  32276. get: function () {
  32277. return this._invertY;
  32278. },
  32279. enumerable: true,
  32280. configurable: true
  32281. });
  32282. /**
  32283. * Update the url (and optional buffer) of this texture if url was null during construction.
  32284. * @param url the url of the texture
  32285. * @param buffer the buffer of the texture (defaults to null)
  32286. */
  32287. Texture.prototype.updateURL = function (url, buffer) {
  32288. if (buffer === void 0) { buffer = null; }
  32289. if (this.url) {
  32290. throw new Error("URL is already set");
  32291. }
  32292. this.url = url;
  32293. this._buffer = buffer;
  32294. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  32295. this.delayLoad();
  32296. };
  32297. /**
  32298. * Finish the loading sequence of a texture flagged as delayed load.
  32299. * @hidden
  32300. */
  32301. Texture.prototype.delayLoad = function () {
  32302. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  32303. return;
  32304. }
  32305. var scene = this.getScene();
  32306. if (!scene) {
  32307. return;
  32308. }
  32309. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32310. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  32311. if (!this._texture) {
  32312. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  32313. if (this._deleteBuffer) {
  32314. delete this._buffer;
  32315. }
  32316. }
  32317. else {
  32318. if (this._delayedOnLoad) {
  32319. if (this._texture.isReady) {
  32320. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  32321. }
  32322. else {
  32323. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  32324. }
  32325. }
  32326. }
  32327. this._delayedOnLoad = null;
  32328. this._delayedOnError = null;
  32329. };
  32330. /**
  32331. * Update the sampling mode of the texture.
  32332. * Default is Trilinear mode.
  32333. *
  32334. * | Value | Type | Description |
  32335. * | ----- | ------------------ | ----------- |
  32336. * | 1 | NEAREST_SAMPLINGMODE or NEAREST_NEAREST_MIPLINEAR | Nearest is: mag = nearest, min = nearest, mip = linear |
  32337. * | 2 | BILINEAR_SAMPLINGMODE or LINEAR_LINEAR_MIPNEAREST | Bilinear is: mag = linear, min = linear, mip = nearest |
  32338. * | 3 | TRILINEAR_SAMPLINGMODE or LINEAR_LINEAR_MIPLINEAR | Trilinear is: mag = linear, min = linear, mip = linear |
  32339. * | 4 | NEAREST_NEAREST_MIPNEAREST | |
  32340. * | 5 | NEAREST_LINEAR_MIPNEAREST | |
  32341. * | 6 | NEAREST_LINEAR_MIPLINEAR | |
  32342. * | 7 | NEAREST_LINEAR | |
  32343. * | 8 | NEAREST_NEAREST | |
  32344. * | 9 | LINEAR_NEAREST_MIPNEAREST | |
  32345. * | 10 | LINEAR_NEAREST_MIPLINEAR | |
  32346. * | 11 | LINEAR_LINEAR | |
  32347. * | 12 | LINEAR_NEAREST | |
  32348. *
  32349. * > _mag_: magnification filter (close to the viewer)
  32350. * > _min_: minification filter (far from the viewer)
  32351. * > _mip_: filter used between mip map levels
  32352. *@param samplingMode Define the new sampling mode of the texture
  32353. */
  32354. Texture.prototype.updateSamplingMode = function (samplingMode) {
  32355. if (!this._texture) {
  32356. return;
  32357. }
  32358. var scene = this.getScene();
  32359. if (!scene) {
  32360. return;
  32361. }
  32362. this._samplingMode = samplingMode;
  32363. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  32364. };
  32365. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  32366. x *= this.uScale;
  32367. y *= this.vScale;
  32368. x -= this.uRotationCenter * this.uScale;
  32369. y -= this.vRotationCenter * this.vScale;
  32370. z -= this.wRotationCenter;
  32371. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  32372. t.x += this.uRotationCenter * this.uScale + this.uOffset;
  32373. t.y += this.vRotationCenter * this.vScale + this.vOffset;
  32374. t.z += this.wRotationCenter;
  32375. };
  32376. /**
  32377. * Get the current texture matrix which includes the requested offsetting, tiling and rotation components.
  32378. * @returns the transform matrix of the texture.
  32379. */
  32380. Texture.prototype.getTextureMatrix = function () {
  32381. var _this = this;
  32382. if (this.uOffset === this._cachedUOffset &&
  32383. this.vOffset === this._cachedVOffset &&
  32384. this.uScale === this._cachedUScale &&
  32385. this.vScale === this._cachedVScale &&
  32386. this.uAng === this._cachedUAng &&
  32387. this.vAng === this._cachedVAng &&
  32388. this.wAng === this._cachedWAng) {
  32389. return this._cachedTextureMatrix;
  32390. }
  32391. this._cachedUOffset = this.uOffset;
  32392. this._cachedVOffset = this.vOffset;
  32393. this._cachedUScale = this.uScale;
  32394. this._cachedVScale = this.vScale;
  32395. this._cachedUAng = this.uAng;
  32396. this._cachedVAng = this.vAng;
  32397. this._cachedWAng = this.wAng;
  32398. if (!this._cachedTextureMatrix) {
  32399. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  32400. this._rowGenerationMatrix = new BABYLON.Matrix();
  32401. this._t0 = BABYLON.Vector3.Zero();
  32402. this._t1 = BABYLON.Vector3.Zero();
  32403. this._t2 = BABYLON.Vector3.Zero();
  32404. }
  32405. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  32406. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  32407. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  32408. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  32409. this._t1.subtractInPlace(this._t0);
  32410. this._t2.subtractInPlace(this._t0);
  32411. BABYLON.Matrix.FromValuesToRef(this._t1.x, this._t1.y, this._t1.z, 0.0, this._t2.x, this._t2.y, this._t2.z, 0.0, this._t0.x, this._t0.y, this._t0.z, 0.0, 0.0, 0.0, 0.0, 1.0, this._cachedTextureMatrix);
  32412. var scene = this.getScene();
  32413. if (!scene) {
  32414. return this._cachedTextureMatrix;
  32415. }
  32416. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  32417. return mat.hasTexture(_this);
  32418. });
  32419. return this._cachedTextureMatrix;
  32420. };
  32421. /**
  32422. * Get the current matrix used to apply reflection. This is useful to rotate an environment texture for instance.
  32423. * @returns The reflection texture transform
  32424. */
  32425. Texture.prototype.getReflectionTextureMatrix = function () {
  32426. var _this = this;
  32427. var scene = this.getScene();
  32428. if (!scene) {
  32429. return this._cachedTextureMatrix;
  32430. }
  32431. if (this.uOffset === this._cachedUOffset &&
  32432. this.vOffset === this._cachedVOffset &&
  32433. this.uScale === this._cachedUScale &&
  32434. this.vScale === this._cachedVScale &&
  32435. this.coordinatesMode === this._cachedCoordinatesMode) {
  32436. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  32437. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  32438. return this._cachedTextureMatrix;
  32439. }
  32440. }
  32441. else {
  32442. return this._cachedTextureMatrix;
  32443. }
  32444. }
  32445. if (!this._cachedTextureMatrix) {
  32446. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  32447. }
  32448. if (!this._projectionModeMatrix) {
  32449. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  32450. }
  32451. this._cachedUOffset = this.uOffset;
  32452. this._cachedVOffset = this.vOffset;
  32453. this._cachedUScale = this.uScale;
  32454. this._cachedVScale = this.vScale;
  32455. this._cachedCoordinatesMode = this.coordinatesMode;
  32456. switch (this.coordinatesMode) {
  32457. case Texture.PLANAR_MODE:
  32458. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  32459. this._cachedTextureMatrix[0] = this.uScale;
  32460. this._cachedTextureMatrix[5] = this.vScale;
  32461. this._cachedTextureMatrix[12] = this.uOffset;
  32462. this._cachedTextureMatrix[13] = this.vOffset;
  32463. break;
  32464. case Texture.PROJECTION_MODE:
  32465. BABYLON.Matrix.FromValuesToRef(0.5, 0.0, 0.0, 0.0, 0.0, -0.5, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.5, 0.5, 1.0, 1.0, this._projectionModeMatrix);
  32466. var projectionMatrix = scene.getProjectionMatrix();
  32467. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  32468. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  32469. break;
  32470. default:
  32471. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  32472. break;
  32473. }
  32474. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  32475. return (mat.getActiveTextures().indexOf(_this) !== -1);
  32476. });
  32477. return this._cachedTextureMatrix;
  32478. };
  32479. /**
  32480. * Clones the texture.
  32481. * @returns the cloned texture
  32482. */
  32483. Texture.prototype.clone = function () {
  32484. var _this = this;
  32485. return BABYLON.SerializationHelper.Clone(function () {
  32486. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  32487. }, this);
  32488. };
  32489. /**
  32490. * Serialize the texture to a JSON representation we can easily use in the resepective Parse function.
  32491. * @returns The JSON representation of the texture
  32492. */
  32493. Texture.prototype.serialize = function () {
  32494. var serializationObject = _super.prototype.serialize.call(this);
  32495. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  32496. serializationObject.base64String = this._buffer;
  32497. serializationObject.name = serializationObject.name.replace("data:", "");
  32498. }
  32499. serializationObject.invertY = this._invertY;
  32500. serializationObject.samplingMode = this.samplingMode;
  32501. return serializationObject;
  32502. };
  32503. /**
  32504. * Get the current class name of the texture usefull for serialization or dynamic coding.
  32505. * @returns "Texture"
  32506. */
  32507. Texture.prototype.getClassName = function () {
  32508. return "Texture";
  32509. };
  32510. /**
  32511. * Dispose the texture and release its associated resources.
  32512. */
  32513. Texture.prototype.dispose = function () {
  32514. _super.prototype.dispose.call(this);
  32515. this.onLoadObservable.clear();
  32516. this._delayedOnLoad = null;
  32517. this._delayedOnError = null;
  32518. };
  32519. /**
  32520. * Parse the JSON representation of a texture in order to recreate the texture in the given scene.
  32521. * @param parsedTexture Define the JSON representation of the texture
  32522. * @param scene Define the scene the parsed texture should be instantiated in
  32523. * @param rootUrl Define the root url of the parsing sequence in the case of relative dependencies
  32524. * @returns The parsed texture if successful
  32525. */
  32526. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  32527. if (parsedTexture.customType) {
  32528. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  32529. // Update Sampling Mode
  32530. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  32531. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  32532. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  32533. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  32534. }
  32535. }
  32536. return parsedCustomTexture;
  32537. }
  32538. if (parsedTexture.isCube) {
  32539. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  32540. }
  32541. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  32542. return null;
  32543. }
  32544. var texture = BABYLON.SerializationHelper.Parse(function () {
  32545. var generateMipMaps = true;
  32546. if (parsedTexture.noMipmap) {
  32547. generateMipMaps = false;
  32548. }
  32549. if (parsedTexture.mirrorPlane) {
  32550. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  32551. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  32552. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  32553. return mirrorTexture;
  32554. }
  32555. else if (parsedTexture.isRenderTarget) {
  32556. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  32557. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  32558. return renderTargetTexture;
  32559. }
  32560. else {
  32561. var texture;
  32562. if (parsedTexture.base64String) {
  32563. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  32564. }
  32565. else {
  32566. var url = rootUrl + parsedTexture.name;
  32567. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  32568. url = parsedTexture.url;
  32569. }
  32570. texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
  32571. }
  32572. return texture;
  32573. }
  32574. }, parsedTexture, scene);
  32575. // Update Sampling Mode
  32576. if (parsedTexture.samplingMode) {
  32577. var sampling = parsedTexture.samplingMode;
  32578. if (texture._samplingMode !== sampling) {
  32579. texture.updateSamplingMode(sampling);
  32580. }
  32581. }
  32582. // Animations
  32583. if (parsedTexture.animations) {
  32584. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  32585. var parsedAnimation = parsedTexture.animations[animationIndex];
  32586. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  32587. }
  32588. }
  32589. return texture;
  32590. };
  32591. /**
  32592. * Creates a texture from its base 64 representation.
  32593. * @param data Define the base64 payload without the data: prefix
  32594. * @param name Define the name of the texture in the scene useful fo caching purpose for instance
  32595. * @param scene Define the scene the texture should belong to
  32596. * @param noMipmap Forces the texture to not create mip map information if true
  32597. * @param invertY define if the texture needs to be inverted on the y axis during loading
  32598. * @param samplingMode define the sampling mode we want for the texture while fectching from it (Texture.NEAREST_SAMPLINGMODE...)
  32599. * @param onLoad define a callback triggered when the texture has been loaded
  32600. * @param onError define a callback triggered when an error occurred during the loading session
  32601. * @param format define the format of the texture we are trying to load (Engine.TEXTUREFORMAT_RGBA...)
  32602. * @returns the created texture
  32603. */
  32604. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  32605. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  32606. if (onLoad === void 0) { onLoad = null; }
  32607. if (onError === void 0) { onError = null; }
  32608. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  32609. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  32610. };
  32611. /**
  32612. * Creates a texture from its data: representation. (data: will be added in case only the payload has been passed in)
  32613. * @param data Define the base64 payload without the data: prefix
  32614. * @param name Define the name of the texture in the scene useful fo caching purpose for instance
  32615. * @param buffer define the buffer to load the texture from in case the texture is loaded from a buffer representation
  32616. * @param scene Define the scene the texture should belong to
  32617. * @param deleteBuffer define if the buffer we are loading the texture from should be deleted after load
  32618. * @param noMipmap Forces the texture to not create mip map information if true
  32619. * @param invertY define if the texture needs to be inverted on the y axis during loading
  32620. * @param samplingMode define the sampling mode we want for the texture while fectching from it (Texture.NEAREST_SAMPLINGMODE...)
  32621. * @param onLoad define a callback triggered when the texture has been loaded
  32622. * @param onError define a callback triggered when an error occurred during the loading session
  32623. * @param format define the format of the texture we are trying to load (Engine.TEXTUREFORMAT_RGBA...)
  32624. * @returns the created texture
  32625. */
  32626. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  32627. if (deleteBuffer === void 0) { deleteBuffer = false; }
  32628. if (noMipmap === void 0) { noMipmap = false; }
  32629. if (invertY === void 0) { invertY = true; }
  32630. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  32631. if (onLoad === void 0) { onLoad = null; }
  32632. if (onError === void 0) { onError = null; }
  32633. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  32634. if (name.substr(0, 5) !== "data:") {
  32635. name = "data:" + name;
  32636. }
  32637. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  32638. };
  32639. /** nearest is mag = nearest and min = nearest and mip = linear */
  32640. Texture.NEAREST_SAMPLINGMODE = BABYLON.Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  32641. /** nearest is mag = nearest and min = nearest and mip = linear */
  32642. Texture.NEAREST_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR; // nearest is mag = nearest and min = nearest and mip = linear
  32643. /** Bilinear is mag = linear and min = linear and mip = nearest */
  32644. Texture.BILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_BILINEAR_SAMPLINGMODE;
  32645. /** Bilinear is mag = linear and min = linear and mip = nearest */
  32646. Texture.LINEAR_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST; // Bilinear is mag = linear and min = linear and mip = nearest
  32647. /** Trilinear is mag = linear and min = linear and mip = linear */
  32648. Texture.TRILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  32649. /** Trilinear is mag = linear and min = linear and mip = linear */
  32650. Texture.LINEAR_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR; // Trilinear is mag = linear and min = linear and mip = linear
  32651. /** mag = nearest and min = nearest and mip = nearest */
  32652. Texture.NEAREST_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST;
  32653. /** mag = nearest and min = linear and mip = nearest */
  32654. Texture.NEAREST_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST;
  32655. /** mag = nearest and min = linear and mip = linear */
  32656. Texture.NEAREST_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR;
  32657. /** mag = nearest and min = linear and mip = none */
  32658. Texture.NEAREST_LINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR;
  32659. /** mag = nearest and min = nearest and mip = none */
  32660. Texture.NEAREST_NEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST;
  32661. /** mag = linear and min = nearest and mip = nearest */
  32662. Texture.LINEAR_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST;
  32663. /** mag = linear and min = nearest and mip = linear */
  32664. Texture.LINEAR_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR;
  32665. /** mag = linear and min = linear and mip = none */
  32666. Texture.LINEAR_LINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR;
  32667. /** mag = linear and min = nearest and mip = none */
  32668. Texture.LINEAR_NEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST;
  32669. /** Explicit coordinates mode */
  32670. Texture.EXPLICIT_MODE = BABYLON.Engine.TEXTURE_EXPLICIT_MODE;
  32671. /** Spherical coordinates mode */
  32672. Texture.SPHERICAL_MODE = BABYLON.Engine.TEXTURE_SPHERICAL_MODE;
  32673. /** Planar coordinates mode */
  32674. Texture.PLANAR_MODE = BABYLON.Engine.TEXTURE_PLANAR_MODE;
  32675. /** Cubic coordinates mode */
  32676. Texture.CUBIC_MODE = BABYLON.Engine.TEXTURE_CUBIC_MODE;
  32677. /** Projection coordinates mode */
  32678. Texture.PROJECTION_MODE = BABYLON.Engine.TEXTURE_PROJECTION_MODE;
  32679. /** Inverse Cubic coordinates mode */
  32680. Texture.SKYBOX_MODE = BABYLON.Engine.TEXTURE_SKYBOX_MODE;
  32681. /** Inverse Cubic coordinates mode */
  32682. Texture.INVCUBIC_MODE = BABYLON.Engine.TEXTURE_INVCUBIC_MODE;
  32683. /** Equirectangular coordinates mode */
  32684. Texture.EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_EQUIRECTANGULAR_MODE;
  32685. /** Equirectangular Fixed coordinates mode */
  32686. Texture.FIXED_EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE;
  32687. /** Equirectangular Fixed Mirrored coordinates mode */
  32688. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE;
  32689. /** Texture is not repeating outside of 0..1 UVs */
  32690. Texture.CLAMP_ADDRESSMODE = BABYLON.Engine.TEXTURE_CLAMP_ADDRESSMODE;
  32691. /** Texture is repeating outside of 0..1 UVs */
  32692. Texture.WRAP_ADDRESSMODE = BABYLON.Engine.TEXTURE_WRAP_ADDRESSMODE;
  32693. /** Texture is repeating and mirrored */
  32694. Texture.MIRROR_ADDRESSMODE = BABYLON.Engine.TEXTURE_MIRROR_ADDRESSMODE;
  32695. /**
  32696. * 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
  32697. */
  32698. Texture.UseSerializedUrlIfAny = false;
  32699. __decorate([
  32700. BABYLON.serialize()
  32701. ], Texture.prototype, "url", void 0);
  32702. __decorate([
  32703. BABYLON.serialize()
  32704. ], Texture.prototype, "uOffset", void 0);
  32705. __decorate([
  32706. BABYLON.serialize()
  32707. ], Texture.prototype, "vOffset", void 0);
  32708. __decorate([
  32709. BABYLON.serialize()
  32710. ], Texture.prototype, "uScale", void 0);
  32711. __decorate([
  32712. BABYLON.serialize()
  32713. ], Texture.prototype, "vScale", void 0);
  32714. __decorate([
  32715. BABYLON.serialize()
  32716. ], Texture.prototype, "uAng", void 0);
  32717. __decorate([
  32718. BABYLON.serialize()
  32719. ], Texture.prototype, "vAng", void 0);
  32720. __decorate([
  32721. BABYLON.serialize()
  32722. ], Texture.prototype, "wAng", void 0);
  32723. __decorate([
  32724. BABYLON.serialize()
  32725. ], Texture.prototype, "uRotationCenter", void 0);
  32726. __decorate([
  32727. BABYLON.serialize()
  32728. ], Texture.prototype, "vRotationCenter", void 0);
  32729. __decorate([
  32730. BABYLON.serialize()
  32731. ], Texture.prototype, "wRotationCenter", void 0);
  32732. __decorate([
  32733. BABYLON.serialize()
  32734. ], Texture.prototype, "isBlocking", null);
  32735. return Texture;
  32736. }(BABYLON.BaseTexture));
  32737. BABYLON.Texture = Texture;
  32738. })(BABYLON || (BABYLON = {}));
  32739. //# sourceMappingURL=babylon.texture.js.map
  32740. var BABYLON;
  32741. (function (BABYLON) {
  32742. /**
  32743. * @hidden
  32744. **/
  32745. var _CreationDataStorage = /** @class */ (function () {
  32746. function _CreationDataStorage() {
  32747. }
  32748. return _CreationDataStorage;
  32749. }());
  32750. BABYLON._CreationDataStorage = _CreationDataStorage;
  32751. /**
  32752. * @hidden
  32753. **/
  32754. var _InstanceDataStorage = /** @class */ (function () {
  32755. function _InstanceDataStorage() {
  32756. this.visibleInstances = {};
  32757. this.renderIdForInstances = new Array();
  32758. this.batchCache = new _InstancesBatch();
  32759. this.instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  32760. }
  32761. return _InstanceDataStorage;
  32762. }());
  32763. /**
  32764. * @hidden
  32765. **/
  32766. var _InstancesBatch = /** @class */ (function () {
  32767. function _InstancesBatch() {
  32768. this.mustReturn = false;
  32769. this.visibleInstances = new Array();
  32770. this.renderSelf = new Array();
  32771. }
  32772. return _InstancesBatch;
  32773. }());
  32774. BABYLON._InstancesBatch = _InstancesBatch;
  32775. /**
  32776. * Class used to represent renderable models
  32777. */
  32778. var Mesh = /** @class */ (function (_super) {
  32779. __extends(Mesh, _super);
  32780. /**
  32781. * @constructor
  32782. * @param name The value used by scene.getMeshByName() to do a lookup.
  32783. * @param scene The scene to add this mesh to.
  32784. * @param parent The parent of this mesh, if it has one
  32785. * @param source An optional Mesh from which geometry is shared, cloned.
  32786. * @param doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  32787. * When false, achieved by calling a clone(), also passing False.
  32788. * This will make creation of children, recursive.
  32789. * @param clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  32790. */
  32791. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  32792. if (scene === void 0) { scene = null; }
  32793. if (parent === void 0) { parent = null; }
  32794. if (source === void 0) { source = null; }
  32795. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  32796. var _this = _super.call(this, name, scene) || this;
  32797. // Members
  32798. /**
  32799. * Gets the delay loading state of the mesh (when delay loading is turned on)
  32800. * @see http://doc.babylonjs.com/how_to/using_the_incremental_loading_system
  32801. */
  32802. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  32803. /**
  32804. * Gets the list of instances created from this mesh
  32805. * it is not supposed to be modified manually.
  32806. * Note also that the order of the InstancedMesh wihin the array is not significant and might change.
  32807. * @see http://doc.babylonjs.com/how_to/how_to_use_instances
  32808. */
  32809. _this.instances = new Array();
  32810. _this._LODLevels = new Array();
  32811. /** @hidden */
  32812. _this._instanceDataStorage = new _InstanceDataStorage();
  32813. // Use by builder only to know what orientation were the mesh build in.
  32814. /** @hidden */
  32815. _this._originalBuilderSideOrientation = Mesh.DEFAULTSIDE;
  32816. /**
  32817. * Use this property to change the original side orientation defined at construction time
  32818. */
  32819. _this.overrideMaterialSideOrientation = null;
  32820. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  32821. // Will be used to save a source mesh reference, If any
  32822. _this._source = null;
  32823. scene = _this.getScene();
  32824. if (source) {
  32825. // Geometry
  32826. if (source._geometry) {
  32827. source._geometry.applyToMesh(_this);
  32828. }
  32829. // Deep copy
  32830. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  32831. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen",
  32832. "onBeforeDrawObservable", "onBeforeRenderObservable", "onAfterRenderObservable", "onBeforeDraw"
  32833. ], ["_poseMatrix"]);
  32834. // Source mesh
  32835. _this._source = source;
  32836. if (scene.useClonedMeshhMap) {
  32837. if (!source.meshMap) {
  32838. source.meshMap = {};
  32839. }
  32840. source.meshMap[_this.uniqueId] = _this;
  32841. }
  32842. // Construction Params
  32843. // Clone parameters allowing mesh to be updated in case of parametric shapes.
  32844. _this._originalBuilderSideOrientation = source._originalBuilderSideOrientation;
  32845. _this._creationDataStorage = source._creationDataStorage;
  32846. // Animation ranges
  32847. if (_this._source._ranges) {
  32848. var ranges = _this._source._ranges;
  32849. for (var name in ranges) {
  32850. if (!ranges.hasOwnProperty(name)) {
  32851. continue;
  32852. }
  32853. if (!ranges[name]) {
  32854. continue;
  32855. }
  32856. _this.createAnimationRange(name, ranges[name].from, ranges[name].to);
  32857. }
  32858. }
  32859. // Metadata
  32860. if (source.metadata && source.metadata.clone) {
  32861. _this.metadata = source.metadata.clone();
  32862. }
  32863. else {
  32864. _this.metadata = source.metadata;
  32865. }
  32866. // Tags
  32867. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  32868. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  32869. }
  32870. // Parent
  32871. _this.parent = source.parent;
  32872. // Pivot
  32873. _this.setPivotMatrix(source.getPivotMatrix());
  32874. _this.id = name + "." + source.id;
  32875. // Material
  32876. _this.material = source.material;
  32877. var index;
  32878. if (!doNotCloneChildren) {
  32879. // Children
  32880. var directDescendants = source.getDescendants(true);
  32881. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  32882. var child = directDescendants[index_1];
  32883. if (child.clone) {
  32884. child.clone(name + "." + child.name, _this);
  32885. }
  32886. }
  32887. }
  32888. // Physics clone
  32889. var physicsEngine = _this.getScene().getPhysicsEngine();
  32890. if (clonePhysicsImpostor && physicsEngine) {
  32891. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  32892. if (impostor) {
  32893. _this.physicsImpostor = impostor.clone(_this);
  32894. }
  32895. }
  32896. // Particles
  32897. for (index = 0; index < scene.particleSystems.length; index++) {
  32898. var system = scene.particleSystems[index];
  32899. if (system.emitter === source) {
  32900. system.clone(system.name, _this);
  32901. }
  32902. }
  32903. _this.refreshBoundingInfo();
  32904. _this.computeWorldMatrix(true);
  32905. }
  32906. // Parent
  32907. if (parent !== null) {
  32908. _this.parent = parent;
  32909. }
  32910. return _this;
  32911. }
  32912. Object.defineProperty(Mesh.prototype, "onBeforeRenderObservable", {
  32913. /**
  32914. * An event triggered before rendering the mesh
  32915. */
  32916. get: function () {
  32917. if (!this._onBeforeRenderObservable) {
  32918. this._onBeforeRenderObservable = new BABYLON.Observable();
  32919. }
  32920. return this._onBeforeRenderObservable;
  32921. },
  32922. enumerable: true,
  32923. configurable: true
  32924. });
  32925. Object.defineProperty(Mesh.prototype, "onAfterRenderObservable", {
  32926. /**
  32927. * An event triggered after rendering the mesh
  32928. */
  32929. get: function () {
  32930. if (!this._onAfterRenderObservable) {
  32931. this._onAfterRenderObservable = new BABYLON.Observable();
  32932. }
  32933. return this._onAfterRenderObservable;
  32934. },
  32935. enumerable: true,
  32936. configurable: true
  32937. });
  32938. Object.defineProperty(Mesh.prototype, "onBeforeDrawObservable", {
  32939. /**
  32940. * An event triggered before drawing the mesh
  32941. */
  32942. get: function () {
  32943. if (!this._onBeforeDrawObservable) {
  32944. this._onBeforeDrawObservable = new BABYLON.Observable();
  32945. }
  32946. return this._onBeforeDrawObservable;
  32947. },
  32948. enumerable: true,
  32949. configurable: true
  32950. });
  32951. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  32952. /**
  32953. * Sets a callback to call before drawing the mesh. It is recommended to use onBeforeDrawObservable instead
  32954. */
  32955. set: function (callback) {
  32956. if (this._onBeforeDrawObserver) {
  32957. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  32958. }
  32959. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  32960. },
  32961. enumerable: true,
  32962. configurable: true
  32963. });
  32964. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  32965. /**
  32966. * Gets or sets the morph target manager
  32967. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  32968. */
  32969. get: function () {
  32970. return this._morphTargetManager;
  32971. },
  32972. set: function (value) {
  32973. if (this._morphTargetManager === value) {
  32974. return;
  32975. }
  32976. this._morphTargetManager = value;
  32977. this._syncGeometryWithMorphTargetManager();
  32978. },
  32979. enumerable: true,
  32980. configurable: true
  32981. });
  32982. Object.defineProperty(Mesh.prototype, "source", {
  32983. /**
  32984. * Gets the source mesh (the one used to clone this one from)
  32985. */
  32986. get: function () {
  32987. return this._source;
  32988. },
  32989. enumerable: true,
  32990. configurable: true
  32991. });
  32992. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  32993. /**
  32994. * Gets or sets a boolean indicating that this mesh does not use index buffer
  32995. */
  32996. get: function () {
  32997. return this._unIndexed;
  32998. },
  32999. set: function (value) {
  33000. if (this._unIndexed !== value) {
  33001. this._unIndexed = value;
  33002. this._markSubMeshesAsAttributesDirty();
  33003. }
  33004. },
  33005. enumerable: true,
  33006. configurable: true
  33007. });
  33008. // Methods
  33009. /**
  33010. * Gets the class name
  33011. * @returns the string "Mesh".
  33012. */
  33013. Mesh.prototype.getClassName = function () {
  33014. return "Mesh";
  33015. };
  33016. /**
  33017. * Returns a description of this mesh
  33018. * @param fullDetails define if full details about this mesh must be used
  33019. * @returns a descriptive string representing this mesh
  33020. */
  33021. Mesh.prototype.toString = function (fullDetails) {
  33022. var ret = _super.prototype.toString.call(this, fullDetails);
  33023. ret += ", n vertices: " + this.getTotalVertices();
  33024. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  33025. if (this.animations) {
  33026. for (var i = 0; i < this.animations.length; i++) {
  33027. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  33028. }
  33029. }
  33030. if (fullDetails) {
  33031. if (this._geometry) {
  33032. var ib = this.getIndices();
  33033. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33034. if (vb && ib) {
  33035. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  33036. }
  33037. }
  33038. else {
  33039. ret += ", flat shading: UNKNOWN";
  33040. }
  33041. }
  33042. return ret;
  33043. };
  33044. /** @hidden */
  33045. Mesh.prototype._unBindEffect = function () {
  33046. _super.prototype._unBindEffect.call(this);
  33047. for (var _i = 0, _a = this.instances; _i < _a.length; _i++) {
  33048. var instance = _a[_i];
  33049. instance._unBindEffect();
  33050. }
  33051. };
  33052. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  33053. /**
  33054. * Gets a boolean indicating if this mesh has LOD
  33055. */
  33056. get: function () {
  33057. return this._LODLevels.length > 0;
  33058. },
  33059. enumerable: true,
  33060. configurable: true
  33061. });
  33062. /**
  33063. * Gets the list of MeshLODLevel associated with the current mesh
  33064. * @returns an array of MeshLODLevel
  33065. */
  33066. Mesh.prototype.getLODLevels = function () {
  33067. return this._LODLevels;
  33068. };
  33069. Mesh.prototype._sortLODLevels = function () {
  33070. this._LODLevels.sort(function (a, b) {
  33071. if (a.distance < b.distance) {
  33072. return 1;
  33073. }
  33074. if (a.distance > b.distance) {
  33075. return -1;
  33076. }
  33077. return 0;
  33078. });
  33079. };
  33080. /**
  33081. * Add a mesh as LOD level triggered at the given distance.
  33082. * @see https://doc.babylonjs.com/how_to/how_to_use_lod
  33083. * @param distance The distance from the center of the object to show this level
  33084. * @param mesh The mesh to be added as LOD level (can be null)
  33085. * @return This mesh (for chaining)
  33086. */
  33087. Mesh.prototype.addLODLevel = function (distance, mesh) {
  33088. if (mesh && mesh._masterMesh) {
  33089. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  33090. return this;
  33091. }
  33092. var level = new BABYLON.MeshLODLevel(distance, mesh);
  33093. this._LODLevels.push(level);
  33094. if (mesh) {
  33095. mesh._masterMesh = this;
  33096. }
  33097. this._sortLODLevels();
  33098. return this;
  33099. };
  33100. /**
  33101. * Returns the LOD level mesh at the passed distance or null if not found.
  33102. * @see https://doc.babylonjs.com/how_to/how_to_use_lod
  33103. * @param distance The distance from the center of the object to show this level
  33104. * @returns a Mesh or `null`
  33105. */
  33106. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  33107. for (var index = 0; index < this._LODLevels.length; index++) {
  33108. var level = this._LODLevels[index];
  33109. if (level.distance === distance) {
  33110. return level.mesh;
  33111. }
  33112. }
  33113. return null;
  33114. };
  33115. /**
  33116. * Remove a mesh from the LOD array
  33117. * @see https://doc.babylonjs.com/how_to/how_to_use_lod
  33118. * @param mesh defines the mesh to be removed
  33119. * @return This mesh (for chaining)
  33120. */
  33121. Mesh.prototype.removeLODLevel = function (mesh) {
  33122. for (var index = 0; index < this._LODLevels.length; index++) {
  33123. if (this._LODLevels[index].mesh === mesh) {
  33124. this._LODLevels.splice(index, 1);
  33125. if (mesh) {
  33126. mesh._masterMesh = null;
  33127. }
  33128. }
  33129. }
  33130. this._sortLODLevels();
  33131. return this;
  33132. };
  33133. /**
  33134. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  33135. * @see https://doc.babylonjs.com/how_to/how_to_use_lod
  33136. * @param camera defines the camera to use to compute distance
  33137. * @param boundingSphere defines a custom bounding sphere to use instead of the one from this mesh
  33138. * @return This mesh (for chaining)
  33139. */
  33140. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  33141. if (!this._LODLevels || this._LODLevels.length === 0) {
  33142. return this;
  33143. }
  33144. var bSphere;
  33145. if (boundingSphere) {
  33146. bSphere = boundingSphere;
  33147. }
  33148. else {
  33149. var boundingInfo = this.getBoundingInfo();
  33150. bSphere = boundingInfo.boundingSphere;
  33151. }
  33152. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  33153. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  33154. if (this.onLODLevelSelection) {
  33155. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  33156. }
  33157. return this;
  33158. }
  33159. for (var index = 0; index < this._LODLevels.length; index++) {
  33160. var level = this._LODLevels[index];
  33161. if (level.distance < distanceToCamera) {
  33162. if (level.mesh) {
  33163. level.mesh._preActivate();
  33164. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  33165. }
  33166. if (this.onLODLevelSelection) {
  33167. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  33168. }
  33169. return level.mesh;
  33170. }
  33171. }
  33172. if (this.onLODLevelSelection) {
  33173. this.onLODLevelSelection(distanceToCamera, this, this);
  33174. }
  33175. return this;
  33176. };
  33177. Object.defineProperty(Mesh.prototype, "geometry", {
  33178. /**
  33179. * Gets the mesh internal Geometry object
  33180. */
  33181. get: function () {
  33182. return this._geometry;
  33183. },
  33184. enumerable: true,
  33185. configurable: true
  33186. });
  33187. /**
  33188. * Returns the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  33189. * @returns the total number of vertices
  33190. */
  33191. Mesh.prototype.getTotalVertices = function () {
  33192. if (this._geometry === null || this._geometry === undefined) {
  33193. return 0;
  33194. }
  33195. return this._geometry.getTotalVertices();
  33196. };
  33197. /**
  33198. * Returns the content of an associated vertex buffer
  33199. * @param kind defines which buffer to read from (positions, indices, normals, etc). Possible `kind` values :
  33200. * - BABYLON.VertexBuffer.PositionKind
  33201. * - BABYLON.VertexBuffer.UVKind
  33202. * - BABYLON.VertexBuffer.UV2Kind
  33203. * - BABYLON.VertexBuffer.UV3Kind
  33204. * - BABYLON.VertexBuffer.UV4Kind
  33205. * - BABYLON.VertexBuffer.UV5Kind
  33206. * - BABYLON.VertexBuffer.UV6Kind
  33207. * - BABYLON.VertexBuffer.ColorKind
  33208. * - BABYLON.VertexBuffer.MatricesIndicesKind
  33209. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  33210. * - BABYLON.VertexBuffer.MatricesWeightsKind
  33211. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  33212. * @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
  33213. * @param forceCopy defines a boolean forcing the copy of the buffer no matter what the value of copyWhenShared is
  33214. * @returns a FloatArray or null if the mesh has no geometry or no vertex buffer for this kind.
  33215. */
  33216. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  33217. if (!this._geometry) {
  33218. return null;
  33219. }
  33220. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  33221. };
  33222. /**
  33223. * Returns the mesh VertexBuffer object from the requested `kind`
  33224. * @param kind defines which buffer to read from (positions, indices, normals, etc). Possible `kind` values :
  33225. * - BABYLON.VertexBuffer.PositionKind
  33226. * - BABYLON.VertexBuffer.UVKind
  33227. * - BABYLON.VertexBuffer.UV2Kind
  33228. * - BABYLON.VertexBuffer.UV3Kind
  33229. * - BABYLON.VertexBuffer.UV4Kind
  33230. * - BABYLON.VertexBuffer.UV5Kind
  33231. * - BABYLON.VertexBuffer.UV6Kind
  33232. * - BABYLON.VertexBuffer.ColorKind
  33233. * - BABYLON.VertexBuffer.MatricesIndicesKind
  33234. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  33235. * - BABYLON.VertexBuffer.MatricesWeightsKind
  33236. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  33237. * @returns a FloatArray or null if the mesh has no vertex buffer for this kind.
  33238. */
  33239. Mesh.prototype.getVertexBuffer = function (kind) {
  33240. if (!this._geometry) {
  33241. return null;
  33242. }
  33243. return this._geometry.getVertexBuffer(kind);
  33244. };
  33245. /**
  33246. * Tests if a specific vertex buffer is associated with this mesh
  33247. * @param kind defines which buffer to check (positions, indices, normals, etc). Possible `kind` values :
  33248. * - BABYLON.VertexBuffer.PositionKind
  33249. * - BABYLON.VertexBuffer.UVKind
  33250. * - BABYLON.VertexBuffer.UV2Kind
  33251. * - BABYLON.VertexBuffer.UV3Kind
  33252. * - BABYLON.VertexBuffer.UV4Kind
  33253. * - BABYLON.VertexBuffer.UV5Kind
  33254. * - BABYLON.VertexBuffer.UV6Kind
  33255. * - BABYLON.VertexBuffer.ColorKind
  33256. * - BABYLON.VertexBuffer.MatricesIndicesKind
  33257. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  33258. * - BABYLON.VertexBuffer.MatricesWeightsKind
  33259. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  33260. * @returns a boolean
  33261. */
  33262. Mesh.prototype.isVerticesDataPresent = function (kind) {
  33263. if (!this._geometry) {
  33264. if (this._delayInfo) {
  33265. return this._delayInfo.indexOf(kind) !== -1;
  33266. }
  33267. return false;
  33268. }
  33269. return this._geometry.isVerticesDataPresent(kind);
  33270. };
  33271. /**
  33272. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  33273. * @param kind defines which buffer to check (positions, indices, normals, etc). Possible `kind` values :
  33274. * - BABYLON.VertexBuffer.PositionKind
  33275. * - BABYLON.VertexBuffer.UVKind
  33276. * - BABYLON.VertexBuffer.UV2Kind
  33277. * - BABYLON.VertexBuffer.UV3Kind
  33278. * - BABYLON.VertexBuffer.UV4Kind
  33279. * - BABYLON.VertexBuffer.UV5Kind
  33280. * - BABYLON.VertexBuffer.UV6Kind
  33281. * - BABYLON.VertexBuffer.ColorKind
  33282. * - BABYLON.VertexBuffer.MatricesIndicesKind
  33283. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  33284. * - BABYLON.VertexBuffer.MatricesWeightsKind
  33285. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  33286. * @returns a boolean
  33287. */
  33288. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  33289. if (!this._geometry) {
  33290. if (this._delayInfo) {
  33291. return this._delayInfo.indexOf(kind) !== -1;
  33292. }
  33293. return false;
  33294. }
  33295. return this._geometry.isVertexBufferUpdatable(kind);
  33296. };
  33297. /**
  33298. * Returns a string which contains the list of existing `kinds` of Vertex Data associated with this mesh.
  33299. * @param kind defines which buffer to read from (positions, indices, normals, etc). Possible `kind` values :
  33300. * - BABYLON.VertexBuffer.PositionKind
  33301. * - BABYLON.VertexBuffer.UVKind
  33302. * - BABYLON.VertexBuffer.UV2Kind
  33303. * - BABYLON.VertexBuffer.UV3Kind
  33304. * - BABYLON.VertexBuffer.UV4Kind
  33305. * - BABYLON.VertexBuffer.UV5Kind
  33306. * - BABYLON.VertexBuffer.UV6Kind
  33307. * - BABYLON.VertexBuffer.ColorKind
  33308. * - BABYLON.VertexBuffer.MatricesIndicesKind
  33309. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  33310. * - BABYLON.VertexBuffer.MatricesWeightsKind
  33311. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  33312. * @returns an array of strings
  33313. */
  33314. Mesh.prototype.getVerticesDataKinds = function () {
  33315. if (!this._geometry) {
  33316. var result = new Array();
  33317. if (this._delayInfo) {
  33318. this._delayInfo.forEach(function (kind, index, array) {
  33319. result.push(kind);
  33320. });
  33321. }
  33322. return result;
  33323. }
  33324. return this._geometry.getVerticesDataKinds();
  33325. };
  33326. /**
  33327. * Returns a positive integer : the total number of indices in this mesh geometry.
  33328. * @returns the numner of indices or zero if the mesh has no geometry.
  33329. */
  33330. Mesh.prototype.getTotalIndices = function () {
  33331. if (!this._geometry) {
  33332. return 0;
  33333. }
  33334. return this._geometry.getTotalIndices();
  33335. };
  33336. /**
  33337. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  33338. * @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.
  33339. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  33340. * @returns the indices array or an empty array if the mesh has no geometry
  33341. */
  33342. Mesh.prototype.getIndices = function (copyWhenShared, forceCopy) {
  33343. if (!this._geometry) {
  33344. return [];
  33345. }
  33346. return this._geometry.getIndices(copyWhenShared, forceCopy);
  33347. };
  33348. Object.defineProperty(Mesh.prototype, "isBlocked", {
  33349. get: function () {
  33350. return this._masterMesh !== null && this._masterMesh !== undefined;
  33351. },
  33352. enumerable: true,
  33353. configurable: true
  33354. });
  33355. /**
  33356. * Determine if the current mesh is ready to be rendered
  33357. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  33358. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  33359. * @returns true if all associated assets are ready (material, textures, shaders)
  33360. */
  33361. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  33362. if (completeCheck === void 0) { completeCheck = false; }
  33363. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  33364. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  33365. return false;
  33366. }
  33367. if (!_super.prototype.isReady.call(this, completeCheck)) {
  33368. return false;
  33369. }
  33370. if (!this.subMeshes || this.subMeshes.length === 0) {
  33371. return true;
  33372. }
  33373. if (!completeCheck) {
  33374. return true;
  33375. }
  33376. var engine = this.getEngine();
  33377. var scene = this.getScene();
  33378. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  33379. this.computeWorldMatrix();
  33380. var mat = this.material || scene.defaultMaterial;
  33381. if (mat) {
  33382. if (mat._storeEffectOnSubMeshes) {
  33383. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  33384. var subMesh = _a[_i];
  33385. var effectiveMaterial = subMesh.getMaterial();
  33386. if (effectiveMaterial) {
  33387. if (effectiveMaterial._storeEffectOnSubMeshes) {
  33388. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  33389. return false;
  33390. }
  33391. }
  33392. else {
  33393. if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  33394. return false;
  33395. }
  33396. }
  33397. }
  33398. }
  33399. }
  33400. else {
  33401. if (!mat.isReady(this, hardwareInstancedRendering)) {
  33402. return false;
  33403. }
  33404. }
  33405. }
  33406. // Shadows
  33407. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  33408. var light = _c[_b];
  33409. var generator = light.getShadowGenerator();
  33410. if (generator) {
  33411. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  33412. var subMesh = _e[_d];
  33413. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  33414. return false;
  33415. }
  33416. }
  33417. }
  33418. }
  33419. // LOD
  33420. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  33421. var lod = _g[_f];
  33422. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  33423. return false;
  33424. }
  33425. }
  33426. return true;
  33427. };
  33428. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  33429. /**
  33430. * 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.
  33431. */
  33432. get: function () {
  33433. return this._areNormalsFrozen;
  33434. },
  33435. enumerable: true,
  33436. configurable: true
  33437. });
  33438. /**
  33439. * 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.
  33440. * @returns the current mesh
  33441. */
  33442. Mesh.prototype.freezeNormals = function () {
  33443. this._areNormalsFrozen = true;
  33444. return this;
  33445. };
  33446. /**
  33447. * 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
  33448. * @returns the current mesh
  33449. */
  33450. Mesh.prototype.unfreezeNormals = function () {
  33451. this._areNormalsFrozen = false;
  33452. return this;
  33453. };
  33454. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  33455. /**
  33456. * Sets a value overriding the instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  33457. */
  33458. set: function (count) {
  33459. this._instanceDataStorage.overridenInstanceCount = count;
  33460. },
  33461. enumerable: true,
  33462. configurable: true
  33463. });
  33464. // Methods
  33465. /** @hidden */
  33466. Mesh.prototype._preActivate = function () {
  33467. var sceneRenderId = this.getScene().getRenderId();
  33468. if (this._preActivateId === sceneRenderId) {
  33469. return this;
  33470. }
  33471. this._preActivateId = sceneRenderId;
  33472. this._instanceDataStorage.visibleInstances = null;
  33473. return this;
  33474. };
  33475. /** @hidden */
  33476. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  33477. if (this._instanceDataStorage.visibleInstances) {
  33478. this._instanceDataStorage.visibleInstances.intermediateDefaultRenderId = renderId;
  33479. }
  33480. return this;
  33481. };
  33482. /** @hidden */
  33483. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  33484. if (!this._instanceDataStorage.visibleInstances) {
  33485. this._instanceDataStorage.visibleInstances = {
  33486. defaultRenderId: renderId,
  33487. selfDefaultRenderId: this._renderId
  33488. };
  33489. }
  33490. if (!this._instanceDataStorage.visibleInstances[renderId]) {
  33491. this._instanceDataStorage.visibleInstances[renderId] = new Array();
  33492. }
  33493. this._instanceDataStorage.visibleInstances[renderId].push(instance);
  33494. return this;
  33495. };
  33496. /**
  33497. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  33498. * This means the mesh underlying bounding box and sphere are recomputed.
  33499. * @param applySkeleton defines whether to apply the skeleton before computing the bounding info
  33500. * @returns the current mesh
  33501. */
  33502. Mesh.prototype.refreshBoundingInfo = function (applySkeleton) {
  33503. if (applySkeleton === void 0) { applySkeleton = false; }
  33504. if (this._boundingInfo && this._boundingInfo.isLocked) {
  33505. return this;
  33506. }
  33507. var bias = this.geometry ? this.geometry.boundingBias : null;
  33508. this._refreshBoundingInfo(this._getPositionData(applySkeleton), bias);
  33509. return this;
  33510. };
  33511. /** @hidden */
  33512. Mesh.prototype._createGlobalSubMesh = function (force) {
  33513. var totalVertices = this.getTotalVertices();
  33514. if (!totalVertices || !this.getIndices()) {
  33515. return null;
  33516. }
  33517. // Check if we need to recreate the submeshes
  33518. if (this.subMeshes && this.subMeshes.length > 0) {
  33519. var ib = this.getIndices();
  33520. if (!ib) {
  33521. return null;
  33522. }
  33523. var totalIndices = ib.length;
  33524. var needToRecreate = false;
  33525. if (force) {
  33526. needToRecreate = true;
  33527. }
  33528. else {
  33529. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  33530. var submesh = _a[_i];
  33531. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  33532. needToRecreate = true;
  33533. break;
  33534. }
  33535. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  33536. needToRecreate = true;
  33537. break;
  33538. }
  33539. }
  33540. }
  33541. if (!needToRecreate) {
  33542. return this.subMeshes[0];
  33543. }
  33544. }
  33545. this.releaseSubMeshes();
  33546. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  33547. };
  33548. /**
  33549. * This function will subdivide the mesh into multiple submeshes
  33550. * @param count defines the expected number of submeshes
  33551. */
  33552. Mesh.prototype.subdivide = function (count) {
  33553. if (count < 1) {
  33554. return;
  33555. }
  33556. var totalIndices = this.getTotalIndices();
  33557. var subdivisionSize = (totalIndices / count) | 0;
  33558. var offset = 0;
  33559. // Ensure that subdivisionSize is a multiple of 3
  33560. while (subdivisionSize % 3 !== 0) {
  33561. subdivisionSize++;
  33562. }
  33563. this.releaseSubMeshes();
  33564. for (var index = 0; index < count; index++) {
  33565. if (offset >= totalIndices) {
  33566. break;
  33567. }
  33568. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  33569. offset += subdivisionSize;
  33570. }
  33571. this.synchronizeInstances();
  33572. };
  33573. /**
  33574. * Copy a FloatArray into a specific associated vertex buffer
  33575. * @param kind defines which buffer to write to (positions, indices, normals, etc). Possible `kind` values :
  33576. * - BABYLON.VertexBuffer.PositionKind
  33577. * - BABYLON.VertexBuffer.UVKind
  33578. * - BABYLON.VertexBuffer.UV2Kind
  33579. * - BABYLON.VertexBuffer.UV3Kind
  33580. * - BABYLON.VertexBuffer.UV4Kind
  33581. * - BABYLON.VertexBuffer.UV5Kind
  33582. * - BABYLON.VertexBuffer.UV6Kind
  33583. * - BABYLON.VertexBuffer.ColorKind
  33584. * - BABYLON.VertexBuffer.MatricesIndicesKind
  33585. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  33586. * - BABYLON.VertexBuffer.MatricesWeightsKind
  33587. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  33588. * @param data defines the data source
  33589. * @param updatable defines if the updated vertex buffer must be flagged as updatable
  33590. * @param stride defines the data stride size (can be null)
  33591. * @returns the current mesh
  33592. */
  33593. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  33594. if (updatable === void 0) { updatable = false; }
  33595. if (!this._geometry) {
  33596. var vertexData = new BABYLON.VertexData();
  33597. vertexData.set(data, kind);
  33598. var scene = this.getScene();
  33599. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  33600. }
  33601. else {
  33602. this._geometry.setVerticesData(kind, data, updatable, stride);
  33603. }
  33604. return this;
  33605. };
  33606. /**
  33607. * Flags an associated vertex buffer as updatable
  33608. * @param kind defines which buffer to use (positions, indices, normals, etc). Possible `kind` values :
  33609. * - BABYLON.VertexBuffer.PositionKind
  33610. * - BABYLON.VertexBuffer.UVKind
  33611. * - BABYLON.VertexBuffer.UV2Kind
  33612. * - BABYLON.VertexBuffer.UV3Kind
  33613. * - BABYLON.VertexBuffer.UV4Kind
  33614. * - BABYLON.VertexBuffer.UV5Kind
  33615. * - BABYLON.VertexBuffer.UV6Kind
  33616. * - BABYLON.VertexBuffer.ColorKind
  33617. * - BABYLON.VertexBuffer.MatricesIndicesKind
  33618. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  33619. * - BABYLON.VertexBuffer.MatricesWeightsKind
  33620. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  33621. * @param updatable defines if the updated vertex buffer must be flagged as updatable
  33622. */
  33623. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  33624. if (updatable === void 0) { updatable = true; }
  33625. var vb = this.getVertexBuffer(kind);
  33626. if (!vb || vb.isUpdatable() === updatable) {
  33627. return;
  33628. }
  33629. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  33630. };
  33631. /**
  33632. * Sets the mesh global Vertex Buffer
  33633. * @param buffer defines the buffer to use
  33634. * @returns the current mesh
  33635. */
  33636. Mesh.prototype.setVerticesBuffer = function (buffer) {
  33637. if (!this._geometry) {
  33638. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  33639. }
  33640. this._geometry.setVerticesBuffer(buffer);
  33641. return this;
  33642. };
  33643. /**
  33644. * Update a specific associated vertex buffer
  33645. * @param kind defines which buffer to write to (positions, indices, normals, etc). Possible `kind` values :
  33646. * - BABYLON.VertexBuffer.PositionKind
  33647. * - BABYLON.VertexBuffer.UVKind
  33648. * - BABYLON.VertexBuffer.UV2Kind
  33649. * - BABYLON.VertexBuffer.UV3Kind
  33650. * - BABYLON.VertexBuffer.UV4Kind
  33651. * - BABYLON.VertexBuffer.UV5Kind
  33652. * - BABYLON.VertexBuffer.UV6Kind
  33653. * - BABYLON.VertexBuffer.ColorKind
  33654. * - BABYLON.VertexBuffer.MatricesIndicesKind
  33655. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  33656. * - BABYLON.VertexBuffer.MatricesWeightsKind
  33657. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  33658. * @param data defines the data source
  33659. * @param updateExtends defines if extends info of the mesh must be updated (can be null). This is mostly useful for "position" kind
  33660. * @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)
  33661. * @returns the current mesh
  33662. */
  33663. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  33664. if (!this._geometry) {
  33665. return this;
  33666. }
  33667. if (!makeItUnique) {
  33668. this._geometry.updateVerticesData(kind, data, updateExtends);
  33669. }
  33670. else {
  33671. this.makeGeometryUnique();
  33672. this.updateVerticesData(kind, data, updateExtends, false);
  33673. }
  33674. return this;
  33675. };
  33676. /**
  33677. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  33678. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  33679. * @param positionFunction is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything
  33680. * @param computeNormals is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update
  33681. * @returns the current mesh
  33682. */
  33683. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  33684. if (computeNormals === void 0) { computeNormals = true; }
  33685. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33686. if (!positions) {
  33687. return this;
  33688. }
  33689. positionFunction(positions);
  33690. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  33691. if (computeNormals) {
  33692. var indices = this.getIndices();
  33693. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33694. if (!normals) {
  33695. return this;
  33696. }
  33697. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  33698. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  33699. }
  33700. return this;
  33701. };
  33702. /**
  33703. * Creates a un-shared specific occurence of the geometry for the mesh.
  33704. * @returns the current mesh
  33705. */
  33706. Mesh.prototype.makeGeometryUnique = function () {
  33707. if (!this._geometry) {
  33708. return this;
  33709. }
  33710. var oldGeometry = this._geometry;
  33711. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  33712. oldGeometry.releaseForMesh(this, true);
  33713. geometry.applyToMesh(this);
  33714. return this;
  33715. };
  33716. /**
  33717. * Set the index buffer of this mesh
  33718. * @param indices defines the source data
  33719. * @param totalVertices defines the total number of vertices referenced by this index data (can be null)
  33720. * @param updatable defines if the updated index buffer must be flagged as updatable (default is false)
  33721. * @returns the current mesh
  33722. */
  33723. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  33724. if (totalVertices === void 0) { totalVertices = null; }
  33725. if (updatable === void 0) { updatable = false; }
  33726. if (!this._geometry) {
  33727. var vertexData = new BABYLON.VertexData();
  33728. vertexData.indices = indices;
  33729. var scene = this.getScene();
  33730. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  33731. }
  33732. else {
  33733. this._geometry.setIndices(indices, totalVertices, updatable);
  33734. }
  33735. return this;
  33736. };
  33737. /**
  33738. * Update the current index buffer
  33739. * @param indices defines the source data
  33740. * @param offset defines the offset in the index buffer where to store the new data (can be null)
  33741. * @returns the current mesh
  33742. */
  33743. Mesh.prototype.updateIndices = function (indices, offset) {
  33744. if (!this._geometry) {
  33745. return this;
  33746. }
  33747. this._geometry.updateIndices(indices, offset);
  33748. return this;
  33749. };
  33750. /**
  33751. * Invert the geometry to move from a right handed system to a left handed one.
  33752. * @returns the current mesh
  33753. */
  33754. Mesh.prototype.toLeftHanded = function () {
  33755. if (!this._geometry) {
  33756. return this;
  33757. }
  33758. this._geometry.toLeftHanded();
  33759. return this;
  33760. };
  33761. /** @hidden */
  33762. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  33763. if (!this._geometry) {
  33764. return this;
  33765. }
  33766. var engine = this.getScene().getEngine();
  33767. // Wireframe
  33768. var indexToBind;
  33769. if (this._unIndexed) {
  33770. indexToBind = null;
  33771. }
  33772. else {
  33773. switch (fillMode) {
  33774. case BABYLON.Material.PointFillMode:
  33775. indexToBind = null;
  33776. break;
  33777. case BABYLON.Material.WireFrameFillMode:
  33778. indexToBind = subMesh._getLinesIndexBuffer(this.getIndices(), engine);
  33779. break;
  33780. default:
  33781. case BABYLON.Material.TriangleFillMode:
  33782. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  33783. break;
  33784. }
  33785. }
  33786. // VBOs
  33787. this._geometry._bind(effect, indexToBind);
  33788. return this;
  33789. };
  33790. /** @hidden */
  33791. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  33792. if (alternate === void 0) { alternate = false; }
  33793. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  33794. return this;
  33795. }
  33796. if (this._onBeforeDrawObservable) {
  33797. this._onBeforeDrawObservable.notifyObservers(this);
  33798. }
  33799. var scene = this.getScene();
  33800. var engine = scene.getEngine();
  33801. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  33802. // or triangles as points
  33803. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  33804. }
  33805. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  33806. // Triangles as wireframe
  33807. engine.drawElementsType(fillMode, 0, subMesh._linesIndexCount, instancesCount);
  33808. }
  33809. else {
  33810. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  33811. }
  33812. if (scene._isAlternateRenderingEnabled && !alternate) {
  33813. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  33814. if (!effect || !scene.activeCamera) {
  33815. return this;
  33816. }
  33817. scene._switchToAlternateCameraConfiguration(true);
  33818. this._effectiveMaterial.bindView(effect);
  33819. this._effectiveMaterial.bindViewProjection(effect);
  33820. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  33821. this._draw(subMesh, fillMode, instancesCount, true);
  33822. engine.setViewport(scene.activeCamera.viewport);
  33823. scene._switchToAlternateCameraConfiguration(false);
  33824. this._effectiveMaterial.bindView(effect);
  33825. this._effectiveMaterial.bindViewProjection(effect);
  33826. }
  33827. return this;
  33828. };
  33829. /**
  33830. * Registers for this mesh a javascript function called just before the rendering process
  33831. * @param func defines the function to call before rendering this mesh
  33832. * @returns the current mesh
  33833. */
  33834. Mesh.prototype.registerBeforeRender = function (func) {
  33835. this.onBeforeRenderObservable.add(func);
  33836. return this;
  33837. };
  33838. /**
  33839. * Disposes a previously registered javascript function called before the rendering
  33840. * @param func defines the function to remove
  33841. * @returns the current mesh
  33842. */
  33843. Mesh.prototype.unregisterBeforeRender = function (func) {
  33844. this.onBeforeRenderObservable.removeCallback(func);
  33845. return this;
  33846. };
  33847. /**
  33848. * Registers for this mesh a javascript function called just after the rendering is complete
  33849. * @param func defines the function to call after rendering this mesh
  33850. * @returns the current mesh
  33851. */
  33852. Mesh.prototype.registerAfterRender = function (func) {
  33853. this.onAfterRenderObservable.add(func);
  33854. return this;
  33855. };
  33856. /**
  33857. * Disposes a previously registered javascript function called after the rendering.
  33858. * @param func defines the function to remove
  33859. * @returns the current mesh
  33860. */
  33861. Mesh.prototype.unregisterAfterRender = function (func) {
  33862. this.onAfterRenderObservable.removeCallback(func);
  33863. return this;
  33864. };
  33865. /** @hidden */
  33866. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  33867. var scene = this.getScene();
  33868. var batchCache = this._instanceDataStorage.batchCache;
  33869. batchCache.mustReturn = false;
  33870. batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  33871. batchCache.visibleInstances[subMeshId] = null;
  33872. if (this._instanceDataStorage.visibleInstances) {
  33873. var visibleInstances = this._instanceDataStorage.visibleInstances;
  33874. var currentRenderId = scene.getRenderId();
  33875. var defaultRenderId = (scene._isInIntermediateRendering() ? visibleInstances.intermediateDefaultRenderId : visibleInstances.defaultRenderId);
  33876. batchCache.visibleInstances[subMeshId] = visibleInstances[currentRenderId];
  33877. var selfRenderId = this._renderId;
  33878. if (!batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  33879. batchCache.visibleInstances[subMeshId] = visibleInstances[defaultRenderId];
  33880. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  33881. selfRenderId = Math.max(visibleInstances.selfDefaultRenderId, currentRenderId);
  33882. }
  33883. var visibleInstancesForSubMesh = batchCache.visibleInstances[subMeshId];
  33884. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  33885. if (this._instanceDataStorage.renderIdForInstances[subMeshId] === currentRenderId) {
  33886. batchCache.mustReturn = true;
  33887. return batchCache;
  33888. }
  33889. if (currentRenderId !== selfRenderId) {
  33890. batchCache.renderSelf[subMeshId] = false;
  33891. }
  33892. }
  33893. this._instanceDataStorage.renderIdForInstances[subMeshId] = currentRenderId;
  33894. }
  33895. return batchCache;
  33896. };
  33897. /** @hidden */
  33898. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  33899. var visibleInstances = batch.visibleInstances[subMesh._id];
  33900. if (!visibleInstances) {
  33901. return this;
  33902. }
  33903. var matricesCount = visibleInstances.length + 1;
  33904. var bufferSize = matricesCount * 16 * 4;
  33905. var instanceStorage = this._instanceDataStorage;
  33906. var currentInstancesBufferSize = instanceStorage.instancesBufferSize;
  33907. var instancesBuffer = instanceStorage.instancesBuffer;
  33908. while (instanceStorage.instancesBufferSize < bufferSize) {
  33909. instanceStorage.instancesBufferSize *= 2;
  33910. }
  33911. if (!instanceStorage.instancesData || currentInstancesBufferSize != instanceStorage.instancesBufferSize) {
  33912. instanceStorage.instancesData = new Float32Array(instanceStorage.instancesBufferSize / 4);
  33913. }
  33914. var offset = 0;
  33915. var instancesCount = 0;
  33916. var world = this.getWorldMatrix();
  33917. if (batch.renderSelf[subMesh._id]) {
  33918. world.copyToArray(instanceStorage.instancesData, offset);
  33919. offset += 16;
  33920. instancesCount++;
  33921. }
  33922. if (visibleInstances) {
  33923. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  33924. var instance = visibleInstances[instanceIndex];
  33925. instance.getWorldMatrix().copyToArray(instanceStorage.instancesData, offset);
  33926. offset += 16;
  33927. instancesCount++;
  33928. }
  33929. }
  33930. if (!instancesBuffer || currentInstancesBufferSize != instanceStorage.instancesBufferSize) {
  33931. if (instancesBuffer) {
  33932. instancesBuffer.dispose();
  33933. }
  33934. instancesBuffer = new BABYLON.Buffer(engine, instanceStorage.instancesData, true, 16, false, true);
  33935. instanceStorage.instancesBuffer = instancesBuffer;
  33936. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  33937. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  33938. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  33939. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  33940. }
  33941. else {
  33942. instancesBuffer.updateDirectly(instanceStorage.instancesData, 0, instancesCount);
  33943. }
  33944. this._bind(subMesh, effect, fillMode);
  33945. this._draw(subMesh, fillMode, instancesCount);
  33946. engine.unbindInstanceAttributes();
  33947. return this;
  33948. };
  33949. /** @hidden */
  33950. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  33951. var scene = this.getScene();
  33952. var engine = scene.getEngine();
  33953. if (hardwareInstancedRendering) {
  33954. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  33955. }
  33956. else {
  33957. if (batch.renderSelf[subMesh._id]) {
  33958. // Draw
  33959. if (onBeforeDraw) {
  33960. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  33961. }
  33962. this._draw(subMesh, fillMode, this._instanceDataStorage.overridenInstanceCount);
  33963. }
  33964. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  33965. if (visibleInstancesForSubMesh) {
  33966. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  33967. var instance = visibleInstancesForSubMesh[instanceIndex];
  33968. // World
  33969. var world = instance.getWorldMatrix();
  33970. if (onBeforeDraw) {
  33971. onBeforeDraw(true, world, effectiveMaterial);
  33972. }
  33973. // Draw
  33974. this._draw(subMesh, fillMode);
  33975. }
  33976. }
  33977. }
  33978. return this;
  33979. };
  33980. /**
  33981. * 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
  33982. * @param subMesh defines the subMesh to render
  33983. * @param enableAlphaMode defines if alpha mode can be changed
  33984. * @returns the current mesh
  33985. */
  33986. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  33987. if (this._checkOcclusionQuery()) {
  33988. return this;
  33989. }
  33990. var scene = this.getScene();
  33991. // Managing instances
  33992. var batch = this._getInstancesRenderList(subMesh._id);
  33993. if (batch.mustReturn) {
  33994. return this;
  33995. }
  33996. // Checking geometry state
  33997. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  33998. return this;
  33999. }
  34000. if (this._onBeforeRenderObservable) {
  34001. this._onBeforeRenderObservable.notifyObservers(this);
  34002. }
  34003. var engine = scene.getEngine();
  34004. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  34005. // Material
  34006. var material = subMesh.getMaterial();
  34007. if (!material) {
  34008. return this;
  34009. }
  34010. this._effectiveMaterial = material;
  34011. if (this._effectiveMaterial._storeEffectOnSubMeshes) {
  34012. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  34013. return this;
  34014. }
  34015. }
  34016. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  34017. return this;
  34018. }
  34019. // Alpha mode
  34020. if (enableAlphaMode) {
  34021. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  34022. }
  34023. for (var _i = 0, _a = scene._beforeRenderingMeshStage; _i < _a.length; _i++) {
  34024. var step = _a[_i];
  34025. step.action(this, subMesh, batch);
  34026. }
  34027. var effect;
  34028. if (this._effectiveMaterial._storeEffectOnSubMeshes) {
  34029. effect = subMesh.effect;
  34030. }
  34031. else {
  34032. effect = this._effectiveMaterial.getEffect();
  34033. }
  34034. if (!effect) {
  34035. return this;
  34036. }
  34037. var sideOrientation = this.overrideMaterialSideOrientation;
  34038. if (sideOrientation == null) {
  34039. sideOrientation = this._effectiveMaterial.sideOrientation;
  34040. if (this._getWorldMatrixDeterminant() < 0) {
  34041. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  34042. }
  34043. }
  34044. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  34045. if (this._effectiveMaterial.forceDepthWrite) {
  34046. engine.setDepthWrite(true);
  34047. }
  34048. // Bind
  34049. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  34050. if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB
  34051. this._bind(subMesh, effect, fillMode);
  34052. }
  34053. var world = this.getWorldMatrix();
  34054. if (this._effectiveMaterial._storeEffectOnSubMeshes) {
  34055. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  34056. }
  34057. else {
  34058. this._effectiveMaterial.bind(world, this);
  34059. }
  34060. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  34061. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  34062. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  34063. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  34064. }
  34065. // Draw
  34066. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  34067. // Unbind
  34068. this._effectiveMaterial.unbind();
  34069. for (var _b = 0, _c = scene._afterRenderingMeshStage; _b < _c.length; _b++) {
  34070. var step = _c[_b];
  34071. step.action(this, subMesh, batch);
  34072. }
  34073. if (this._onAfterRenderObservable) {
  34074. this._onAfterRenderObservable.notifyObservers(this);
  34075. }
  34076. return this;
  34077. };
  34078. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  34079. if (isInstance && effectiveMaterial) {
  34080. effectiveMaterial.bindOnlyWorldMatrix(world);
  34081. }
  34082. };
  34083. /**
  34084. * Renormalize the mesh and patch it up if there are no weights
  34085. * Similar to normalization by adding the weights compute the reciprocal and multiply all elements, this wil ensure that everything adds to 1.
  34086. * However in the case of zero weights then we set just a single influence to 1.
  34087. * We check in the function for extra's present and if so we use the normalizeSkinWeightsWithExtras rather than the FourWeights version.
  34088. */
  34089. Mesh.prototype.cleanMatrixWeights = function () {
  34090. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  34091. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  34092. this.normalizeSkinWeightsAndExtra();
  34093. }
  34094. else {
  34095. this.normalizeSkinFourWeights();
  34096. }
  34097. }
  34098. };
  34099. // faster 4 weight version.
  34100. Mesh.prototype.normalizeSkinFourWeights = function () {
  34101. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  34102. var numWeights = matricesWeights.length;
  34103. for (var a = 0; a < numWeights; a += 4) {
  34104. // accumulate weights
  34105. var t = matricesWeights[a] + matricesWeights[a + 1] + matricesWeights[a + 2] + matricesWeights[a + 3];
  34106. // check for invalid weight and just set it to 1.
  34107. if (t === 0) {
  34108. matricesWeights[a] = 1;
  34109. }
  34110. else {
  34111. // renormalize so everything adds to 1 use reciprical
  34112. var recip = 1 / t;
  34113. matricesWeights[a] *= recip;
  34114. matricesWeights[a + 1] *= recip;
  34115. matricesWeights[a + 2] *= recip;
  34116. matricesWeights[a + 3] *= recip;
  34117. }
  34118. }
  34119. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeights);
  34120. };
  34121. // handle special case of extra verts. (in theory gltf can handle 12 influences)
  34122. Mesh.prototype.normalizeSkinWeightsAndExtra = function () {
  34123. var matricesWeightsExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  34124. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  34125. var numWeights = matricesWeights.length;
  34126. for (var a = 0; a < numWeights; a += 4) {
  34127. // accumulate weights
  34128. var t = matricesWeights[a] + matricesWeights[a + 1] + matricesWeights[a + 2] + matricesWeights[a + 3];
  34129. t += matricesWeightsExtra[a] + matricesWeightsExtra[a + 1] + matricesWeightsExtra[a + 2] + matricesWeightsExtra[a + 3];
  34130. // check for invalid weight and just set it to 1.
  34131. if (t === 0) {
  34132. matricesWeights[a] = 1;
  34133. }
  34134. else {
  34135. // renormalize so everything adds to 1 use reciprical
  34136. var recip = 1 / t;
  34137. matricesWeights[a] *= recip;
  34138. matricesWeights[a + 1] *= recip;
  34139. matricesWeights[a + 2] *= recip;
  34140. matricesWeights[a + 3] *= recip;
  34141. // same goes for extras
  34142. matricesWeightsExtra[a] *= recip;
  34143. matricesWeightsExtra[a + 1] *= recip;
  34144. matricesWeightsExtra[a + 2] *= recip;
  34145. matricesWeightsExtra[a + 3] *= recip;
  34146. }
  34147. }
  34148. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeights);
  34149. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsExtra);
  34150. };
  34151. /**
  34152. * ValidateSkinning is used to determine that a mesh has valid skinning data along with skin metrics, if missing weights,
  34153. * or not normalized it is returned as invalid mesh the string can be used for console logs, or on screen messages to let
  34154. * the user know there was an issue with importing the mesh
  34155. * @returns a validation object with skinned, valid and report string
  34156. */
  34157. Mesh.prototype.validateSkinning = function () {
  34158. var matricesWeightsExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  34159. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  34160. if (matricesWeights === null || this.skeleton == null) {
  34161. return { skinned: false, valid: true, report: "not skinned" };
  34162. }
  34163. var numWeights = matricesWeights.length;
  34164. var numberNotSorted = 0;
  34165. var missingWeights = 0;
  34166. var maxUsedWeights = 0;
  34167. var numberNotNormalized = 0;
  34168. var numInfluences = matricesWeightsExtra === null ? 4 : 8;
  34169. var usedWeightCounts = new Array();
  34170. for (var a = 0; a <= numInfluences; a++) {
  34171. usedWeightCounts[a] = 0;
  34172. }
  34173. var toleranceEpsilon = 0.001;
  34174. for (var a = 0; a < numWeights; a += 4) {
  34175. var lastWeight = matricesWeights[a];
  34176. var t = lastWeight;
  34177. var usedWeights = t === 0 ? 0 : 1;
  34178. for (var b = 1; b < numInfluences; b++) {
  34179. var d = b < 4 ? matricesWeights[a + b] : matricesWeightsExtra[a + b - 4];
  34180. if (d > lastWeight) {
  34181. numberNotSorted++;
  34182. }
  34183. if (d !== 0) {
  34184. usedWeights++;
  34185. }
  34186. t += d;
  34187. lastWeight = d;
  34188. }
  34189. // count the buffer weights usage
  34190. usedWeightCounts[usedWeights]++;
  34191. // max influences
  34192. if (usedWeights > maxUsedWeights) {
  34193. maxUsedWeights = usedWeights;
  34194. }
  34195. // check for invalid weight and just set it to 1.
  34196. if (t === 0) {
  34197. missingWeights++;
  34198. }
  34199. else {
  34200. // renormalize so everything adds to 1 use reciprical
  34201. var recip = 1 / t;
  34202. var tolerance = 0;
  34203. for (b = 0; b < numInfluences; b++) {
  34204. if (b < 4) {
  34205. tolerance += Math.abs(matricesWeights[a + b] - (matricesWeights[a + b] * recip));
  34206. }
  34207. else {
  34208. tolerance += Math.abs(matricesWeightsExtra[a + b - 4] - (matricesWeightsExtra[a + b - 4] * recip));
  34209. }
  34210. }
  34211. // arbitary epsilon value for dicdating not normalized
  34212. if (tolerance > toleranceEpsilon) {
  34213. numberNotNormalized++;
  34214. }
  34215. }
  34216. }
  34217. // validate bone indices are in range of the skeleton
  34218. var numBones = this.skeleton.bones.length;
  34219. var matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  34220. var matricesIndicesExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  34221. var numBadBoneIndices = 0;
  34222. for (var a = 0; a < numWeights; a++) {
  34223. for (var b = 0; b < numInfluences; b++) {
  34224. var index = b < 4 ? matricesIndices[b] : matricesIndicesExtra[b - 4];
  34225. if (index >= numBones || index < 0) {
  34226. numBadBoneIndices++;
  34227. }
  34228. }
  34229. }
  34230. // log mesh stats
  34231. var output = "Number of Weights = " + numWeights / 4 + "\nMaximum influences = " + maxUsedWeights +
  34232. "\nMissing Weights = " + missingWeights + "\nNot Sorted = " + numberNotSorted +
  34233. "\nNot Normalized = " + numberNotNormalized + "\nWeightCounts = [" + usedWeightCounts + "]" +
  34234. "\nNumber of bones = " + numBones + "\nBad Bone Indices = " + numBadBoneIndices;
  34235. return { skinned: true, valid: missingWeights === 0 && numberNotNormalized === 0 && numBadBoneIndices === 0, report: output };
  34236. };
  34237. /** @hidden */
  34238. Mesh.prototype._checkDelayState = function () {
  34239. var scene = this.getScene();
  34240. if (this._geometry) {
  34241. this._geometry.load(scene);
  34242. }
  34243. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  34244. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  34245. this._queueLoad(scene);
  34246. }
  34247. return this;
  34248. };
  34249. Mesh.prototype._queueLoad = function (scene) {
  34250. var _this = this;
  34251. scene._addPendingData(this);
  34252. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  34253. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  34254. if (data instanceof ArrayBuffer) {
  34255. _this._delayLoadingFunction(data, _this);
  34256. }
  34257. else {
  34258. _this._delayLoadingFunction(JSON.parse(data), _this);
  34259. }
  34260. _this.instances.forEach(function (instance) {
  34261. instance._syncSubMeshes();
  34262. });
  34263. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  34264. scene._removePendingData(_this);
  34265. }, function () { }, scene.offlineProvider, getBinaryData);
  34266. return this;
  34267. };
  34268. /**
  34269. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  34270. * A mesh is in the frustum if its bounding box intersects the frustum
  34271. * @param frustumPlanes defines the frustum to test
  34272. * @returns true if the mesh is in the frustum planes
  34273. */
  34274. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  34275. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  34276. return false;
  34277. }
  34278. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  34279. return false;
  34280. }
  34281. this._checkDelayState();
  34282. return true;
  34283. };
  34284. /**
  34285. * Sets the mesh material by the material or multiMaterial `id` property
  34286. * @param id is a string identifying the material or the multiMaterial
  34287. * @returns the current mesh
  34288. */
  34289. Mesh.prototype.setMaterialByID = function (id) {
  34290. var materials = this.getScene().materials;
  34291. var index;
  34292. for (index = materials.length - 1; index > -1; index--) {
  34293. if (materials[index].id === id) {
  34294. this.material = materials[index];
  34295. return this;
  34296. }
  34297. }
  34298. // Multi
  34299. var multiMaterials = this.getScene().multiMaterials;
  34300. for (index = multiMaterials.length - 1; index > -1; index--) {
  34301. if (multiMaterials[index].id === id) {
  34302. this.material = multiMaterials[index];
  34303. return this;
  34304. }
  34305. }
  34306. return this;
  34307. };
  34308. /**
  34309. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  34310. * @returns an array of IAnimatable
  34311. */
  34312. Mesh.prototype.getAnimatables = function () {
  34313. var results = new Array();
  34314. if (this.material) {
  34315. results.push(this.material);
  34316. }
  34317. if (this.skeleton) {
  34318. results.push(this.skeleton);
  34319. }
  34320. return results;
  34321. };
  34322. /**
  34323. * Modifies the mesh geometry according to the passed transformation matrix.
  34324. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  34325. * The mesh normals are modified using the same transformation.
  34326. * Note that, under the hood, this method sets a new VertexBuffer each call.
  34327. * @param transform defines the transform matrix to use
  34328. * @see http://doc.babylonjs.com/resources/baking_transformations
  34329. * @returns the current mesh
  34330. */
  34331. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  34332. // Position
  34333. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  34334. return this;
  34335. }
  34336. var submeshes = this.subMeshes.splice(0);
  34337. this._resetPointsArrayCache();
  34338. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34339. var temp = new Array();
  34340. var index;
  34341. for (index = 0; index < data.length; index += 3) {
  34342. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  34343. }
  34344. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  34345. // Normals
  34346. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  34347. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34348. temp = [];
  34349. for (index = 0; index < data.length; index += 3) {
  34350. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  34351. }
  34352. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  34353. }
  34354. // flip faces?
  34355. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  34356. this.flipFaces();
  34357. }
  34358. // Restore submeshes
  34359. this.releaseSubMeshes();
  34360. this.subMeshes = submeshes;
  34361. return this;
  34362. };
  34363. /**
  34364. * Modifies the mesh geometry according to its own current World Matrix.
  34365. * The mesh World Matrix is then reset.
  34366. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  34367. * Note that, under the hood, this method sets a new VertexBuffer each call.
  34368. * @see http://doc.babylonjs.com/resources/baking_transformations
  34369. * @returns the current mesh
  34370. */
  34371. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  34372. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  34373. this.scaling.copyFromFloats(1, 1, 1);
  34374. this.position.copyFromFloats(0, 0, 0);
  34375. this.rotation.copyFromFloats(0, 0, 0);
  34376. //only if quaternion is already set
  34377. if (this.rotationQuaternion) {
  34378. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  34379. }
  34380. this._worldMatrix = BABYLON.Matrix.Identity();
  34381. return this;
  34382. };
  34383. Object.defineProperty(Mesh.prototype, "_positions", {
  34384. // Cache
  34385. /** @hidden */
  34386. get: function () {
  34387. if (this._geometry) {
  34388. return this._geometry._positions;
  34389. }
  34390. return null;
  34391. },
  34392. enumerable: true,
  34393. configurable: true
  34394. });
  34395. /** @hidden */
  34396. Mesh.prototype._resetPointsArrayCache = function () {
  34397. if (this._geometry) {
  34398. this._geometry._resetPointsArrayCache();
  34399. }
  34400. return this;
  34401. };
  34402. /** @hidden */
  34403. Mesh.prototype._generatePointsArray = function () {
  34404. if (this._geometry) {
  34405. return this._geometry._generatePointsArray();
  34406. }
  34407. return false;
  34408. };
  34409. /**
  34410. * Returns a new Mesh object generated from the current mesh properties.
  34411. * This method must not get confused with createInstance()
  34412. * @param name is a string, the name given to the new mesh
  34413. * @param newParent can be any Node object (default `null`)
  34414. * @param doNotCloneChildren allows/denies the recursive cloning of the original mesh children if any (default `false`)
  34415. * @param clonePhysicsImpostor allows/denies the cloning in the same time of the original mesh `body` used by the physics engine, if any (default `true`)
  34416. * @returns a new mesh
  34417. */
  34418. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  34419. if (name === void 0) { name = ""; }
  34420. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  34421. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  34422. };
  34423. /**
  34424. * Releases resources associated with this mesh.
  34425. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  34426. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  34427. */
  34428. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  34429. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  34430. this.morphTargetManager = null;
  34431. if (this._geometry) {
  34432. this._geometry.releaseForMesh(this, true);
  34433. }
  34434. if (this._onBeforeDrawObservable) {
  34435. this._onBeforeDrawObservable.clear();
  34436. }
  34437. if (this._onBeforeRenderObservable) {
  34438. this._onBeforeRenderObservable.clear();
  34439. }
  34440. if (this._onAfterRenderObservable) {
  34441. this._onAfterRenderObservable.clear();
  34442. }
  34443. // Sources
  34444. if (this._scene.useClonedMeshhMap) {
  34445. if (this.meshMap) {
  34446. for (var uniqueId in this.meshMap) {
  34447. var mesh = this.meshMap[uniqueId];
  34448. if (mesh) {
  34449. mesh._source = null;
  34450. this.meshMap[uniqueId] = undefined;
  34451. }
  34452. }
  34453. }
  34454. if (this._source && this._source.meshMap) {
  34455. this._source.meshMap[this.uniqueId] = undefined;
  34456. }
  34457. }
  34458. else {
  34459. var meshes = this.getScene().meshes;
  34460. for (var _i = 0, meshes_1 = meshes; _i < meshes_1.length; _i++) {
  34461. var abstractMesh = meshes_1[_i];
  34462. var mesh = abstractMesh;
  34463. if (mesh._source && mesh._source === this) {
  34464. mesh._source = null;
  34465. }
  34466. }
  34467. }
  34468. this._source = null;
  34469. // Instances
  34470. if (this._instanceDataStorage.instancesBuffer) {
  34471. this._instanceDataStorage.instancesBuffer.dispose();
  34472. this._instanceDataStorage.instancesBuffer = null;
  34473. }
  34474. while (this.instances.length) {
  34475. this.instances[0].dispose();
  34476. }
  34477. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  34478. };
  34479. /**
  34480. * Modifies the mesh geometry according to a displacement map.
  34481. * 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.
  34482. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  34483. * @param url is a string, the URL from the image file is to be downloaded.
  34484. * @param minHeight is the lower limit of the displacement.
  34485. * @param maxHeight is the upper limit of the displacement.
  34486. * @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.
  34487. * @param uvOffset is an optional vector2 used to offset UV.
  34488. * @param uvScale is an optional vector2 used to scale UV.
  34489. * @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.
  34490. * @returns the Mesh.
  34491. */
  34492. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale, forceUpdate) {
  34493. var _this = this;
  34494. if (forceUpdate === void 0) { forceUpdate = false; }
  34495. var scene = this.getScene();
  34496. var onload = function (img) {
  34497. // Getting height map data
  34498. var canvas = document.createElement("canvas");
  34499. var context = canvas.getContext("2d");
  34500. var heightMapWidth = img.width;
  34501. var heightMapHeight = img.height;
  34502. canvas.width = heightMapWidth;
  34503. canvas.height = heightMapHeight;
  34504. context.drawImage(img, 0, 0);
  34505. // Create VertexData from map data
  34506. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  34507. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  34508. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale, forceUpdate);
  34509. //execute success callback, if set
  34510. if (onSuccess) {
  34511. onSuccess(_this);
  34512. }
  34513. };
  34514. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.offlineProvider);
  34515. return this;
  34516. };
  34517. /**
  34518. * Modifies the mesh geometry according to a displacementMap buffer.
  34519. * 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.
  34520. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  34521. * @param buffer is a `Uint8Array` buffer containing series of `Uint8` lower than 255, the red, green, blue and alpha values of each successive pixel.
  34522. * @param heightMapWidth is the width of the buffer image.
  34523. * @param heightMapHeight is the height of the buffer image.
  34524. * @param minHeight is the lower limit of the displacement.
  34525. * @param maxHeight is the upper limit of the displacement.
  34526. * @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.
  34527. * @param uvOffset is an optional vector2 used to offset UV.
  34528. * @param uvScale is an optional vector2 used to scale UV.
  34529. * @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.
  34530. * @returns the Mesh.
  34531. */
  34532. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale, forceUpdate) {
  34533. if (forceUpdate === void 0) { forceUpdate = false; }
  34534. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  34535. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  34536. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  34537. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  34538. return this;
  34539. }
  34540. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, true, true);
  34541. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34542. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  34543. var position = BABYLON.Vector3.Zero();
  34544. var normal = BABYLON.Vector3.Zero();
  34545. var uv = BABYLON.Vector2.Zero();
  34546. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  34547. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  34548. for (var index = 0; index < positions.length; index += 3) {
  34549. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  34550. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  34551. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  34552. // Compute height
  34553. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  34554. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  34555. var pos = (u + v * heightMapWidth) * 4;
  34556. var r = buffer[pos] / 255.0;
  34557. var g = buffer[pos + 1] / 255.0;
  34558. var b = buffer[pos + 2] / 255.0;
  34559. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  34560. normal.normalize();
  34561. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  34562. position = position.add(normal);
  34563. position.toArray(positions, index);
  34564. }
  34565. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  34566. if (forceUpdate) {
  34567. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  34568. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  34569. }
  34570. else {
  34571. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  34572. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  34573. }
  34574. return this;
  34575. };
  34576. /**
  34577. * Modify the mesh to get a flat shading rendering.
  34578. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  34579. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  34580. * @returns current mesh
  34581. */
  34582. Mesh.prototype.convertToFlatShadedMesh = function () {
  34583. var kinds = this.getVerticesDataKinds();
  34584. var vbs = {};
  34585. var data = {};
  34586. var newdata = {};
  34587. var updatableNormals = false;
  34588. var kindIndex;
  34589. var kind;
  34590. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  34591. kind = kinds[kindIndex];
  34592. var vertexBuffer = this.getVertexBuffer(kind);
  34593. if (kind === BABYLON.VertexBuffer.NormalKind) {
  34594. updatableNormals = vertexBuffer.isUpdatable();
  34595. kinds.splice(kindIndex, 1);
  34596. kindIndex--;
  34597. continue;
  34598. }
  34599. vbs[kind] = vertexBuffer;
  34600. data[kind] = vbs[kind].getData();
  34601. newdata[kind] = [];
  34602. }
  34603. // Save previous submeshes
  34604. var previousSubmeshes = this.subMeshes.slice(0);
  34605. var indices = this.getIndices();
  34606. var totalIndices = this.getTotalIndices();
  34607. // Generating unique vertices per face
  34608. var index;
  34609. for (index = 0; index < totalIndices; index++) {
  34610. var vertexIndex = indices[index];
  34611. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  34612. kind = kinds[kindIndex];
  34613. var stride = vbs[kind].getStrideSize();
  34614. for (var offset = 0; offset < stride; offset++) {
  34615. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  34616. }
  34617. }
  34618. }
  34619. // Updating faces & normal
  34620. var normals = [];
  34621. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  34622. for (index = 0; index < totalIndices; index += 3) {
  34623. indices[index] = index;
  34624. indices[index + 1] = index + 1;
  34625. indices[index + 2] = index + 2;
  34626. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  34627. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  34628. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  34629. var p1p2 = p1.subtract(p2);
  34630. var p3p2 = p3.subtract(p2);
  34631. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  34632. // Store same normals for every vertex
  34633. for (var localIndex = 0; localIndex < 3; localIndex++) {
  34634. normals.push(normal.x);
  34635. normals.push(normal.y);
  34636. normals.push(normal.z);
  34637. }
  34638. }
  34639. this.setIndices(indices);
  34640. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  34641. // Updating vertex buffers
  34642. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  34643. kind = kinds[kindIndex];
  34644. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  34645. }
  34646. // Updating submeshes
  34647. this.releaseSubMeshes();
  34648. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  34649. var previousOne = previousSubmeshes[submeshIndex];
  34650. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  34651. }
  34652. this.synchronizeInstances();
  34653. return this;
  34654. };
  34655. /**
  34656. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  34657. * In other words, more vertices, no more indices and a single bigger VBO.
  34658. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  34659. * @returns current mesh
  34660. */
  34661. Mesh.prototype.convertToUnIndexedMesh = function () {
  34662. var kinds = this.getVerticesDataKinds();
  34663. var vbs = {};
  34664. var data = {};
  34665. var newdata = {};
  34666. var kindIndex;
  34667. var kind;
  34668. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  34669. kind = kinds[kindIndex];
  34670. var vertexBuffer = this.getVertexBuffer(kind);
  34671. vbs[kind] = vertexBuffer;
  34672. data[kind] = vbs[kind].getData();
  34673. newdata[kind] = [];
  34674. }
  34675. // Save previous submeshes
  34676. var previousSubmeshes = this.subMeshes.slice(0);
  34677. var indices = this.getIndices();
  34678. var totalIndices = this.getTotalIndices();
  34679. // Generating unique vertices per face
  34680. var index;
  34681. for (index = 0; index < totalIndices; index++) {
  34682. var vertexIndex = indices[index];
  34683. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  34684. kind = kinds[kindIndex];
  34685. var stride = vbs[kind].getStrideSize();
  34686. for (var offset = 0; offset < stride; offset++) {
  34687. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  34688. }
  34689. }
  34690. }
  34691. // Updating indices
  34692. for (index = 0; index < totalIndices; index += 3) {
  34693. indices[index] = index;
  34694. indices[index + 1] = index + 1;
  34695. indices[index + 2] = index + 2;
  34696. }
  34697. this.setIndices(indices);
  34698. // Updating vertex buffers
  34699. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  34700. kind = kinds[kindIndex];
  34701. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  34702. }
  34703. // Updating submeshes
  34704. this.releaseSubMeshes();
  34705. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  34706. var previousOne = previousSubmeshes[submeshIndex];
  34707. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  34708. }
  34709. this._unIndexed = true;
  34710. this.synchronizeInstances();
  34711. return this;
  34712. };
  34713. /**
  34714. * Inverses facet orientations.
  34715. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  34716. * @param flipNormals will also inverts the normals
  34717. * @returns current mesh
  34718. */
  34719. Mesh.prototype.flipFaces = function (flipNormals) {
  34720. if (flipNormals === void 0) { flipNormals = false; }
  34721. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  34722. var i;
  34723. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  34724. for (i = 0; i < vertex_data.normals.length; i++) {
  34725. vertex_data.normals[i] *= -1;
  34726. }
  34727. }
  34728. if (vertex_data.indices) {
  34729. var temp;
  34730. for (i = 0; i < vertex_data.indices.length; i += 3) {
  34731. // reassign indices
  34732. temp = vertex_data.indices[i + 1];
  34733. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  34734. vertex_data.indices[i + 2] = temp;
  34735. }
  34736. }
  34737. vertex_data.applyToMesh(this);
  34738. return this;
  34739. };
  34740. // Instances
  34741. /**
  34742. * Creates a new InstancedMesh object from the mesh model.
  34743. * @see http://doc.babylonjs.com/how_to/how_to_use_instances
  34744. * @param name defines the name of the new instance
  34745. * @returns a new InstancedMesh
  34746. */
  34747. Mesh.prototype.createInstance = function (name) {
  34748. return new BABYLON.InstancedMesh(name, this);
  34749. };
  34750. /**
  34751. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  34752. * After this call, all the mesh instances have the same submeshes than the current mesh.
  34753. * @returns the current mesh
  34754. */
  34755. Mesh.prototype.synchronizeInstances = function () {
  34756. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  34757. var instance = this.instances[instanceIndex];
  34758. instance._syncSubMeshes();
  34759. }
  34760. return this;
  34761. };
  34762. /**
  34763. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  34764. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  34765. * This should be used together with the simplification to avoid disappearing triangles.
  34766. * @param successCallback an optional success callback to be called after the optimization finished.
  34767. * @returns the current mesh
  34768. */
  34769. Mesh.prototype.optimizeIndices = function (successCallback) {
  34770. var _this = this;
  34771. var indices = this.getIndices();
  34772. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34773. if (!positions || !indices) {
  34774. return this;
  34775. }
  34776. var vectorPositions = new Array();
  34777. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  34778. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  34779. }
  34780. var dupes = new Array();
  34781. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  34782. var realPos = vectorPositions.length - 1 - iteration;
  34783. var testedPosition = vectorPositions[realPos];
  34784. for (var j = 0; j < realPos; ++j) {
  34785. var againstPosition = vectorPositions[j];
  34786. if (testedPosition.equals(againstPosition)) {
  34787. dupes[realPos] = j;
  34788. break;
  34789. }
  34790. }
  34791. }, function () {
  34792. for (var i = 0; i < indices.length; ++i) {
  34793. indices[i] = dupes[indices[i]] || indices[i];
  34794. }
  34795. //indices are now reordered
  34796. var originalSubMeshes = _this.subMeshes.slice(0);
  34797. _this.setIndices(indices);
  34798. _this.subMeshes = originalSubMeshes;
  34799. if (successCallback) {
  34800. successCallback(_this);
  34801. }
  34802. });
  34803. return this;
  34804. };
  34805. /**
  34806. * Serialize current mesh
  34807. * @param serializationObject defines the object which will receive the serialization data
  34808. */
  34809. Mesh.prototype.serialize = function (serializationObject) {
  34810. serializationObject.name = this.name;
  34811. serializationObject.id = this.id;
  34812. serializationObject.type = this.getClassName();
  34813. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  34814. serializationObject.tags = BABYLON.Tags.GetTags(this);
  34815. }
  34816. serializationObject.position = this.position.asArray();
  34817. if (this.rotationQuaternion) {
  34818. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  34819. }
  34820. else if (this.rotation) {
  34821. serializationObject.rotation = this.rotation.asArray();
  34822. }
  34823. serializationObject.scaling = this.scaling.asArray();
  34824. if (this._postMultiplyPivotMatrix) {
  34825. serializationObject.pivotMatrix = this.getPivotMatrix().asArray();
  34826. }
  34827. else {
  34828. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  34829. }
  34830. serializationObject.isEnabled = this.isEnabled(false);
  34831. serializationObject.isVisible = this.isVisible;
  34832. serializationObject.infiniteDistance = this.infiniteDistance;
  34833. serializationObject.pickable = this.isPickable;
  34834. serializationObject.receiveShadows = this.receiveShadows;
  34835. serializationObject.billboardMode = this.billboardMode;
  34836. serializationObject.visibility = this.visibility;
  34837. serializationObject.checkCollisions = this.checkCollisions;
  34838. serializationObject.isBlocker = this.isBlocker;
  34839. // Parent
  34840. if (this.parent) {
  34841. serializationObject.parentId = this.parent.id;
  34842. }
  34843. // Geometry
  34844. serializationObject.isUnIndexed = this.isUnIndexed;
  34845. var geometry = this._geometry;
  34846. if (geometry) {
  34847. var geometryId = geometry.id;
  34848. serializationObject.geometryId = geometryId;
  34849. // SubMeshes
  34850. serializationObject.subMeshes = [];
  34851. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  34852. var subMesh = this.subMeshes[subIndex];
  34853. serializationObject.subMeshes.push({
  34854. materialIndex: subMesh.materialIndex,
  34855. verticesStart: subMesh.verticesStart,
  34856. verticesCount: subMesh.verticesCount,
  34857. indexStart: subMesh.indexStart,
  34858. indexCount: subMesh.indexCount
  34859. });
  34860. }
  34861. }
  34862. // Material
  34863. if (this.material) {
  34864. serializationObject.materialId = this.material.id;
  34865. }
  34866. else {
  34867. this.material = null;
  34868. }
  34869. // Morph targets
  34870. if (this.morphTargetManager) {
  34871. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  34872. }
  34873. // Skeleton
  34874. if (this.skeleton) {
  34875. serializationObject.skeletonId = this.skeleton.id;
  34876. }
  34877. // Physics
  34878. //TODO implement correct serialization for physics impostors.
  34879. var impostor = this.getPhysicsImpostor();
  34880. if (impostor) {
  34881. serializationObject.physicsMass = impostor.getParam("mass");
  34882. serializationObject.physicsFriction = impostor.getParam("friction");
  34883. serializationObject.physicsRestitution = impostor.getParam("mass");
  34884. serializationObject.physicsImpostor = impostor.type;
  34885. }
  34886. // Metadata
  34887. if (this.metadata) {
  34888. serializationObject.metadata = this.metadata;
  34889. }
  34890. // Instances
  34891. serializationObject.instances = [];
  34892. for (var index = 0; index < this.instances.length; index++) {
  34893. var instance = this.instances[index];
  34894. if (instance.doNotSerialize) {
  34895. continue;
  34896. }
  34897. var serializationInstance = {
  34898. name: instance.name,
  34899. id: instance.id,
  34900. position: instance.position.asArray(),
  34901. scaling: instance.scaling.asArray()
  34902. };
  34903. if (instance.parent) {
  34904. serializationInstance.parentId = instance.parent.id;
  34905. }
  34906. if (instance.rotationQuaternion) {
  34907. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  34908. }
  34909. else if (instance.rotation) {
  34910. serializationInstance.rotation = instance.rotation.asArray();
  34911. }
  34912. serializationObject.instances.push(serializationInstance);
  34913. // Animations
  34914. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  34915. serializationInstance.ranges = instance.serializeAnimationRanges();
  34916. }
  34917. //
  34918. // Animations
  34919. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  34920. serializationObject.ranges = this.serializeAnimationRanges();
  34921. // Layer mask
  34922. serializationObject.layerMask = this.layerMask;
  34923. // Alpha
  34924. serializationObject.alphaIndex = this.alphaIndex;
  34925. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  34926. // Overlay
  34927. serializationObject.overlayAlpha = this.overlayAlpha;
  34928. serializationObject.overlayColor = this.overlayColor.asArray();
  34929. serializationObject.renderOverlay = this.renderOverlay;
  34930. // Fog
  34931. serializationObject.applyFog = this.applyFog;
  34932. // Action Manager
  34933. if (this.actionManager) {
  34934. serializationObject.actions = this.actionManager.serialize(this.name);
  34935. }
  34936. };
  34937. /** @hidden */
  34938. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  34939. if (!this.geometry) {
  34940. return;
  34941. }
  34942. this._markSubMeshesAsAttributesDirty();
  34943. var morphTargetManager = this._morphTargetManager;
  34944. if (morphTargetManager && morphTargetManager.vertexCount) {
  34945. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  34946. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  34947. this.morphTargetManager = null;
  34948. return;
  34949. }
  34950. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  34951. var morphTarget = morphTargetManager.getActiveTarget(index);
  34952. var positions = morphTarget.getPositions();
  34953. if (!positions) {
  34954. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  34955. return;
  34956. }
  34957. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  34958. var normals = morphTarget.getNormals();
  34959. if (normals) {
  34960. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  34961. }
  34962. var tangents = morphTarget.getTangents();
  34963. if (tangents) {
  34964. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  34965. }
  34966. }
  34967. }
  34968. else {
  34969. var index = 0;
  34970. // Positions
  34971. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  34972. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  34973. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  34974. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  34975. }
  34976. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  34977. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  34978. }
  34979. index++;
  34980. }
  34981. }
  34982. };
  34983. // Statics
  34984. /**
  34985. * Returns a new Mesh object parsed from the source provided.
  34986. * @param parsedMesh is the source
  34987. * @param scene defines the hosting scene
  34988. * @param rootUrl is the root URL to prefix the `delayLoadingFile` property with
  34989. * @returns a new Mesh
  34990. */
  34991. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  34992. var mesh;
  34993. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  34994. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  34995. }
  34996. else {
  34997. mesh = new Mesh(parsedMesh.name, scene);
  34998. }
  34999. mesh.id = parsedMesh.id;
  35000. if (BABYLON.Tags) {
  35001. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  35002. }
  35003. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  35004. if (parsedMesh.metadata !== undefined) {
  35005. mesh.metadata = parsedMesh.metadata;
  35006. }
  35007. if (parsedMesh.rotationQuaternion) {
  35008. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  35009. }
  35010. else if (parsedMesh.rotation) {
  35011. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  35012. }
  35013. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  35014. if (parsedMesh.localMatrix) {
  35015. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  35016. }
  35017. else if (parsedMesh.pivotMatrix) {
  35018. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  35019. }
  35020. mesh.setEnabled(parsedMesh.isEnabled);
  35021. mesh.isVisible = parsedMesh.isVisible;
  35022. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  35023. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  35024. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  35025. if (parsedMesh.applyFog !== undefined) {
  35026. mesh.applyFog = parsedMesh.applyFog;
  35027. }
  35028. if (parsedMesh.pickable !== undefined) {
  35029. mesh.isPickable = parsedMesh.pickable;
  35030. }
  35031. if (parsedMesh.alphaIndex !== undefined) {
  35032. mesh.alphaIndex = parsedMesh.alphaIndex;
  35033. }
  35034. mesh.receiveShadows = parsedMesh.receiveShadows;
  35035. mesh.billboardMode = parsedMesh.billboardMode;
  35036. if (parsedMesh.visibility !== undefined) {
  35037. mesh.visibility = parsedMesh.visibility;
  35038. }
  35039. mesh.checkCollisions = parsedMesh.checkCollisions;
  35040. if (parsedMesh.isBlocker !== undefined) {
  35041. mesh.isBlocker = parsedMesh.isBlocker;
  35042. }
  35043. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  35044. // freezeWorldMatrix
  35045. if (parsedMesh.freezeWorldMatrix) {
  35046. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  35047. }
  35048. // Parent
  35049. if (parsedMesh.parentId) {
  35050. mesh._waitingParentId = parsedMesh.parentId;
  35051. }
  35052. // Actions
  35053. if (parsedMesh.actions !== undefined) {
  35054. mesh._waitingActions = parsedMesh.actions;
  35055. }
  35056. // Overlay
  35057. if (parsedMesh.overlayAlpha !== undefined) {
  35058. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  35059. }
  35060. if (parsedMesh.overlayColor !== undefined) {
  35061. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  35062. }
  35063. if (parsedMesh.renderOverlay !== undefined) {
  35064. mesh.renderOverlay = parsedMesh.renderOverlay;
  35065. }
  35066. // Geometry
  35067. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  35068. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  35069. if (parsedMesh.delayLoadingFile) {
  35070. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  35071. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  35072. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  35073. if (parsedMesh._binaryInfo) {
  35074. mesh._binaryInfo = parsedMesh._binaryInfo;
  35075. }
  35076. mesh._delayInfo = [];
  35077. if (parsedMesh.hasUVs) {
  35078. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  35079. }
  35080. if (parsedMesh.hasUVs2) {
  35081. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  35082. }
  35083. if (parsedMesh.hasUVs3) {
  35084. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  35085. }
  35086. if (parsedMesh.hasUVs4) {
  35087. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  35088. }
  35089. if (parsedMesh.hasUVs5) {
  35090. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  35091. }
  35092. if (parsedMesh.hasUVs6) {
  35093. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  35094. }
  35095. if (parsedMesh.hasColors) {
  35096. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  35097. }
  35098. if (parsedMesh.hasMatricesIndices) {
  35099. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  35100. }
  35101. if (parsedMesh.hasMatricesWeights) {
  35102. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  35103. }
  35104. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  35105. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  35106. mesh._checkDelayState();
  35107. }
  35108. }
  35109. else {
  35110. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  35111. }
  35112. // Material
  35113. if (parsedMesh.materialId) {
  35114. mesh.setMaterialByID(parsedMesh.materialId);
  35115. }
  35116. else {
  35117. mesh.material = null;
  35118. }
  35119. // Morph targets
  35120. if (parsedMesh.morphTargetManagerId > -1) {
  35121. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  35122. }
  35123. // Skeleton
  35124. if (parsedMesh.skeletonId > -1) {
  35125. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  35126. if (parsedMesh.numBoneInfluencers) {
  35127. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  35128. }
  35129. }
  35130. // Animations
  35131. if (parsedMesh.animations) {
  35132. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  35133. var parsedAnimation = parsedMesh.animations[animationIndex];
  35134. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  35135. }
  35136. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  35137. }
  35138. if (parsedMesh.autoAnimate) {
  35139. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  35140. }
  35141. // Layer Mask
  35142. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  35143. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  35144. }
  35145. else {
  35146. mesh.layerMask = 0x0FFFFFFF;
  35147. }
  35148. // Physics
  35149. if (parsedMesh.physicsImpostor) {
  35150. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  35151. mass: parsedMesh.physicsMass,
  35152. friction: parsedMesh.physicsFriction,
  35153. restitution: parsedMesh.physicsRestitution
  35154. }, scene);
  35155. }
  35156. // Instances
  35157. if (parsedMesh.instances) {
  35158. for (var index = 0; index < parsedMesh.instances.length; index++) {
  35159. var parsedInstance = parsedMesh.instances[index];
  35160. var instance = mesh.createInstance(parsedInstance.name);
  35161. if (parsedInstance.id) {
  35162. instance.id = parsedInstance.id;
  35163. }
  35164. if (BABYLON.Tags) {
  35165. if (parsedInstance.tags) {
  35166. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  35167. }
  35168. else {
  35169. BABYLON.Tags.AddTagsTo(instance, parsedMesh.tags);
  35170. }
  35171. }
  35172. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  35173. if (parsedInstance.parentId) {
  35174. instance._waitingParentId = parsedInstance.parentId;
  35175. }
  35176. if (parsedInstance.rotationQuaternion) {
  35177. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  35178. }
  35179. else if (parsedInstance.rotation) {
  35180. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  35181. }
  35182. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  35183. if (parsedInstance.checkCollisions != undefined && parsedInstance.checkCollisions != null) {
  35184. instance.checkCollisions = parsedInstance.checkCollisions;
  35185. }
  35186. if (parsedInstance.pickable != undefined && parsedInstance.pickable != null) {
  35187. instance.isPickable = parsedInstance.pickable;
  35188. }
  35189. if (parsedInstance.showBoundingBox != undefined && parsedInstance.showBoundingBox != null) {
  35190. instance.showBoundingBox = parsedInstance.showBoundingBox;
  35191. }
  35192. if (parsedInstance.showSubMeshesBoundingBox != undefined && parsedInstance.showSubMeshesBoundingBox != null) {
  35193. instance.showSubMeshesBoundingBox = parsedInstance.showSubMeshesBoundingBox;
  35194. }
  35195. if (parsedInstance.alphaIndex != undefined && parsedInstance.showSubMeshesBoundingBox != null) {
  35196. instance.alphaIndex = parsedInstance.alphaIndex;
  35197. }
  35198. // Physics
  35199. if (parsedInstance.physicsImpostor) {
  35200. instance.physicsImpostor = new BABYLON.PhysicsImpostor(instance, parsedInstance.physicsImpostor, {
  35201. mass: parsedInstance.physicsMass,
  35202. friction: parsedInstance.physicsFriction,
  35203. restitution: parsedInstance.physicsRestitution
  35204. }, scene);
  35205. }
  35206. // Animation
  35207. if (parsedInstance.animations) {
  35208. for (animationIndex = 0; animationIndex < parsedInstance.animations.length; animationIndex++) {
  35209. parsedAnimation = parsedInstance.animations[animationIndex];
  35210. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  35211. }
  35212. BABYLON.Node.ParseAnimationRanges(instance, parsedInstance, scene);
  35213. if (parsedInstance.autoAnimate) {
  35214. scene.beginAnimation(instance, parsedInstance.autoAnimateFrom, parsedInstance.autoAnimateTo, parsedInstance.autoAnimateLoop, parsedInstance.autoAnimateSpeed || 1.0);
  35215. }
  35216. }
  35217. }
  35218. }
  35219. return mesh;
  35220. };
  35221. /**
  35222. * Creates a ribbon mesh. Please consider using the same method from the MeshBuilder class instead
  35223. * @see http://doc.babylonjs.com/how_to/parametric_shapes
  35224. * @param name defines the name of the mesh to create
  35225. * @param pathArray is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  35226. * @param closeArray creates a seam between the first and the last paths of the path array (default is false)
  35227. * @param closePath creates a seam between the first and the last points of each path of the path array
  35228. * @param offset is taken in account only if the `pathArray` is containing a single path
  35229. * @param scene defines the hosting scene
  35230. * @param updatable defines if the mesh must be flagged as updatable
  35231. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  35232. * @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)
  35233. * @returns a new Mesh
  35234. */
  35235. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  35236. if (closeArray === void 0) { closeArray = false; }
  35237. if (updatable === void 0) { updatable = false; }
  35238. return BABYLON.MeshBuilder.CreateRibbon(name, {
  35239. pathArray: pathArray,
  35240. closeArray: closeArray,
  35241. closePath: closePath,
  35242. offset: offset,
  35243. updatable: updatable,
  35244. sideOrientation: sideOrientation,
  35245. instance: instance
  35246. }, scene);
  35247. };
  35248. /**
  35249. * Creates a plane polygonal mesh. By default, this is a disc. Please consider using the same method from the MeshBuilder class instead
  35250. * @param name defines the name of the mesh to create
  35251. * @param radius sets the radius size (float) of the polygon (default 0.5)
  35252. * @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
  35253. * @param scene defines the hosting scene
  35254. * @param updatable defines if the mesh must be flagged as updatable
  35255. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  35256. * @returns a new Mesh
  35257. */
  35258. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  35259. if (scene === void 0) { scene = null; }
  35260. var options = {
  35261. radius: radius,
  35262. tessellation: tessellation,
  35263. sideOrientation: sideOrientation,
  35264. updatable: updatable
  35265. };
  35266. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  35267. };
  35268. /**
  35269. * Creates a box mesh. Please consider using the same method from the MeshBuilder class instead
  35270. * @param name defines the name of the mesh to create
  35271. * @param size sets the size (float) of each box side (default 1)
  35272. * @param scene defines the hosting scene
  35273. * @param updatable defines if the mesh must be flagged as updatable
  35274. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  35275. * @returns a new Mesh
  35276. */
  35277. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  35278. if (scene === void 0) { scene = null; }
  35279. var options = {
  35280. size: size,
  35281. sideOrientation: sideOrientation,
  35282. updatable: updatable
  35283. };
  35284. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  35285. };
  35286. /**
  35287. * Creates a sphere mesh. Please consider using the same method from the MeshBuilder class instead
  35288. * @param name defines the name of the mesh to create
  35289. * @param segments sets the sphere number of horizontal stripes (positive integer, default 32)
  35290. * @param diameter sets the diameter size (float) of the sphere (default 1)
  35291. * @param scene defines the hosting scene
  35292. * @param updatable defines if the mesh must be flagged as updatable
  35293. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  35294. * @returns a new Mesh
  35295. */
  35296. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  35297. var options = {
  35298. segments: segments,
  35299. diameterX: diameter,
  35300. diameterY: diameter,
  35301. diameterZ: diameter,
  35302. sideOrientation: sideOrientation,
  35303. updatable: updatable
  35304. };
  35305. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  35306. };
  35307. /**
  35308. * Creates a cylinder or a cone mesh. Please consider using the same method from the MeshBuilder class instead
  35309. * @param name defines the name of the mesh to create
  35310. * @param height sets the height size (float) of the cylinder/cone (float, default 2)
  35311. * @param diameterTop set the top cap diameter (floats, default 1)
  35312. * @param diameterBottom set the bottom cap diameter (floats, default 1). This value can't be zero
  35313. * @param tessellation sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance
  35314. * @param subdivisions sets the number of rings along the cylinder height (positive integer, default 1)
  35315. * @param scene defines the hosting scene
  35316. * @param updatable defines if the mesh must be flagged as updatable
  35317. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  35318. * @returns a new Mesh
  35319. */
  35320. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  35321. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  35322. if (scene !== undefined) {
  35323. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  35324. updatable = scene;
  35325. }
  35326. scene = subdivisions;
  35327. subdivisions = 1;
  35328. }
  35329. var options = {
  35330. height: height,
  35331. diameterTop: diameterTop,
  35332. diameterBottom: diameterBottom,
  35333. tessellation: tessellation,
  35334. subdivisions: subdivisions,
  35335. sideOrientation: sideOrientation,
  35336. updatable: updatable
  35337. };
  35338. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  35339. };
  35340. // Torus (Code from SharpDX.org)
  35341. /**
  35342. * Creates a torus mesh. Please consider using the same method from the MeshBuilder class instead
  35343. * @param name defines the name of the mesh to create
  35344. * @param diameter sets the diameter size (float) of the torus (default 1)
  35345. * @param thickness sets the diameter size of the tube of the torus (float, default 0.5)
  35346. * @param tessellation sets the number of torus sides (postive integer, default 16)
  35347. * @param scene defines the hosting scene
  35348. * @param updatable defines if the mesh must be flagged as updatable
  35349. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  35350. * @returns a new Mesh
  35351. */
  35352. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  35353. var options = {
  35354. diameter: diameter,
  35355. thickness: thickness,
  35356. tessellation: tessellation,
  35357. sideOrientation: sideOrientation,
  35358. updatable: updatable
  35359. };
  35360. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  35361. };
  35362. /**
  35363. * Creates a torus knot mesh. Please consider using the same method from the MeshBuilder class instead
  35364. * @param name defines the name of the mesh to create
  35365. * @param radius sets the global radius size (float) of the torus knot (default 2)
  35366. * @param tube sets the diameter size of the tube of the torus (float, default 0.5)
  35367. * @param radialSegments sets the number of sides on each tube segments (positive integer, default 32)
  35368. * @param tubularSegments sets the number of tubes to decompose the knot into (positive integer, default 32)
  35369. * @param p the number of windings on X axis (positive integers, default 2)
  35370. * @param q the number of windings on Y axis (positive integers, default 3)
  35371. * @param scene defines the hosting scene
  35372. * @param updatable defines if the mesh must be flagged as updatable
  35373. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  35374. * @returns a new Mesh
  35375. */
  35376. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  35377. var options = {
  35378. radius: radius,
  35379. tube: tube,
  35380. radialSegments: radialSegments,
  35381. tubularSegments: tubularSegments,
  35382. p: p,
  35383. q: q,
  35384. sideOrientation: sideOrientation,
  35385. updatable: updatable
  35386. };
  35387. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  35388. };
  35389. /**
  35390. * Creates a line mesh. Please consider using the same method from the MeshBuilder class instead.
  35391. * @param name defines the name of the mesh to create
  35392. * @param points is an array successive Vector3
  35393. * @param scene defines the hosting scene
  35394. * @param updatable defines if the mesh must be flagged as updatable
  35395. * @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).
  35396. * @returns a new Mesh
  35397. */
  35398. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  35399. if (scene === void 0) { scene = null; }
  35400. if (updatable === void 0) { updatable = false; }
  35401. if (instance === void 0) { instance = null; }
  35402. var options = {
  35403. points: points,
  35404. updatable: updatable,
  35405. instance: instance
  35406. };
  35407. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  35408. };
  35409. /**
  35410. * Creates a dashed line mesh. Please consider using the same method from the MeshBuilder class instead
  35411. * @param name defines the name of the mesh to create
  35412. * @param points is an array successive Vector3
  35413. * @param dashSize is the size of the dashes relatively the dash number (positive float, default 3)
  35414. * @param gapSize is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  35415. * @param dashNb is the intended total number of dashes (positive integer, default 200)
  35416. * @param scene defines the hosting scene
  35417. * @param updatable defines if the mesh must be flagged as updatable
  35418. * @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)
  35419. * @returns a new Mesh
  35420. */
  35421. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  35422. if (scene === void 0) { scene = null; }
  35423. var options = {
  35424. points: points,
  35425. dashSize: dashSize,
  35426. gapSize: gapSize,
  35427. dashNb: dashNb,
  35428. updatable: updatable,
  35429. instance: instance
  35430. };
  35431. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  35432. };
  35433. /**
  35434. * Creates a polygon mesh.
  35435. * Please consider using the same method from the MeshBuilder class instead.
  35436. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  35437. * 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.
  35438. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  35439. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  35440. * Remember you can only change the shape positions, not their number when updating a polygon.
  35441. */
  35442. /**
  35443. * Creates a polygon mesh.Please consider using the same method from the MeshBuilder class instead
  35444. * @see http://doc.babylonjs.com/how_to/parametric_shapes#non-regular-polygon
  35445. * @param name defines the name of the mesh to create
  35446. * @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
  35447. * @param scene defines the hosting scene
  35448. * @param holes is a required array of arrays of successive Vector3 used to defines holes in the polygon
  35449. * @param updatable defines if the mesh must be flagged as updatable
  35450. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  35451. * @returns a new Mesh
  35452. */
  35453. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  35454. var options = {
  35455. shape: shape,
  35456. holes: holes,
  35457. updatable: updatable,
  35458. sideOrientation: sideOrientation
  35459. };
  35460. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  35461. };
  35462. /**
  35463. * Creates an extruded polygon mesh, with depth in the Y direction. Please consider using the same method from the MeshBuilder class instead.
  35464. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-non-regular-polygon
  35465. * @param name defines the name of the mesh to create
  35466. * @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
  35467. * @param depth defines the height of extrusion
  35468. * @param scene defines the hosting scene
  35469. * @param holes is a required array of arrays of successive Vector3 used to defines holes in the polygon
  35470. * @param updatable defines if the mesh must be flagged as updatable
  35471. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  35472. * @returns a new Mesh
  35473. */
  35474. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  35475. var options = {
  35476. shape: shape,
  35477. holes: holes,
  35478. depth: depth,
  35479. updatable: updatable,
  35480. sideOrientation: sideOrientation
  35481. };
  35482. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  35483. };
  35484. /**
  35485. * Creates an extruded shape mesh.
  35486. * 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
  35487. * @see http://doc.babylonjs.com/how_to/parametric_shapes
  35488. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  35489. * @param name defines the name of the mesh to create
  35490. * @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
  35491. * @param path is a required array of successive Vector3. This is the axis curve the shape is extruded along
  35492. * @param scale is the value to scale the shape
  35493. * @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
  35494. * @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
  35495. * @param scene defines the hosting scene
  35496. * @param updatable defines if the mesh must be flagged as updatable
  35497. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  35498. * @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)
  35499. * @returns a new Mesh
  35500. */
  35501. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  35502. if (scene === void 0) { scene = null; }
  35503. var options = {
  35504. shape: shape,
  35505. path: path,
  35506. scale: scale,
  35507. rotation: rotation,
  35508. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  35509. sideOrientation: sideOrientation,
  35510. instance: instance,
  35511. updatable: updatable
  35512. };
  35513. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  35514. };
  35515. /**
  35516. * Creates an custom extruded shape mesh.
  35517. * The custom extrusion is a parametric shape.
  35518. * It has no predefined shape. Its final shape will depend on the input parameters.
  35519. * Please consider using the same method from the MeshBuilder class instead
  35520. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  35521. * @param name defines the name of the mesh to create
  35522. * @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
  35523. * @param path is a required array of successive Vector3. This is the axis curve the shape is extruded along
  35524. * @param scaleFunction is a custom Javascript function called on each path point
  35525. * @param rotationFunction is a custom Javascript function called on each path point
  35526. * @param ribbonCloseArray forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  35527. * @param ribbonClosePath forces the extrusion underlying ribbon to close its `pathArray`
  35528. * @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
  35529. * @param scene defines the hosting scene
  35530. * @param updatable defines if the mesh must be flagged as updatable
  35531. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  35532. * @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)
  35533. * @returns a new Mesh
  35534. */
  35535. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  35536. var options = {
  35537. shape: shape,
  35538. path: path,
  35539. scaleFunction: scaleFunction,
  35540. rotationFunction: rotationFunction,
  35541. ribbonCloseArray: ribbonCloseArray,
  35542. ribbonClosePath: ribbonClosePath,
  35543. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  35544. sideOrientation: sideOrientation,
  35545. instance: instance,
  35546. updatable: updatable
  35547. };
  35548. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  35549. };
  35550. /**
  35551. * Creates lathe mesh.
  35552. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  35553. * Please consider using the same method from the MeshBuilder class instead
  35554. * @param name defines the name of the mesh to create
  35555. * @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
  35556. * @param radius is the radius value of the lathe
  35557. * @param tessellation is the side number of the lathe.
  35558. * @param scene defines the hosting scene
  35559. * @param updatable defines if the mesh must be flagged as updatable
  35560. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  35561. * @returns a new Mesh
  35562. */
  35563. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  35564. var options = {
  35565. shape: shape,
  35566. radius: radius,
  35567. tessellation: tessellation,
  35568. sideOrientation: sideOrientation,
  35569. updatable: updatable
  35570. };
  35571. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  35572. };
  35573. /**
  35574. * Creates a plane mesh. Please consider using the same method from the MeshBuilder class instead
  35575. * @param name defines the name of the mesh to create
  35576. * @param size sets the size (float) of both sides of the plane at once (default 1)
  35577. * @param scene defines the hosting scene
  35578. * @param updatable defines if the mesh must be flagged as updatable
  35579. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  35580. * @returns a new Mesh
  35581. */
  35582. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  35583. var options = {
  35584. size: size,
  35585. width: size,
  35586. height: size,
  35587. sideOrientation: sideOrientation,
  35588. updatable: updatable
  35589. };
  35590. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  35591. };
  35592. /**
  35593. * Creates a ground mesh.
  35594. * Please consider using the same method from the MeshBuilder class instead
  35595. * @param name defines the name of the mesh to create
  35596. * @param width set the width of the ground
  35597. * @param height set the height of the ground
  35598. * @param subdivisions sets the number of subdivisions per side
  35599. * @param scene defines the hosting scene
  35600. * @param updatable defines if the mesh must be flagged as updatable
  35601. * @returns a new Mesh
  35602. */
  35603. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  35604. var options = {
  35605. width: width,
  35606. height: height,
  35607. subdivisions: subdivisions,
  35608. updatable: updatable
  35609. };
  35610. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  35611. };
  35612. /**
  35613. * Creates a tiled ground mesh.
  35614. * Please consider using the same method from the MeshBuilder class instead
  35615. * @param name defines the name of the mesh to create
  35616. * @param xmin set the ground minimum X coordinate
  35617. * @param zmin set the ground minimum Y coordinate
  35618. * @param xmax set the ground maximum X coordinate
  35619. * @param zmax set the ground maximum Z coordinate
  35620. * @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
  35621. * @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
  35622. * @param scene defines the hosting scene
  35623. * @param updatable defines if the mesh must be flagged as updatable
  35624. * @returns a new Mesh
  35625. */
  35626. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  35627. var options = {
  35628. xmin: xmin,
  35629. zmin: zmin,
  35630. xmax: xmax,
  35631. zmax: zmax,
  35632. subdivisions: subdivisions,
  35633. precision: precision,
  35634. updatable: updatable
  35635. };
  35636. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  35637. };
  35638. /**
  35639. * Creates a ground mesh from a height map.
  35640. * Please consider using the same method from the MeshBuilder class instead
  35641. * @see http://doc.babylonjs.com/babylon101/height_map
  35642. * @param name defines the name of the mesh to create
  35643. * @param url sets the URL of the height map image resource
  35644. * @param width set the ground width size
  35645. * @param height set the ground height size
  35646. * @param subdivisions sets the number of subdivision per side
  35647. * @param minHeight is the minimum altitude on the ground
  35648. * @param maxHeight is the maximum altitude on the ground
  35649. * @param scene defines the hosting scene
  35650. * @param updatable defines if the mesh must be flagged as updatable
  35651. * @param onReady is a callback function that will be called once the mesh is built (the height map download can last some time)
  35652. * @param alphaFilter will filter any data where the alpha channel is below this value, defaults 0 (all data visible)
  35653. * @returns a new Mesh
  35654. */
  35655. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady, alphaFilter) {
  35656. var options = {
  35657. width: width,
  35658. height: height,
  35659. subdivisions: subdivisions,
  35660. minHeight: minHeight,
  35661. maxHeight: maxHeight,
  35662. updatable: updatable,
  35663. onReady: onReady,
  35664. alphaFilter: alphaFilter
  35665. };
  35666. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  35667. };
  35668. /**
  35669. * Creates a tube mesh.
  35670. * The tube is a parametric shape.
  35671. * It has no predefined shape. Its final shape will depend on the input parameters.
  35672. * Please consider using the same method from the MeshBuilder class instead
  35673. * @see http://doc.babylonjs.com/how_to/parametric_shapes
  35674. * @param name defines the name of the mesh to create
  35675. * @param path is a required array of successive Vector3. It is the curve used as the axis of the tube
  35676. * @param radius sets the tube radius size
  35677. * @param tessellation is the number of sides on the tubular surface
  35678. * @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
  35679. * @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
  35680. * @param scene defines the hosting scene
  35681. * @param updatable defines if the mesh must be flagged as updatable
  35682. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  35683. * @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)
  35684. * @returns a new Mesh
  35685. */
  35686. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  35687. var options = {
  35688. path: path,
  35689. radius: radius,
  35690. tessellation: tessellation,
  35691. radiusFunction: radiusFunction,
  35692. arc: 1,
  35693. cap: cap,
  35694. updatable: updatable,
  35695. sideOrientation: sideOrientation,
  35696. instance: instance
  35697. };
  35698. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  35699. };
  35700. /**
  35701. * Creates a polyhedron mesh.
  35702. * Please consider using the same method from the MeshBuilder class instead.
  35703. * * 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
  35704. * * The parameter `size` (positive float, default 1) sets the polygon size
  35705. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  35706. * * 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`
  35707. * * 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
  35708. * * 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)`)
  35709. * * 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
  35710. * * 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
  35711. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  35712. * * 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
  35713. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  35714. * @param name defines the name of the mesh to create
  35715. * @param options defines the options used to create the mesh
  35716. * @param scene defines the hosting scene
  35717. * @returns a new Mesh
  35718. */
  35719. Mesh.CreatePolyhedron = function (name, options, scene) {
  35720. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  35721. };
  35722. /**
  35723. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  35724. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  35725. * * 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`)
  35726. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  35727. * * 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
  35728. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  35729. * * 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
  35730. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  35731. * @param name defines the name of the mesh
  35732. * @param options defines the options used to create the mesh
  35733. * @param scene defines the hosting scene
  35734. * @returns a new Mesh
  35735. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  35736. */
  35737. Mesh.CreateIcoSphere = function (name, options, scene) {
  35738. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  35739. };
  35740. /**
  35741. * Creates a decal mesh.
  35742. * Please consider using the same method from the MeshBuilder class instead.
  35743. * A decal is a mesh usually applied as a model onto the surface of another mesh
  35744. * @param name defines the name of the mesh
  35745. * @param sourceMesh defines the mesh receiving the decal
  35746. * @param position sets the position of the decal in world coordinates
  35747. * @param normal sets the normal of the mesh where the decal is applied onto in world coordinates
  35748. * @param size sets the decal scaling
  35749. * @param angle sets the angle to rotate the decal
  35750. * @returns a new Mesh
  35751. */
  35752. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  35753. var options = {
  35754. position: position,
  35755. normal: normal,
  35756. size: size,
  35757. angle: angle
  35758. };
  35759. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  35760. };
  35761. // Skeletons
  35762. /**
  35763. * Prepare internal position array for software CPU skinning
  35764. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh
  35765. */
  35766. Mesh.prototype.setPositionsForCPUSkinning = function () {
  35767. if (!this._sourcePositions) {
  35768. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35769. if (!source) {
  35770. return this._sourcePositions;
  35771. }
  35772. this._sourcePositions = new Float32Array(source);
  35773. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  35774. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  35775. }
  35776. }
  35777. return this._sourcePositions;
  35778. };
  35779. /**
  35780. * Prepare internal normal array for software CPU skinning
  35781. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  35782. */
  35783. Mesh.prototype.setNormalsForCPUSkinning = function () {
  35784. if (!this._sourceNormals) {
  35785. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  35786. if (!source) {
  35787. return this._sourceNormals;
  35788. }
  35789. this._sourceNormals = new Float32Array(source);
  35790. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  35791. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  35792. }
  35793. }
  35794. return this._sourceNormals;
  35795. };
  35796. /**
  35797. * Updates the vertex buffer by applying transformation from the bones
  35798. * @param skeleton defines the skeleton to apply to current mesh
  35799. * @returns the current mesh
  35800. */
  35801. Mesh.prototype.applySkeleton = function (skeleton) {
  35802. if (!this.geometry) {
  35803. return this;
  35804. }
  35805. if (this.geometry._softwareSkinningFrameId == this.getScene().getFrameId()) {
  35806. return this;
  35807. }
  35808. this.geometry._softwareSkinningFrameId = this.getScene().getFrameId();
  35809. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  35810. return this;
  35811. }
  35812. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  35813. return this;
  35814. }
  35815. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  35816. return this;
  35817. }
  35818. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  35819. return this;
  35820. }
  35821. if (!this._sourcePositions) {
  35822. var submeshes = this.subMeshes.slice();
  35823. this.setPositionsForCPUSkinning();
  35824. this.subMeshes = submeshes;
  35825. }
  35826. if (!this._sourceNormals) {
  35827. this.setNormalsForCPUSkinning();
  35828. }
  35829. // positionsData checks for not being Float32Array will only pass at most once
  35830. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35831. if (!positionsData) {
  35832. return this;
  35833. }
  35834. if (!(positionsData instanceof Float32Array)) {
  35835. positionsData = new Float32Array(positionsData);
  35836. }
  35837. // normalsData checks for not being Float32Array will only pass at most once
  35838. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  35839. if (!normalsData) {
  35840. return this;
  35841. }
  35842. if (!(normalsData instanceof Float32Array)) {
  35843. normalsData = new Float32Array(normalsData);
  35844. }
  35845. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  35846. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  35847. if (!matricesWeightsData || !matricesIndicesData) {
  35848. return this;
  35849. }
  35850. var needExtras = this.numBoneInfluencers > 4;
  35851. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  35852. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  35853. var skeletonMatrices = skeleton.getTransformMatrices(this);
  35854. var tempVector3 = BABYLON.Vector3.Zero();
  35855. var finalMatrix = new BABYLON.Matrix();
  35856. var tempMatrix = new BABYLON.Matrix();
  35857. var matWeightIdx = 0;
  35858. var inf;
  35859. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  35860. var weight;
  35861. for (inf = 0; inf < 4; inf++) {
  35862. weight = matricesWeightsData[matWeightIdx + inf];
  35863. if (weight > 0) {
  35864. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  35865. finalMatrix.addToSelf(tempMatrix);
  35866. }
  35867. }
  35868. if (needExtras) {
  35869. for (inf = 0; inf < 4; inf++) {
  35870. weight = matricesWeightsExtraData[matWeightIdx + inf];
  35871. if (weight > 0) {
  35872. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  35873. finalMatrix.addToSelf(tempMatrix);
  35874. }
  35875. }
  35876. }
  35877. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  35878. tempVector3.toArray(positionsData, index);
  35879. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  35880. tempVector3.toArray(normalsData, index);
  35881. finalMatrix.reset();
  35882. }
  35883. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  35884. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  35885. return this;
  35886. };
  35887. // Tools
  35888. /**
  35889. * 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
  35890. * @param meshes defines the list of meshes to scan
  35891. * @returns an object `{min:` Vector3`, max:` Vector3`}`
  35892. */
  35893. Mesh.MinMax = function (meshes) {
  35894. var minVector = null;
  35895. var maxVector = null;
  35896. meshes.forEach(function (mesh, index, array) {
  35897. var boundingInfo = mesh.getBoundingInfo();
  35898. var boundingBox = boundingInfo.boundingBox;
  35899. if (!minVector || !maxVector) {
  35900. minVector = boundingBox.minimumWorld;
  35901. maxVector = boundingBox.maximumWorld;
  35902. }
  35903. else {
  35904. minVector.minimizeInPlace(boundingBox.minimumWorld);
  35905. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  35906. }
  35907. });
  35908. if (!minVector || !maxVector) {
  35909. return {
  35910. min: BABYLON.Vector3.Zero(),
  35911. max: BABYLON.Vector3.Zero()
  35912. };
  35913. }
  35914. return {
  35915. min: minVector,
  35916. max: maxVector
  35917. };
  35918. };
  35919. /**
  35920. * Returns the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array
  35921. * @param meshesOrMinMaxVector could be an array of meshes or a `{min:` Vector3`, max:` Vector3`}` object
  35922. * @returns a vector3
  35923. */
  35924. Mesh.Center = function (meshesOrMinMaxVector) {
  35925. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  35926. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  35927. };
  35928. /**
  35929. * Merge the array of meshes into a single mesh for performance reasons.
  35930. * @param meshes defines he vertices source. They should all be of the same material. Entries can empty
  35931. * @param disposeSource when true (default), dispose of the vertices from the source meshes
  35932. * @param allow32BitsIndices when the sum of the vertices > 64k, this must be set to true
  35933. * @param meshSubclass when set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  35934. * @param subdivideWithSubMeshes when true (false default), subdivide mesh to his subMesh array with meshes source.
  35935. * @returns a new mesh
  35936. */
  35937. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  35938. if (disposeSource === void 0) { disposeSource = true; }
  35939. var index;
  35940. if (!allow32BitsIndices) {
  35941. var totalVertices = 0;
  35942. // Counting vertices
  35943. for (index = 0; index < meshes.length; index++) {
  35944. if (meshes[index]) {
  35945. totalVertices += meshes[index].getTotalVertices();
  35946. if (totalVertices > 65536) {
  35947. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  35948. return null;
  35949. }
  35950. }
  35951. }
  35952. }
  35953. // Merge
  35954. var vertexData = null;
  35955. var otherVertexData;
  35956. var indiceArray = new Array();
  35957. var source = null;
  35958. for (index = 0; index < meshes.length; index++) {
  35959. if (meshes[index]) {
  35960. var wm = meshes[index].computeWorldMatrix(true);
  35961. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true, true);
  35962. otherVertexData.transform(wm);
  35963. if (vertexData) {
  35964. vertexData.merge(otherVertexData, allow32BitsIndices);
  35965. }
  35966. else {
  35967. vertexData = otherVertexData;
  35968. source = meshes[index];
  35969. }
  35970. if (subdivideWithSubMeshes) {
  35971. indiceArray.push(meshes[index].getTotalIndices());
  35972. }
  35973. }
  35974. }
  35975. source = source;
  35976. if (!meshSubclass) {
  35977. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  35978. }
  35979. vertexData.applyToMesh(meshSubclass);
  35980. // Setting properties
  35981. meshSubclass.material = source.material;
  35982. meshSubclass.checkCollisions = source.checkCollisions;
  35983. // Cleaning
  35984. if (disposeSource) {
  35985. for (index = 0; index < meshes.length; index++) {
  35986. if (meshes[index]) {
  35987. meshes[index].dispose();
  35988. }
  35989. }
  35990. }
  35991. // Subdivide
  35992. if (subdivideWithSubMeshes) {
  35993. //-- removal of global submesh
  35994. meshSubclass.releaseSubMeshes();
  35995. index = 0;
  35996. var offset = 0;
  35997. //-- apply subdivision according to index table
  35998. while (index < indiceArray.length) {
  35999. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  36000. offset += indiceArray[index];
  36001. index++;
  36002. }
  36003. }
  36004. return meshSubclass;
  36005. };
  36006. /** @hidden */
  36007. Mesh.prototype.addInstance = function (instance) {
  36008. instance._indexInSourceMeshInstanceArray = this.instances.length;
  36009. this.instances.push(instance);
  36010. };
  36011. /** @hidden */
  36012. Mesh.prototype.removeInstance = function (instance) {
  36013. // Remove from mesh
  36014. var index = instance._indexInSourceMeshInstanceArray;
  36015. if (index != -1) {
  36016. if (index !== this.instances.length - 1) {
  36017. var last = this.instances[this.instances.length - 1];
  36018. this.instances[index] = last;
  36019. last._indexInSourceMeshInstanceArray = index;
  36020. }
  36021. instance._indexInSourceMeshInstanceArray = -1;
  36022. this.instances.pop();
  36023. }
  36024. };
  36025. // Consts
  36026. /**
  36027. * Mesh side orientation : usually the external or front surface
  36028. */
  36029. Mesh.FRONTSIDE = 0;
  36030. /**
  36031. * Mesh side orientation : usually the internal or back surface
  36032. */
  36033. Mesh.BACKSIDE = 1;
  36034. /**
  36035. * Mesh side orientation : both internal and external or front and back surfaces
  36036. */
  36037. Mesh.DOUBLESIDE = 2;
  36038. /**
  36039. * Mesh side orientation : by default, `FRONTSIDE`
  36040. */
  36041. Mesh.DEFAULTSIDE = 0;
  36042. /**
  36043. * Mesh cap setting : no cap
  36044. */
  36045. Mesh.NO_CAP = 0;
  36046. /**
  36047. * Mesh cap setting : one cap at the beginning of the mesh
  36048. */
  36049. Mesh.CAP_START = 1;
  36050. /**
  36051. * Mesh cap setting : one cap at the end of the mesh
  36052. */
  36053. Mesh.CAP_END = 2;
  36054. /**
  36055. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  36056. */
  36057. Mesh.CAP_ALL = 3;
  36058. return Mesh;
  36059. }(BABYLON.AbstractMesh));
  36060. BABYLON.Mesh = Mesh;
  36061. })(BABYLON || (BABYLON = {}));
  36062. //# sourceMappingURL=babylon.mesh.js.map
  36063. var BABYLON;
  36064. (function (BABYLON) {
  36065. /**
  36066. * Base class for submeshes
  36067. */
  36068. var BaseSubMesh = /** @class */ (function () {
  36069. function BaseSubMesh() {
  36070. }
  36071. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  36072. /**
  36073. * Gets associated effect
  36074. */
  36075. get: function () {
  36076. return this._materialEffect;
  36077. },
  36078. enumerable: true,
  36079. configurable: true
  36080. });
  36081. /**
  36082. * Sets associated effect (effect used to render this submesh)
  36083. * @param effect defines the effect to associate with
  36084. * @param defines defines the set of defines used to compile this effect
  36085. */
  36086. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  36087. if (defines === void 0) { defines = null; }
  36088. if (this._materialEffect === effect) {
  36089. if (!effect) {
  36090. this._materialDefines = null;
  36091. }
  36092. return;
  36093. }
  36094. this._materialDefines = defines;
  36095. this._materialEffect = effect;
  36096. };
  36097. return BaseSubMesh;
  36098. }());
  36099. BABYLON.BaseSubMesh = BaseSubMesh;
  36100. /**
  36101. * Defines a subdivision inside a mesh
  36102. */
  36103. var SubMesh = /** @class */ (function (_super) {
  36104. __extends(SubMesh, _super);
  36105. /**
  36106. * Creates a new submesh
  36107. * @param materialIndex defines the material index to use
  36108. * @param verticesStart defines vertex index start
  36109. * @param verticesCount defines vertices count
  36110. * @param indexStart defines index start
  36111. * @param indexCount defines indices count
  36112. * @param mesh defines the parent mesh
  36113. * @param renderingMesh defines an optional rendering mesh
  36114. * @param createBoundingBox defines if bounding box should be created for this submesh
  36115. */
  36116. function SubMesh(
  36117. /** the material index to use */
  36118. materialIndex,
  36119. /** vertex index start */
  36120. verticesStart,
  36121. /** vertices count */
  36122. verticesCount,
  36123. /** index start */
  36124. indexStart,
  36125. /** indices count */
  36126. indexCount, mesh, renderingMesh, createBoundingBox) {
  36127. if (createBoundingBox === void 0) { createBoundingBox = true; }
  36128. var _this = _super.call(this) || this;
  36129. _this.materialIndex = materialIndex;
  36130. _this.verticesStart = verticesStart;
  36131. _this.verticesCount = verticesCount;
  36132. _this.indexStart = indexStart;
  36133. _this.indexCount = indexCount;
  36134. /** @hidden */
  36135. _this._renderId = 0;
  36136. _this._mesh = mesh;
  36137. _this._renderingMesh = renderingMesh || mesh;
  36138. mesh.subMeshes.push(_this);
  36139. _this._trianglePlanes = [];
  36140. _this._id = mesh.subMeshes.length - 1;
  36141. if (createBoundingBox) {
  36142. _this.refreshBoundingInfo();
  36143. mesh.computeWorldMatrix(true);
  36144. }
  36145. return _this;
  36146. }
  36147. /**
  36148. * Add a new submesh to a mesh
  36149. * @param materialIndex defines the material index to use
  36150. * @param verticesStart defines vertex index start
  36151. * @param verticesCount defines vertices count
  36152. * @param indexStart defines index start
  36153. * @param indexCount defines indices count
  36154. * @param mesh defines the parent mesh
  36155. * @param renderingMesh defines an optional rendering mesh
  36156. * @param createBoundingBox defines if bounding box should be created for this submesh
  36157. * @returns the new submesh
  36158. */
  36159. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  36160. if (createBoundingBox === void 0) { createBoundingBox = true; }
  36161. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  36162. };
  36163. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  36164. /**
  36165. * Returns true if this submesh covers the entire parent mesh
  36166. * @ignorenaming
  36167. */
  36168. get: function () {
  36169. return (this.verticesStart === 0 && this.verticesCount === this._mesh.getTotalVertices());
  36170. },
  36171. enumerable: true,
  36172. configurable: true
  36173. });
  36174. /**
  36175. * Returns the submesh BoudingInfo object
  36176. * @returns current bounding info (or mesh's one if the submesh is global)
  36177. */
  36178. SubMesh.prototype.getBoundingInfo = function () {
  36179. if (this.IsGlobal) {
  36180. return this._mesh.getBoundingInfo();
  36181. }
  36182. return this._boundingInfo;
  36183. };
  36184. /**
  36185. * Sets the submesh BoundingInfo
  36186. * @param boundingInfo defines the new bounding info to use
  36187. * @returns the SubMesh
  36188. */
  36189. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  36190. this._boundingInfo = boundingInfo;
  36191. return this;
  36192. };
  36193. /**
  36194. * Returns the mesh of the current submesh
  36195. * @return the parent mesh
  36196. */
  36197. SubMesh.prototype.getMesh = function () {
  36198. return this._mesh;
  36199. };
  36200. /**
  36201. * Returns the rendering mesh of the submesh
  36202. * @returns the rendering mesh (could be different from parent mesh)
  36203. */
  36204. SubMesh.prototype.getRenderingMesh = function () {
  36205. return this._renderingMesh;
  36206. };
  36207. /**
  36208. * Returns the submesh material
  36209. * @returns null or the current material
  36210. */
  36211. SubMesh.prototype.getMaterial = function () {
  36212. var rootMaterial = this._renderingMesh.material;
  36213. if (rootMaterial === null || rootMaterial === undefined) {
  36214. return this._mesh.getScene().defaultMaterial;
  36215. }
  36216. else if (rootMaterial.getSubMaterial) {
  36217. var multiMaterial = rootMaterial;
  36218. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  36219. if (this._currentMaterial !== effectiveMaterial) {
  36220. this._currentMaterial = effectiveMaterial;
  36221. this._materialDefines = null;
  36222. }
  36223. return effectiveMaterial;
  36224. }
  36225. return rootMaterial;
  36226. };
  36227. // Methods
  36228. /**
  36229. * Sets a new updated BoundingInfo object to the submesh
  36230. * @returns the SubMesh
  36231. */
  36232. SubMesh.prototype.refreshBoundingInfo = function () {
  36233. this._lastColliderWorldVertices = null;
  36234. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  36235. return this;
  36236. }
  36237. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  36238. if (!data) {
  36239. this._boundingInfo = this._mesh.getBoundingInfo();
  36240. return this;
  36241. }
  36242. var indices = this._renderingMesh.getIndices();
  36243. var extend;
  36244. //is this the only submesh?
  36245. if (this.indexStart === 0 && this.indexCount === indices.length) {
  36246. var boundingInfo = this._renderingMesh.getBoundingInfo();
  36247. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  36248. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  36249. }
  36250. else {
  36251. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  36252. }
  36253. if (this._boundingInfo) {
  36254. this._boundingInfo.reConstruct(extend.minimum, extend.maximum);
  36255. }
  36256. else {
  36257. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  36258. }
  36259. return this;
  36260. };
  36261. /** @hidden */
  36262. SubMesh.prototype._checkCollision = function (collider) {
  36263. var boundingInfo = this.getBoundingInfo();
  36264. return boundingInfo._checkCollision(collider);
  36265. };
  36266. /**
  36267. * Updates the submesh BoundingInfo
  36268. * @param world defines the world matrix to use to update the bounding info
  36269. * @returns the submesh
  36270. */
  36271. SubMesh.prototype.updateBoundingInfo = function (world) {
  36272. var boundingInfo = this.getBoundingInfo();
  36273. if (!boundingInfo) {
  36274. this.refreshBoundingInfo();
  36275. boundingInfo = this.getBoundingInfo();
  36276. }
  36277. boundingInfo.update(world);
  36278. return this;
  36279. };
  36280. /**
  36281. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  36282. * @param frustumPlanes defines the frustum planes
  36283. * @returns true if the submesh is intersecting with the frustum
  36284. */
  36285. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  36286. var boundingInfo = this.getBoundingInfo();
  36287. if (!boundingInfo) {
  36288. return false;
  36289. }
  36290. return boundingInfo.isInFrustum(frustumPlanes, this._mesh.cullingStrategy);
  36291. };
  36292. /**
  36293. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes
  36294. * @param frustumPlanes defines the frustum planes
  36295. * @returns true if the submesh is inside the frustum
  36296. */
  36297. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  36298. var boundingInfo = this.getBoundingInfo();
  36299. if (!boundingInfo) {
  36300. return false;
  36301. }
  36302. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  36303. };
  36304. /**
  36305. * Renders the submesh
  36306. * @param enableAlphaMode defines if alpha needs to be used
  36307. * @returns the submesh
  36308. */
  36309. SubMesh.prototype.render = function (enableAlphaMode) {
  36310. this._renderingMesh.render(this, enableAlphaMode);
  36311. return this;
  36312. };
  36313. /**
  36314. * @hidden
  36315. */
  36316. SubMesh.prototype._getLinesIndexBuffer = function (indices, engine) {
  36317. if (!this._linesIndexBuffer) {
  36318. var linesIndices = [];
  36319. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  36320. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  36321. }
  36322. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  36323. this._linesIndexCount = linesIndices.length;
  36324. }
  36325. return this._linesIndexBuffer;
  36326. };
  36327. /**
  36328. * Checks if the submesh intersects with a ray
  36329. * @param ray defines the ray to test
  36330. * @returns true is the passed ray intersects the submesh bounding box
  36331. */
  36332. SubMesh.prototype.canIntersects = function (ray) {
  36333. var boundingInfo = this.getBoundingInfo();
  36334. if (!boundingInfo) {
  36335. return false;
  36336. }
  36337. return ray.intersectsBox(boundingInfo.boundingBox);
  36338. };
  36339. /**
  36340. * Intersects current submesh with a ray
  36341. * @param ray defines the ray to test
  36342. * @param positions defines mesh's positions array
  36343. * @param indices defines mesh's indices array
  36344. * @param fastCheck defines if only bounding info should be used
  36345. * @returns intersection info or null if no intersection
  36346. */
  36347. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  36348. var material = this.getMaterial();
  36349. if (!material) {
  36350. return null;
  36351. }
  36352. switch (material.fillMode) {
  36353. case BABYLON.Material.PointListDrawMode:
  36354. case BABYLON.Material.LineListDrawMode:
  36355. case BABYLON.Material.LineLoopDrawMode:
  36356. case BABYLON.Material.LineStripDrawMode:
  36357. case BABYLON.Material.TriangleFanDrawMode:
  36358. case BABYLON.Material.TriangleStripDrawMode:
  36359. return null;
  36360. }
  36361. // LineMesh first as it's also a Mesh...
  36362. if (BABYLON.LinesMesh) {
  36363. if (this._mesh.getClassName() === "InstancedLinesMesh" || this._mesh.getClassName() === "LinesMesh") {
  36364. return this._intersectLines(ray, positions, indices, this._mesh.intersectionThreshold, fastCheck);
  36365. }
  36366. }
  36367. return this._intersectTriangles(ray, positions, indices, fastCheck);
  36368. };
  36369. /** @hidden */
  36370. SubMesh.prototype._intersectLines = function (ray, positions, indices, intersectionThreshold, fastCheck) {
  36371. var intersectInfo = null;
  36372. // Line test
  36373. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  36374. var p0 = positions[indices[index]];
  36375. var p1 = positions[indices[index + 1]];
  36376. var length = ray.intersectionSegment(p0, p1, intersectionThreshold);
  36377. if (length < 0) {
  36378. continue;
  36379. }
  36380. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  36381. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  36382. if (fastCheck) {
  36383. break;
  36384. }
  36385. }
  36386. }
  36387. return intersectInfo;
  36388. };
  36389. /** @hidden */
  36390. SubMesh.prototype._intersectTriangles = function (ray, positions, indices, fastCheck) {
  36391. var intersectInfo = null;
  36392. // Triangles test
  36393. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  36394. var p0 = positions[indices[index]];
  36395. var p1 = positions[indices[index + 1]];
  36396. var p2 = positions[indices[index + 2]];
  36397. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  36398. if (currentIntersectInfo) {
  36399. if (currentIntersectInfo.distance < 0) {
  36400. continue;
  36401. }
  36402. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  36403. intersectInfo = currentIntersectInfo;
  36404. intersectInfo.faceId = index / 3;
  36405. if (fastCheck) {
  36406. break;
  36407. }
  36408. }
  36409. }
  36410. }
  36411. return intersectInfo;
  36412. };
  36413. /** @hidden */
  36414. SubMesh.prototype._rebuild = function () {
  36415. if (this._linesIndexBuffer) {
  36416. this._linesIndexBuffer = null;
  36417. }
  36418. };
  36419. // Clone
  36420. /**
  36421. * Creates a new submesh from the passed mesh
  36422. * @param newMesh defines the new hosting mesh
  36423. * @param newRenderingMesh defines an optional rendering mesh
  36424. * @returns the new submesh
  36425. */
  36426. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  36427. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  36428. if (!this.IsGlobal) {
  36429. var boundingInfo = this.getBoundingInfo();
  36430. if (!boundingInfo) {
  36431. return result;
  36432. }
  36433. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  36434. }
  36435. return result;
  36436. };
  36437. // Dispose
  36438. /**
  36439. * Release associated resources
  36440. */
  36441. SubMesh.prototype.dispose = function () {
  36442. if (this._linesIndexBuffer) {
  36443. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  36444. this._linesIndexBuffer = null;
  36445. }
  36446. // Remove from mesh
  36447. var index = this._mesh.subMeshes.indexOf(this);
  36448. this._mesh.subMeshes.splice(index, 1);
  36449. };
  36450. // Statics
  36451. /**
  36452. * Creates a new submesh from indices data
  36453. * @param materialIndex the index of the main mesh material
  36454. * @param startIndex the index where to start the copy in the mesh indices array
  36455. * @param indexCount the number of indices to copy then from the startIndex
  36456. * @param mesh the main mesh to create the submesh from
  36457. * @param renderingMesh the optional rendering mesh
  36458. * @returns a new submesh
  36459. */
  36460. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  36461. var minVertexIndex = Number.MAX_VALUE;
  36462. var maxVertexIndex = -Number.MAX_VALUE;
  36463. renderingMesh = (renderingMesh || mesh);
  36464. var indices = renderingMesh.getIndices();
  36465. for (var index = startIndex; index < startIndex + indexCount; index++) {
  36466. var vertexIndex = indices[index];
  36467. if (vertexIndex < minVertexIndex) {
  36468. minVertexIndex = vertexIndex;
  36469. }
  36470. if (vertexIndex > maxVertexIndex) {
  36471. maxVertexIndex = vertexIndex;
  36472. }
  36473. }
  36474. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  36475. };
  36476. return SubMesh;
  36477. }(BaseSubMesh));
  36478. BABYLON.SubMesh = SubMesh;
  36479. })(BABYLON || (BABYLON = {}));
  36480. //# sourceMappingURL=babylon.subMesh.js.map
  36481. var __assign = (this && this.__assign) || function () {
  36482. __assign = Object.assign || function(t) {
  36483. for (var s, i = 1, n = arguments.length; i < n; i++) {
  36484. s = arguments[i];
  36485. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  36486. t[p] = s[p];
  36487. }
  36488. return t;
  36489. };
  36490. return __assign.apply(this, arguments);
  36491. };
  36492. var BABYLON;
  36493. (function (BABYLON) {
  36494. /**
  36495. * Manages the defines for the Material
  36496. */
  36497. var MaterialDefines = /** @class */ (function () {
  36498. function MaterialDefines() {
  36499. this._isDirty = true;
  36500. /** @hidden */
  36501. this._areLightsDirty = true;
  36502. /** @hidden */
  36503. this._areAttributesDirty = true;
  36504. /** @hidden */
  36505. this._areTexturesDirty = true;
  36506. /** @hidden */
  36507. this._areFresnelDirty = true;
  36508. /** @hidden */
  36509. this._areMiscDirty = true;
  36510. /** @hidden */
  36511. this._areImageProcessingDirty = true;
  36512. /** @hidden */
  36513. this._normals = false;
  36514. /** @hidden */
  36515. this._uvs = false;
  36516. /** @hidden */
  36517. this._needNormals = false;
  36518. /** @hidden */
  36519. this._needUVs = false;
  36520. }
  36521. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  36522. /**
  36523. * Specifies if the material needs to be re-calculated
  36524. */
  36525. get: function () {
  36526. return this._isDirty;
  36527. },
  36528. enumerable: true,
  36529. configurable: true
  36530. });
  36531. /**
  36532. * Marks the material to indicate that it has been re-calculated
  36533. */
  36534. MaterialDefines.prototype.markAsProcessed = function () {
  36535. this._isDirty = false;
  36536. this._areAttributesDirty = false;
  36537. this._areTexturesDirty = false;
  36538. this._areFresnelDirty = false;
  36539. this._areLightsDirty = false;
  36540. this._areMiscDirty = false;
  36541. this._areImageProcessingDirty = false;
  36542. };
  36543. /**
  36544. * Marks the material to indicate that it needs to be re-calculated
  36545. */
  36546. MaterialDefines.prototype.markAsUnprocessed = function () {
  36547. this._isDirty = true;
  36548. };
  36549. /**
  36550. * Marks the material to indicate all of its defines need to be re-calculated
  36551. */
  36552. MaterialDefines.prototype.markAllAsDirty = function () {
  36553. this._areTexturesDirty = true;
  36554. this._areAttributesDirty = true;
  36555. this._areLightsDirty = true;
  36556. this._areFresnelDirty = true;
  36557. this._areMiscDirty = true;
  36558. this._areImageProcessingDirty = true;
  36559. this._isDirty = true;
  36560. };
  36561. /**
  36562. * Marks the material to indicate that image processing needs to be re-calculated
  36563. */
  36564. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  36565. this._areImageProcessingDirty = true;
  36566. this._isDirty = true;
  36567. };
  36568. /**
  36569. * Marks the material to indicate the lights need to be re-calculated
  36570. */
  36571. MaterialDefines.prototype.markAsLightDirty = function () {
  36572. this._areLightsDirty = true;
  36573. this._isDirty = true;
  36574. };
  36575. /**
  36576. * Marks the attribute state as changed
  36577. */
  36578. MaterialDefines.prototype.markAsAttributesDirty = function () {
  36579. this._areAttributesDirty = true;
  36580. this._isDirty = true;
  36581. };
  36582. /**
  36583. * Marks the texture state as changed
  36584. */
  36585. MaterialDefines.prototype.markAsTexturesDirty = function () {
  36586. this._areTexturesDirty = true;
  36587. this._isDirty = true;
  36588. };
  36589. /**
  36590. * Marks the fresnel state as changed
  36591. */
  36592. MaterialDefines.prototype.markAsFresnelDirty = function () {
  36593. this._areFresnelDirty = true;
  36594. this._isDirty = true;
  36595. };
  36596. /**
  36597. * Marks the misc state as changed
  36598. */
  36599. MaterialDefines.prototype.markAsMiscDirty = function () {
  36600. this._areMiscDirty = true;
  36601. this._isDirty = true;
  36602. };
  36603. /**
  36604. * Rebuilds the material defines
  36605. */
  36606. MaterialDefines.prototype.rebuild = function () {
  36607. if (this._keys) {
  36608. delete this._keys;
  36609. }
  36610. this._keys = [];
  36611. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  36612. var key = _a[_i];
  36613. if (key[0] === "_") {
  36614. continue;
  36615. }
  36616. this._keys.push(key);
  36617. }
  36618. };
  36619. /**
  36620. * Specifies if two material defines are equal
  36621. * @param other - A material define instance to compare to
  36622. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  36623. */
  36624. MaterialDefines.prototype.isEqual = function (other) {
  36625. if (this._keys.length !== other._keys.length) {
  36626. return false;
  36627. }
  36628. for (var index = 0; index < this._keys.length; index++) {
  36629. var prop = this._keys[index];
  36630. if (this[prop] !== other[prop]) {
  36631. return false;
  36632. }
  36633. }
  36634. return true;
  36635. };
  36636. /**
  36637. * Clones this instance's defines to another instance
  36638. * @param other - material defines to clone values to
  36639. */
  36640. MaterialDefines.prototype.cloneTo = function (other) {
  36641. if (this._keys.length !== other._keys.length) {
  36642. other._keys = this._keys.slice(0);
  36643. }
  36644. for (var index = 0; index < this._keys.length; index++) {
  36645. var prop = this._keys[index];
  36646. other[prop] = this[prop];
  36647. }
  36648. };
  36649. /**
  36650. * Resets the material define values
  36651. */
  36652. MaterialDefines.prototype.reset = function () {
  36653. for (var index = 0; index < this._keys.length; index++) {
  36654. var prop = this._keys[index];
  36655. var type = typeof this[prop];
  36656. switch (type) {
  36657. case "number":
  36658. this[prop] = 0;
  36659. break;
  36660. case "string":
  36661. this[prop] = "";
  36662. break;
  36663. default:
  36664. this[prop] = false;
  36665. break;
  36666. }
  36667. }
  36668. };
  36669. /**
  36670. * Converts the material define values to a string
  36671. * @returns - String of material define information
  36672. */
  36673. MaterialDefines.prototype.toString = function () {
  36674. var result = "";
  36675. for (var index = 0; index < this._keys.length; index++) {
  36676. var prop = this._keys[index];
  36677. var value = this[prop];
  36678. var type = typeof value;
  36679. switch (type) {
  36680. case "number":
  36681. case "string":
  36682. result += "#define " + prop + " " + value + "\n";
  36683. break;
  36684. default:
  36685. if (value) {
  36686. result += "#define " + prop + "\n";
  36687. }
  36688. break;
  36689. }
  36690. }
  36691. return result;
  36692. };
  36693. return MaterialDefines;
  36694. }());
  36695. BABYLON.MaterialDefines = MaterialDefines;
  36696. /**
  36697. * Base class for the main features of a material in Babylon.js
  36698. */
  36699. var Material = /** @class */ (function () {
  36700. /**
  36701. * Creates a material instance
  36702. * @param name defines the name of the material
  36703. * @param scene defines the scene to reference
  36704. * @param doNotAdd specifies if the material should be added to the scene
  36705. */
  36706. function Material(name, scene, doNotAdd) {
  36707. /**
  36708. * Gets or sets user defined metadata
  36709. */
  36710. this.metadata = null;
  36711. /**
  36712. * Specifies if the ready state should be checked on each call
  36713. */
  36714. this.checkReadyOnEveryCall = false;
  36715. /**
  36716. * Specifies if the ready state should be checked once
  36717. */
  36718. this.checkReadyOnlyOnce = false;
  36719. /**
  36720. * The state of the material
  36721. */
  36722. this.state = "";
  36723. /**
  36724. * The alpha value of the material
  36725. */
  36726. this._alpha = 1.0;
  36727. /**
  36728. * Specifies if back face culling is enabled
  36729. */
  36730. this._backFaceCulling = true;
  36731. /**
  36732. * Specifies if the material should be serialized
  36733. */
  36734. this.doNotSerialize = false;
  36735. /**
  36736. * @hidden
  36737. */
  36738. this._storeEffectOnSubMeshes = false;
  36739. /**
  36740. * An event triggered when the material is disposed
  36741. */
  36742. this.onDisposeObservable = new BABYLON.Observable();
  36743. /**
  36744. * Stores the value of the alpha mode
  36745. */
  36746. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  36747. /**
  36748. * Stores the state of the need depth pre-pass value
  36749. */
  36750. this._needDepthPrePass = false;
  36751. /**
  36752. * Specifies if depth writing should be disabled
  36753. */
  36754. this.disableDepthWrite = false;
  36755. /**
  36756. * Specifies if depth writing should be forced
  36757. */
  36758. this.forceDepthWrite = false;
  36759. /**
  36760. * Specifies if there should be a separate pass for culling
  36761. */
  36762. this.separateCullingPass = false;
  36763. /**
  36764. * Stores the state specifing if fog should be enabled
  36765. */
  36766. this._fogEnabled = true;
  36767. /**
  36768. * Stores the size of points
  36769. */
  36770. this.pointSize = 1.0;
  36771. /**
  36772. * Stores the z offset value
  36773. */
  36774. this.zOffset = 0;
  36775. /**
  36776. * @hidden
  36777. * Specifies if the material was previously ready
  36778. */
  36779. this._wasPreviouslyReady = false;
  36780. /**
  36781. * Stores the fill mode state
  36782. */
  36783. this._fillMode = Material.TriangleFillMode;
  36784. /** @hidden */
  36785. this._indexInSceneMaterialArray = -1;
  36786. this.name = name;
  36787. this.id = name || BABYLON.Tools.RandomId();
  36788. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  36789. this.uniqueId = this._scene.getUniqueId();
  36790. if (this._scene.useRightHandedSystem) {
  36791. this.sideOrientation = Material.ClockWiseSideOrientation;
  36792. }
  36793. else {
  36794. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  36795. }
  36796. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  36797. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  36798. if (!doNotAdd) {
  36799. this._scene.addMaterial(this);
  36800. }
  36801. if (this._scene.useMaterialMeshMap) {
  36802. this.meshMap = {};
  36803. }
  36804. }
  36805. Object.defineProperty(Material, "TriangleFillMode", {
  36806. /**
  36807. * Returns the triangle fill mode
  36808. */
  36809. get: function () {
  36810. return Material._TriangleFillMode;
  36811. },
  36812. enumerable: true,
  36813. configurable: true
  36814. });
  36815. Object.defineProperty(Material, "WireFrameFillMode", {
  36816. /**
  36817. * Returns the wireframe mode
  36818. */
  36819. get: function () {
  36820. return Material._WireFrameFillMode;
  36821. },
  36822. enumerable: true,
  36823. configurable: true
  36824. });
  36825. Object.defineProperty(Material, "PointFillMode", {
  36826. /**
  36827. * Returns the point fill mode
  36828. */
  36829. get: function () {
  36830. return Material._PointFillMode;
  36831. },
  36832. enumerable: true,
  36833. configurable: true
  36834. });
  36835. Object.defineProperty(Material, "PointListDrawMode", {
  36836. /**
  36837. * Returns the point list draw mode
  36838. */
  36839. get: function () {
  36840. return Material._PointListDrawMode;
  36841. },
  36842. enumerable: true,
  36843. configurable: true
  36844. });
  36845. Object.defineProperty(Material, "LineListDrawMode", {
  36846. /**
  36847. * Returns the line list draw mode
  36848. */
  36849. get: function () {
  36850. return Material._LineListDrawMode;
  36851. },
  36852. enumerable: true,
  36853. configurable: true
  36854. });
  36855. Object.defineProperty(Material, "LineLoopDrawMode", {
  36856. /**
  36857. * Returns the line loop draw mode
  36858. */
  36859. get: function () {
  36860. return Material._LineLoopDrawMode;
  36861. },
  36862. enumerable: true,
  36863. configurable: true
  36864. });
  36865. Object.defineProperty(Material, "LineStripDrawMode", {
  36866. /**
  36867. * Returns the line strip draw mode
  36868. */
  36869. get: function () {
  36870. return Material._LineStripDrawMode;
  36871. },
  36872. enumerable: true,
  36873. configurable: true
  36874. });
  36875. Object.defineProperty(Material, "TriangleStripDrawMode", {
  36876. /**
  36877. * Returns the triangle strip draw mode
  36878. */
  36879. get: function () {
  36880. return Material._TriangleStripDrawMode;
  36881. },
  36882. enumerable: true,
  36883. configurable: true
  36884. });
  36885. Object.defineProperty(Material, "TriangleFanDrawMode", {
  36886. /**
  36887. * Returns the triangle fan draw mode
  36888. */
  36889. get: function () {
  36890. return Material._TriangleFanDrawMode;
  36891. },
  36892. enumerable: true,
  36893. configurable: true
  36894. });
  36895. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  36896. /**
  36897. * Returns the clock-wise side orientation
  36898. */
  36899. get: function () {
  36900. return Material._ClockWiseSideOrientation;
  36901. },
  36902. enumerable: true,
  36903. configurable: true
  36904. });
  36905. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  36906. /**
  36907. * Returns the counter clock-wise side orientation
  36908. */
  36909. get: function () {
  36910. return Material._CounterClockWiseSideOrientation;
  36911. },
  36912. enumerable: true,
  36913. configurable: true
  36914. });
  36915. Object.defineProperty(Material.prototype, "alpha", {
  36916. /**
  36917. * Gets the alpha value of the material
  36918. */
  36919. get: function () {
  36920. return this._alpha;
  36921. },
  36922. /**
  36923. * Sets the alpha value of the material
  36924. */
  36925. set: function (value) {
  36926. if (this._alpha === value) {
  36927. return;
  36928. }
  36929. this._alpha = value;
  36930. this.markAsDirty(Material.MiscDirtyFlag);
  36931. },
  36932. enumerable: true,
  36933. configurable: true
  36934. });
  36935. Object.defineProperty(Material.prototype, "backFaceCulling", {
  36936. /**
  36937. * Gets the back-face culling state
  36938. */
  36939. get: function () {
  36940. return this._backFaceCulling;
  36941. },
  36942. /**
  36943. * Sets the back-face culling state
  36944. */
  36945. set: function (value) {
  36946. if (this._backFaceCulling === value) {
  36947. return;
  36948. }
  36949. this._backFaceCulling = value;
  36950. this.markAsDirty(Material.TextureDirtyFlag);
  36951. },
  36952. enumerable: true,
  36953. configurable: true
  36954. });
  36955. Object.defineProperty(Material.prototype, "hasRenderTargetTextures", {
  36956. /**
  36957. * Gets a boolean indicating that current material needs to register RTT
  36958. */
  36959. get: function () {
  36960. return false;
  36961. },
  36962. enumerable: true,
  36963. configurable: true
  36964. });
  36965. Object.defineProperty(Material.prototype, "onDispose", {
  36966. /**
  36967. * Called during a dispose event
  36968. */
  36969. set: function (callback) {
  36970. if (this._onDisposeObserver) {
  36971. this.onDisposeObservable.remove(this._onDisposeObserver);
  36972. }
  36973. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  36974. },
  36975. enumerable: true,
  36976. configurable: true
  36977. });
  36978. Object.defineProperty(Material.prototype, "onBindObservable", {
  36979. /**
  36980. * An event triggered when the material is bound
  36981. */
  36982. get: function () {
  36983. if (!this._onBindObservable) {
  36984. this._onBindObservable = new BABYLON.Observable();
  36985. }
  36986. return this._onBindObservable;
  36987. },
  36988. enumerable: true,
  36989. configurable: true
  36990. });
  36991. Object.defineProperty(Material.prototype, "onBind", {
  36992. /**
  36993. * Called during a bind event
  36994. */
  36995. set: function (callback) {
  36996. if (this._onBindObserver) {
  36997. this.onBindObservable.remove(this._onBindObserver);
  36998. }
  36999. this._onBindObserver = this.onBindObservable.add(callback);
  37000. },
  37001. enumerable: true,
  37002. configurable: true
  37003. });
  37004. Object.defineProperty(Material.prototype, "onUnBindObservable", {
  37005. /**
  37006. * An event triggered when the material is unbound
  37007. */
  37008. get: function () {
  37009. if (!this._onUnBindObservable) {
  37010. this._onUnBindObservable = new BABYLON.Observable();
  37011. }
  37012. return this._onUnBindObservable;
  37013. },
  37014. enumerable: true,
  37015. configurable: true
  37016. });
  37017. Object.defineProperty(Material.prototype, "alphaMode", {
  37018. /**
  37019. * Gets the value of the alpha mode
  37020. */
  37021. get: function () {
  37022. return this._alphaMode;
  37023. },
  37024. /**
  37025. * Sets the value of the alpha mode.
  37026. *
  37027. * | Value | Type | Description |
  37028. * | --- | --- | --- |
  37029. * | 0 | ALPHA_DISABLE | |
  37030. * | 1 | ALPHA_ADD | |
  37031. * | 2 | ALPHA_COMBINE | |
  37032. * | 3 | ALPHA_SUBTRACT | |
  37033. * | 4 | ALPHA_MULTIPLY | |
  37034. * | 5 | ALPHA_MAXIMIZED | |
  37035. * | 6 | ALPHA_ONEONE | |
  37036. * | 7 | ALPHA_PREMULTIPLIED | |
  37037. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  37038. * | 9 | ALPHA_INTERPOLATE | |
  37039. * | 10 | ALPHA_SCREENMODE | |
  37040. *
  37041. */
  37042. set: function (value) {
  37043. if (this._alphaMode === value) {
  37044. return;
  37045. }
  37046. this._alphaMode = value;
  37047. this.markAsDirty(Material.TextureDirtyFlag);
  37048. },
  37049. enumerable: true,
  37050. configurable: true
  37051. });
  37052. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  37053. /**
  37054. * Gets the depth pre-pass value
  37055. */
  37056. get: function () {
  37057. return this._needDepthPrePass;
  37058. },
  37059. /**
  37060. * Sets the need depth pre-pass value
  37061. */
  37062. set: function (value) {
  37063. if (this._needDepthPrePass === value) {
  37064. return;
  37065. }
  37066. this._needDepthPrePass = value;
  37067. if (this._needDepthPrePass) {
  37068. this.checkReadyOnEveryCall = true;
  37069. }
  37070. },
  37071. enumerable: true,
  37072. configurable: true
  37073. });
  37074. Object.defineProperty(Material.prototype, "fogEnabled", {
  37075. /**
  37076. * Gets the value of the fog enabled state
  37077. */
  37078. get: function () {
  37079. return this._fogEnabled;
  37080. },
  37081. /**
  37082. * Sets the state for enabling fog
  37083. */
  37084. set: function (value) {
  37085. if (this._fogEnabled === value) {
  37086. return;
  37087. }
  37088. this._fogEnabled = value;
  37089. this.markAsDirty(Material.MiscDirtyFlag);
  37090. },
  37091. enumerable: true,
  37092. configurable: true
  37093. });
  37094. Object.defineProperty(Material.prototype, "wireframe", {
  37095. /**
  37096. * Gets a value specifying if wireframe mode is enabled
  37097. */
  37098. get: function () {
  37099. switch (this._fillMode) {
  37100. case Material.WireFrameFillMode:
  37101. case Material.LineListDrawMode:
  37102. case Material.LineLoopDrawMode:
  37103. case Material.LineStripDrawMode:
  37104. return true;
  37105. }
  37106. return this._scene.forceWireframe;
  37107. },
  37108. /**
  37109. * Sets the state of wireframe mode
  37110. */
  37111. set: function (value) {
  37112. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  37113. },
  37114. enumerable: true,
  37115. configurable: true
  37116. });
  37117. Object.defineProperty(Material.prototype, "pointsCloud", {
  37118. /**
  37119. * Gets the value specifying if point clouds are enabled
  37120. */
  37121. get: function () {
  37122. switch (this._fillMode) {
  37123. case Material.PointFillMode:
  37124. case Material.PointListDrawMode:
  37125. return true;
  37126. }
  37127. return this._scene.forcePointsCloud;
  37128. },
  37129. /**
  37130. * Sets the state of point cloud mode
  37131. */
  37132. set: function (value) {
  37133. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  37134. },
  37135. enumerable: true,
  37136. configurable: true
  37137. });
  37138. Object.defineProperty(Material.prototype, "fillMode", {
  37139. /**
  37140. * Gets the material fill mode
  37141. */
  37142. get: function () {
  37143. return this._fillMode;
  37144. },
  37145. /**
  37146. * Sets the material fill mode
  37147. */
  37148. set: function (value) {
  37149. if (this._fillMode === value) {
  37150. return;
  37151. }
  37152. this._fillMode = value;
  37153. this.markAsDirty(Material.MiscDirtyFlag);
  37154. },
  37155. enumerable: true,
  37156. configurable: true
  37157. });
  37158. /**
  37159. * Returns a string representation of the current material
  37160. * @param fullDetails defines a boolean indicating which levels of logging is desired
  37161. * @returns a string with material information
  37162. */
  37163. Material.prototype.toString = function (fullDetails) {
  37164. var ret = "Name: " + this.name;
  37165. if (fullDetails) {
  37166. }
  37167. return ret;
  37168. };
  37169. /**
  37170. * Gets the class name of the material
  37171. * @returns a string with the class name of the material
  37172. */
  37173. Material.prototype.getClassName = function () {
  37174. return "Material";
  37175. };
  37176. Object.defineProperty(Material.prototype, "isFrozen", {
  37177. /**
  37178. * Specifies if updates for the material been locked
  37179. */
  37180. get: function () {
  37181. return this.checkReadyOnlyOnce;
  37182. },
  37183. enumerable: true,
  37184. configurable: true
  37185. });
  37186. /**
  37187. * Locks updates for the material
  37188. */
  37189. Material.prototype.freeze = function () {
  37190. this.checkReadyOnlyOnce = true;
  37191. };
  37192. /**
  37193. * Unlocks updates for the material
  37194. */
  37195. Material.prototype.unfreeze = function () {
  37196. this.checkReadyOnlyOnce = false;
  37197. };
  37198. /**
  37199. * Specifies if the material is ready to be used
  37200. * @param mesh defines the mesh to check
  37201. * @param useInstances specifies if instances should be used
  37202. * @returns a boolean indicating if the material is ready to be used
  37203. */
  37204. Material.prototype.isReady = function (mesh, useInstances) {
  37205. return true;
  37206. };
  37207. /**
  37208. * Specifies that the submesh is ready to be used
  37209. * @param mesh defines the mesh to check
  37210. * @param subMesh defines which submesh to check
  37211. * @param useInstances specifies that instances should be used
  37212. * @returns a boolean indicating that the submesh is ready or not
  37213. */
  37214. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  37215. return false;
  37216. };
  37217. /**
  37218. * Returns the material effect
  37219. * @returns the effect associated with the material
  37220. */
  37221. Material.prototype.getEffect = function () {
  37222. return this._effect;
  37223. };
  37224. /**
  37225. * Returns the current scene
  37226. * @returns a Scene
  37227. */
  37228. Material.prototype.getScene = function () {
  37229. return this._scene;
  37230. };
  37231. /**
  37232. * Specifies if the material will require alpha blending
  37233. * @returns a boolean specifying if alpha blending is needed
  37234. */
  37235. Material.prototype.needAlphaBlending = function () {
  37236. return (this.alpha < 1.0);
  37237. };
  37238. /**
  37239. * Specifies if the mesh will require alpha blending
  37240. * @param mesh defines the mesh to check
  37241. * @returns a boolean specifying if alpha blending is needed for the mesh
  37242. */
  37243. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  37244. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  37245. };
  37246. /**
  37247. * Specifies if this material should be rendered in alpha test mode
  37248. * @returns a boolean specifying if an alpha test is needed.
  37249. */
  37250. Material.prototype.needAlphaTesting = function () {
  37251. return false;
  37252. };
  37253. /**
  37254. * Gets the texture used for the alpha test
  37255. * @returns the texture to use for alpha testing
  37256. */
  37257. Material.prototype.getAlphaTestTexture = function () {
  37258. return null;
  37259. };
  37260. /**
  37261. * Marks the material to indicate that it needs to be re-calculated
  37262. */
  37263. Material.prototype.markDirty = function () {
  37264. this._wasPreviouslyReady = false;
  37265. };
  37266. /** @hidden */
  37267. Material.prototype._preBind = function (effect, overrideOrientation) {
  37268. if (overrideOrientation === void 0) { overrideOrientation = null; }
  37269. var engine = this._scene.getEngine();
  37270. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  37271. var reverse = orientation === Material.ClockWiseSideOrientation;
  37272. engine.enableEffect(effect ? effect : this._effect);
  37273. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  37274. return reverse;
  37275. };
  37276. /**
  37277. * Binds the material to the mesh
  37278. * @param world defines the world transformation matrix
  37279. * @param mesh defines the mesh to bind the material to
  37280. */
  37281. Material.prototype.bind = function (world, mesh) {
  37282. };
  37283. /**
  37284. * Binds the submesh to the material
  37285. * @param world defines the world transformation matrix
  37286. * @param mesh defines the mesh containing the submesh
  37287. * @param subMesh defines the submesh to bind the material to
  37288. */
  37289. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  37290. };
  37291. /**
  37292. * Binds the world matrix to the material
  37293. * @param world defines the world transformation matrix
  37294. */
  37295. Material.prototype.bindOnlyWorldMatrix = function (world) {
  37296. };
  37297. /**
  37298. * Binds the scene's uniform buffer to the effect.
  37299. * @param effect defines the effect to bind to the scene uniform buffer
  37300. * @param sceneUbo defines the uniform buffer storing scene data
  37301. */
  37302. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  37303. sceneUbo.bindToEffect(effect, "Scene");
  37304. };
  37305. /**
  37306. * Binds the view matrix to the effect
  37307. * @param effect defines the effect to bind the view matrix to
  37308. */
  37309. Material.prototype.bindView = function (effect) {
  37310. if (!this._useUBO) {
  37311. effect.setMatrix("view", this.getScene().getViewMatrix());
  37312. }
  37313. else {
  37314. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  37315. }
  37316. };
  37317. /**
  37318. * Binds the view projection matrix to the effect
  37319. * @param effect defines the effect to bind the view projection matrix to
  37320. */
  37321. Material.prototype.bindViewProjection = function (effect) {
  37322. if (!this._useUBO) {
  37323. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  37324. }
  37325. else {
  37326. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  37327. }
  37328. };
  37329. /**
  37330. * Specifies if material alpha testing should be turned on for the mesh
  37331. * @param mesh defines the mesh to check
  37332. */
  37333. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  37334. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  37335. };
  37336. /**
  37337. * Processes to execute after binding the material to a mesh
  37338. * @param mesh defines the rendered mesh
  37339. */
  37340. Material.prototype._afterBind = function (mesh) {
  37341. this._scene._cachedMaterial = this;
  37342. if (mesh) {
  37343. this._scene._cachedVisibility = mesh.visibility;
  37344. }
  37345. else {
  37346. this._scene._cachedVisibility = 1;
  37347. }
  37348. if (this._onBindObservable && mesh) {
  37349. this._onBindObservable.notifyObservers(mesh);
  37350. }
  37351. if (this.disableDepthWrite) {
  37352. var engine = this._scene.getEngine();
  37353. this._cachedDepthWriteState = engine.getDepthWrite();
  37354. engine.setDepthWrite(false);
  37355. }
  37356. };
  37357. /**
  37358. * Unbinds the material from the mesh
  37359. */
  37360. Material.prototype.unbind = function () {
  37361. if (this._onUnBindObservable) {
  37362. this._onUnBindObservable.notifyObservers(this);
  37363. }
  37364. if (this.disableDepthWrite) {
  37365. var engine = this._scene.getEngine();
  37366. engine.setDepthWrite(this._cachedDepthWriteState);
  37367. }
  37368. };
  37369. /**
  37370. * Gets the active textures from the material
  37371. * @returns an array of textures
  37372. */
  37373. Material.prototype.getActiveTextures = function () {
  37374. return [];
  37375. };
  37376. /**
  37377. * Specifies if the material uses a texture
  37378. * @param texture defines the texture to check against the material
  37379. * @returns a boolean specifying if the material uses the texture
  37380. */
  37381. Material.prototype.hasTexture = function (texture) {
  37382. return false;
  37383. };
  37384. /**
  37385. * Makes a duplicate of the material, and gives it a new name
  37386. * @param name defines the new name for the duplicated material
  37387. * @returns the cloned material
  37388. */
  37389. Material.prototype.clone = function (name) {
  37390. return null;
  37391. };
  37392. /**
  37393. * Gets the meshes bound to the material
  37394. * @returns an array of meshes bound to the material
  37395. */
  37396. Material.prototype.getBindedMeshes = function () {
  37397. var _this = this;
  37398. if (this.meshMap) {
  37399. var result = new Array();
  37400. for (var meshId in this.meshMap) {
  37401. var mesh = this.meshMap[meshId];
  37402. if (mesh) {
  37403. result.push(mesh);
  37404. }
  37405. }
  37406. return result;
  37407. }
  37408. else {
  37409. var meshes = this._scene.meshes;
  37410. return meshes.filter(function (mesh) { return mesh.material === _this; });
  37411. }
  37412. };
  37413. /**
  37414. * Force shader compilation
  37415. * @param mesh defines the mesh associated with this material
  37416. * @param onCompiled defines a function to execute once the material is compiled
  37417. * @param options defines the options to configure the compilation
  37418. */
  37419. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  37420. var _this = this;
  37421. var localOptions = __assign({ clipPlane: false }, options);
  37422. var subMesh = new BABYLON.BaseSubMesh();
  37423. var scene = this.getScene();
  37424. var checkReady = function () {
  37425. if (!_this._scene || !_this._scene.getEngine()) {
  37426. return;
  37427. }
  37428. if (subMesh._materialDefines) {
  37429. subMesh._materialDefines._renderId = -1;
  37430. }
  37431. var clipPlaneState = scene.clipPlane;
  37432. if (localOptions.clipPlane) {
  37433. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  37434. }
  37435. if (_this._storeEffectOnSubMeshes) {
  37436. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  37437. if (onCompiled) {
  37438. onCompiled(_this);
  37439. }
  37440. }
  37441. else {
  37442. setTimeout(checkReady, 16);
  37443. }
  37444. }
  37445. else {
  37446. if (_this.isReady(mesh)) {
  37447. if (onCompiled) {
  37448. onCompiled(_this);
  37449. }
  37450. }
  37451. else {
  37452. setTimeout(checkReady, 16);
  37453. }
  37454. }
  37455. if (localOptions.clipPlane) {
  37456. scene.clipPlane = clipPlaneState;
  37457. }
  37458. };
  37459. checkReady();
  37460. };
  37461. /**
  37462. * Force shader compilation
  37463. * @param mesh defines the mesh that will use this material
  37464. * @param options defines additional options for compiling the shaders
  37465. * @returns a promise that resolves when the compilation completes
  37466. */
  37467. Material.prototype.forceCompilationAsync = function (mesh, options) {
  37468. var _this = this;
  37469. return new Promise(function (resolve) {
  37470. _this.forceCompilation(mesh, function () {
  37471. resolve();
  37472. }, options);
  37473. });
  37474. };
  37475. /**
  37476. * Marks a define in the material to indicate that it needs to be re-computed
  37477. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  37478. */
  37479. Material.prototype.markAsDirty = function (flag) {
  37480. if (this.getScene().blockMaterialDirtyMechanism) {
  37481. return;
  37482. }
  37483. Material._DirtyCallbackArray.length = 0;
  37484. if (flag & Material.TextureDirtyFlag) {
  37485. Material._DirtyCallbackArray.push(Material._TextureDirtyCallBack);
  37486. }
  37487. if (flag & Material.LightDirtyFlag) {
  37488. Material._DirtyCallbackArray.push(Material._LightsDirtyCallBack);
  37489. }
  37490. if (flag & Material.FresnelDirtyFlag) {
  37491. Material._DirtyCallbackArray.push(Material._FresnelDirtyCallBack);
  37492. }
  37493. if (flag & Material.AttributesDirtyFlag) {
  37494. Material._DirtyCallbackArray.push(Material._AttributeDirtyCallBack);
  37495. }
  37496. if (flag & Material.MiscDirtyFlag) {
  37497. Material._DirtyCallbackArray.push(Material._MiscDirtyCallBack);
  37498. }
  37499. if (Material._DirtyCallbackArray.length) {
  37500. this._markAllSubMeshesAsDirty(Material._RunDirtyCallBacks);
  37501. }
  37502. this.getScene().resetCachedMaterial();
  37503. };
  37504. /**
  37505. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  37506. * @param func defines a function which checks material defines against the submeshes
  37507. */
  37508. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  37509. if (this.getScene().blockMaterialDirtyMechanism) {
  37510. return;
  37511. }
  37512. var meshes = this.getScene().meshes;
  37513. for (var _i = 0, meshes_1 = meshes; _i < meshes_1.length; _i++) {
  37514. var mesh = meshes_1[_i];
  37515. if (!mesh.subMeshes) {
  37516. continue;
  37517. }
  37518. for (var _a = 0, _b = mesh.subMeshes; _a < _b.length; _a++) {
  37519. var subMesh = _b[_a];
  37520. if (subMesh.getMaterial() !== this) {
  37521. continue;
  37522. }
  37523. if (!subMesh._materialDefines) {
  37524. continue;
  37525. }
  37526. func(subMesh._materialDefines);
  37527. }
  37528. }
  37529. };
  37530. /**
  37531. * Indicates that image processing needs to be re-calculated for all submeshes
  37532. */
  37533. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  37534. this._markAllSubMeshesAsDirty(Material._ImageProcessingDirtyCallBack);
  37535. };
  37536. /**
  37537. * Indicates that textures need to be re-calculated for all submeshes
  37538. */
  37539. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  37540. this._markAllSubMeshesAsDirty(Material._TextureDirtyCallBack);
  37541. };
  37542. /**
  37543. * Indicates that fresnel needs to be re-calculated for all submeshes
  37544. */
  37545. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  37546. this._markAllSubMeshesAsDirty(Material._FresnelDirtyCallBack);
  37547. };
  37548. /**
  37549. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  37550. */
  37551. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  37552. this._markAllSubMeshesAsDirty(Material._FresnelAndMiscDirtyCallBack);
  37553. };
  37554. /**
  37555. * Indicates that lights need to be re-calculated for all submeshes
  37556. */
  37557. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  37558. this._markAllSubMeshesAsDirty(Material._LightsDirtyCallBack);
  37559. };
  37560. /**
  37561. * Indicates that attributes need to be re-calculated for all submeshes
  37562. */
  37563. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  37564. this._markAllSubMeshesAsDirty(Material._AttributeDirtyCallBack);
  37565. };
  37566. /**
  37567. * Indicates that misc needs to be re-calculated for all submeshes
  37568. */
  37569. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  37570. this._markAllSubMeshesAsDirty(Material._MiscDirtyCallBack);
  37571. };
  37572. /**
  37573. * Indicates that textures and misc need to be re-calculated for all submeshes
  37574. */
  37575. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  37576. this._markAllSubMeshesAsDirty(Material._TextureAndMiscDirtyCallBack);
  37577. };
  37578. /**
  37579. * Disposes the material
  37580. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  37581. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  37582. * @param notBoundToMesh specifies if the material that is being disposed is known to be not bound to any mesh
  37583. */
  37584. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures, notBoundToMesh) {
  37585. var scene = this.getScene();
  37586. // Animations
  37587. scene.stopAnimation(this);
  37588. scene.freeProcessedMaterials();
  37589. // Remove from scene
  37590. scene.removeMaterial(this);
  37591. if (notBoundToMesh !== true) {
  37592. // Remove from meshes
  37593. if (this.meshMap) {
  37594. for (var meshId in this.meshMap) {
  37595. var mesh = this.meshMap[meshId];
  37596. if (mesh) {
  37597. mesh.material = null; // will set the entry in the map to undefined
  37598. this.releaseVertexArrayObject(mesh, forceDisposeEffect);
  37599. }
  37600. }
  37601. }
  37602. else {
  37603. var meshes = scene.meshes;
  37604. for (var _i = 0, meshes_2 = meshes; _i < meshes_2.length; _i++) {
  37605. var mesh = meshes_2[_i];
  37606. if (mesh.material === this) {
  37607. mesh.material = null;
  37608. this.releaseVertexArrayObject(mesh, forceDisposeEffect);
  37609. }
  37610. }
  37611. }
  37612. }
  37613. this._uniformBuffer.dispose();
  37614. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  37615. if (forceDisposeEffect && this._effect) {
  37616. if (!this._storeEffectOnSubMeshes) {
  37617. scene.getEngine()._releaseEffect(this._effect);
  37618. }
  37619. this._effect = null;
  37620. }
  37621. // Callback
  37622. this.onDisposeObservable.notifyObservers(this);
  37623. this.onDisposeObservable.clear();
  37624. if (this._onBindObservable) {
  37625. this._onBindObservable.clear();
  37626. }
  37627. if (this._onUnBindObservable) {
  37628. this._onUnBindObservable.clear();
  37629. }
  37630. };
  37631. /** @hidden */
  37632. Material.prototype.releaseVertexArrayObject = function (mesh, forceDisposeEffect) {
  37633. if (mesh.geometry) {
  37634. var geometry = (mesh.geometry);
  37635. var scene = this.getScene();
  37636. if (this._storeEffectOnSubMeshes) {
  37637. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  37638. var subMesh = _a[_i];
  37639. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  37640. if (forceDisposeEffect && subMesh._materialEffect) {
  37641. scene.getEngine()._releaseEffect(subMesh._materialEffect);
  37642. }
  37643. }
  37644. }
  37645. else {
  37646. geometry._releaseVertexArrayObject(this._effect);
  37647. }
  37648. }
  37649. };
  37650. /**
  37651. * Serializes this material
  37652. * @returns the serialized material object
  37653. */
  37654. Material.prototype.serialize = function () {
  37655. return BABYLON.SerializationHelper.Serialize(this);
  37656. };
  37657. /**
  37658. * Creates a MultiMaterial from parsed MultiMaterial data.
  37659. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  37660. * @param scene defines the hosting scene
  37661. * @returns a new MultiMaterial
  37662. */
  37663. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  37664. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  37665. multiMaterial.id = parsedMultiMaterial.id;
  37666. if (BABYLON.Tags) {
  37667. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  37668. }
  37669. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  37670. var subMatId = parsedMultiMaterial.materials[matIndex];
  37671. if (subMatId) {
  37672. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  37673. }
  37674. else {
  37675. multiMaterial.subMaterials.push(null);
  37676. }
  37677. }
  37678. return multiMaterial;
  37679. };
  37680. /**
  37681. * Creates a material from parsed material data
  37682. * @param parsedMaterial defines parsed material data
  37683. * @param scene defines the hosting scene
  37684. * @param rootUrl defines the root URL to use to load textures
  37685. * @returns a new material
  37686. */
  37687. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  37688. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  37689. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  37690. }
  37691. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  37692. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  37693. if (!BABYLON.LegacyPBRMaterial) {
  37694. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  37695. return;
  37696. }
  37697. }
  37698. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  37699. return materialType.Parse(parsedMaterial, scene, rootUrl);
  37700. };
  37701. // Triangle views
  37702. Material._TriangleFillMode = 0;
  37703. Material._WireFrameFillMode = 1;
  37704. Material._PointFillMode = 2;
  37705. // Draw modes
  37706. Material._PointListDrawMode = 3;
  37707. Material._LineListDrawMode = 4;
  37708. Material._LineLoopDrawMode = 5;
  37709. Material._LineStripDrawMode = 6;
  37710. Material._TriangleStripDrawMode = 7;
  37711. Material._TriangleFanDrawMode = 8;
  37712. /**
  37713. * Stores the clock-wise side orientation
  37714. */
  37715. Material._ClockWiseSideOrientation = 0;
  37716. /**
  37717. * Stores the counter clock-wise side orientation
  37718. */
  37719. Material._CounterClockWiseSideOrientation = 1;
  37720. /**
  37721. * The dirty texture flag value
  37722. */
  37723. Material.TextureDirtyFlag = 1;
  37724. /**
  37725. * The dirty light flag value
  37726. */
  37727. Material.LightDirtyFlag = 2;
  37728. /**
  37729. * The dirty fresnel flag value
  37730. */
  37731. Material.FresnelDirtyFlag = 4;
  37732. /**
  37733. * The dirty attribute flag value
  37734. */
  37735. Material.AttributesDirtyFlag = 8;
  37736. /**
  37737. * The dirty misc flag value
  37738. */
  37739. Material.MiscDirtyFlag = 16;
  37740. /**
  37741. * The all dirty flag value
  37742. */
  37743. Material.AllDirtyFlag = 31;
  37744. Material._ImageProcessingDirtyCallBack = function (defines) { return defines.markAsImageProcessingDirty(); };
  37745. Material._TextureDirtyCallBack = function (defines) { return defines.markAsTexturesDirty(); };
  37746. Material._FresnelDirtyCallBack = function (defines) { return defines.markAsFresnelDirty(); };
  37747. Material._MiscDirtyCallBack = function (defines) { return defines.markAsMiscDirty(); };
  37748. Material._LightsDirtyCallBack = function (defines) { return defines.markAsLightDirty(); };
  37749. Material._AttributeDirtyCallBack = function (defines) { return defines.markAsAttributesDirty(); };
  37750. Material._FresnelAndMiscDirtyCallBack = function (defines) {
  37751. Material._FresnelDirtyCallBack(defines);
  37752. Material._MiscDirtyCallBack(defines);
  37753. };
  37754. Material._TextureAndMiscDirtyCallBack = function (defines) {
  37755. Material._TextureDirtyCallBack(defines);
  37756. Material._MiscDirtyCallBack(defines);
  37757. };
  37758. Material._DirtyCallbackArray = [];
  37759. Material._RunDirtyCallBacks = function (defines) {
  37760. for (var _i = 0, _a = Material._DirtyCallbackArray; _i < _a.length; _i++) {
  37761. var cb = _a[_i];
  37762. cb(defines);
  37763. }
  37764. };
  37765. __decorate([
  37766. BABYLON.serialize()
  37767. ], Material.prototype, "id", void 0);
  37768. __decorate([
  37769. BABYLON.serialize()
  37770. ], Material.prototype, "uniqueId", void 0);
  37771. __decorate([
  37772. BABYLON.serialize()
  37773. ], Material.prototype, "name", void 0);
  37774. __decorate([
  37775. BABYLON.serialize()
  37776. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  37777. __decorate([
  37778. BABYLON.serialize()
  37779. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  37780. __decorate([
  37781. BABYLON.serialize()
  37782. ], Material.prototype, "state", void 0);
  37783. __decorate([
  37784. BABYLON.serialize("alpha")
  37785. ], Material.prototype, "_alpha", void 0);
  37786. __decorate([
  37787. BABYLON.serialize("backFaceCulling")
  37788. ], Material.prototype, "_backFaceCulling", void 0);
  37789. __decorate([
  37790. BABYLON.serialize()
  37791. ], Material.prototype, "sideOrientation", void 0);
  37792. __decorate([
  37793. BABYLON.serialize("alphaMode")
  37794. ], Material.prototype, "_alphaMode", void 0);
  37795. __decorate([
  37796. BABYLON.serialize()
  37797. ], Material.prototype, "_needDepthPrePass", void 0);
  37798. __decorate([
  37799. BABYLON.serialize()
  37800. ], Material.prototype, "disableDepthWrite", void 0);
  37801. __decorate([
  37802. BABYLON.serialize()
  37803. ], Material.prototype, "forceDepthWrite", void 0);
  37804. __decorate([
  37805. BABYLON.serialize()
  37806. ], Material.prototype, "separateCullingPass", void 0);
  37807. __decorate([
  37808. BABYLON.serialize("fogEnabled")
  37809. ], Material.prototype, "_fogEnabled", void 0);
  37810. __decorate([
  37811. BABYLON.serialize()
  37812. ], Material.prototype, "pointSize", void 0);
  37813. __decorate([
  37814. BABYLON.serialize()
  37815. ], Material.prototype, "zOffset", void 0);
  37816. __decorate([
  37817. BABYLON.serialize()
  37818. ], Material.prototype, "wireframe", null);
  37819. __decorate([
  37820. BABYLON.serialize()
  37821. ], Material.prototype, "pointsCloud", null);
  37822. __decorate([
  37823. BABYLON.serialize()
  37824. ], Material.prototype, "fillMode", null);
  37825. return Material;
  37826. }());
  37827. BABYLON.Material = Material;
  37828. })(BABYLON || (BABYLON = {}));
  37829. //# sourceMappingURL=babylon.material.js.map
  37830. var BABYLON;
  37831. (function (BABYLON) {
  37832. /**
  37833. * Uniform buffer objects.
  37834. *
  37835. * Handles blocks of uniform on the GPU.
  37836. *
  37837. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  37838. *
  37839. * For more information, please refer to :
  37840. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  37841. */
  37842. var UniformBuffer = /** @class */ (function () {
  37843. /**
  37844. * Instantiates a new Uniform buffer objects.
  37845. *
  37846. * Handles blocks of uniform on the GPU.
  37847. *
  37848. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  37849. *
  37850. * For more information, please refer to :
  37851. * @see https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  37852. * @param engine Define the engine the buffer is associated with
  37853. * @param data Define the data contained in the buffer
  37854. * @param dynamic Define if the buffer is updatable
  37855. */
  37856. function UniformBuffer(engine, data, dynamic) {
  37857. this._engine = engine;
  37858. this._noUBO = !engine.supportsUniformBuffers;
  37859. this._dynamic = dynamic;
  37860. this._data = data || [];
  37861. this._uniformLocations = {};
  37862. this._uniformSizes = {};
  37863. this._uniformLocationPointer = 0;
  37864. this._needSync = false;
  37865. if (this._noUBO) {
  37866. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  37867. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  37868. this.updateFloat = this._updateFloatForEffect;
  37869. this.updateFloat2 = this._updateFloat2ForEffect;
  37870. this.updateFloat3 = this._updateFloat3ForEffect;
  37871. this.updateFloat4 = this._updateFloat4ForEffect;
  37872. this.updateMatrix = this._updateMatrixForEffect;
  37873. this.updateVector3 = this._updateVector3ForEffect;
  37874. this.updateVector4 = this._updateVector4ForEffect;
  37875. this.updateColor3 = this._updateColor3ForEffect;
  37876. this.updateColor4 = this._updateColor4ForEffect;
  37877. }
  37878. else {
  37879. this._engine._uniformBuffers.push(this);
  37880. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  37881. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  37882. this.updateFloat = this._updateFloatForUniform;
  37883. this.updateFloat2 = this._updateFloat2ForUniform;
  37884. this.updateFloat3 = this._updateFloat3ForUniform;
  37885. this.updateFloat4 = this._updateFloat4ForUniform;
  37886. this.updateMatrix = this._updateMatrixForUniform;
  37887. this.updateVector3 = this._updateVector3ForUniform;
  37888. this.updateVector4 = this._updateVector4ForUniform;
  37889. this.updateColor3 = this._updateColor3ForUniform;
  37890. this.updateColor4 = this._updateColor4ForUniform;
  37891. }
  37892. }
  37893. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  37894. /**
  37895. * Indicates if the buffer is using the WebGL2 UBO implementation,
  37896. * or just falling back on setUniformXXX calls.
  37897. */
  37898. get: function () {
  37899. return !this._noUBO;
  37900. },
  37901. enumerable: true,
  37902. configurable: true
  37903. });
  37904. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  37905. /**
  37906. * Indicates if the WebGL underlying uniform buffer is in sync
  37907. * with the javascript cache data.
  37908. */
  37909. get: function () {
  37910. return !this._needSync;
  37911. },
  37912. enumerable: true,
  37913. configurable: true
  37914. });
  37915. /**
  37916. * Indicates if the WebGL underlying uniform buffer is dynamic.
  37917. * Also, a dynamic UniformBuffer will disable cache verification and always
  37918. * update the underlying WebGL uniform buffer to the GPU.
  37919. * @returns if Dynamic, otherwise false
  37920. */
  37921. UniformBuffer.prototype.isDynamic = function () {
  37922. return this._dynamic !== undefined;
  37923. };
  37924. /**
  37925. * The data cache on JS side.
  37926. * @returns the underlying data as a float array
  37927. */
  37928. UniformBuffer.prototype.getData = function () {
  37929. return this._bufferData;
  37930. };
  37931. /**
  37932. * The underlying WebGL Uniform buffer.
  37933. * @returns the webgl buffer
  37934. */
  37935. UniformBuffer.prototype.getBuffer = function () {
  37936. return this._buffer;
  37937. };
  37938. /**
  37939. * std140 layout specifies how to align data within an UBO structure.
  37940. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  37941. * for specs.
  37942. */
  37943. UniformBuffer.prototype._fillAlignment = function (size) {
  37944. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  37945. // and 4x4 matrices
  37946. // TODO : change if other types are used
  37947. var alignment;
  37948. if (size <= 2) {
  37949. alignment = size;
  37950. }
  37951. else {
  37952. alignment = 4;
  37953. }
  37954. if ((this._uniformLocationPointer % alignment) !== 0) {
  37955. var oldPointer = this._uniformLocationPointer;
  37956. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  37957. var diff = this._uniformLocationPointer - oldPointer;
  37958. for (var i = 0; i < diff; i++) {
  37959. this._data.push(0);
  37960. }
  37961. }
  37962. };
  37963. /**
  37964. * Adds an uniform in the buffer.
  37965. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  37966. * for the layout to be correct !
  37967. * @param name Name of the uniform, as used in the uniform block in the shader.
  37968. * @param size Data size, or data directly.
  37969. */
  37970. UniformBuffer.prototype.addUniform = function (name, size) {
  37971. if (this._noUBO) {
  37972. return;
  37973. }
  37974. if (this._uniformLocations[name] !== undefined) {
  37975. // Already existing uniform
  37976. return;
  37977. }
  37978. // This function must be called in the order of the shader layout !
  37979. // size can be the size of the uniform, or data directly
  37980. var data;
  37981. if (size instanceof Array) {
  37982. data = size;
  37983. size = data.length;
  37984. }
  37985. else {
  37986. size = size;
  37987. data = [];
  37988. // Fill with zeros
  37989. for (var i = 0; i < size; i++) {
  37990. data.push(0);
  37991. }
  37992. }
  37993. this._fillAlignment(size);
  37994. this._uniformSizes[name] = size;
  37995. this._uniformLocations[name] = this._uniformLocationPointer;
  37996. this._uniformLocationPointer += size;
  37997. for (var i = 0; i < size; i++) {
  37998. this._data.push(data[i]);
  37999. }
  38000. this._needSync = true;
  38001. };
  38002. /**
  38003. * Adds a Matrix 4x4 to the uniform buffer.
  38004. * @param name Name of the uniform, as used in the uniform block in the shader.
  38005. * @param mat A 4x4 matrix.
  38006. */
  38007. UniformBuffer.prototype.addMatrix = function (name, mat) {
  38008. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  38009. };
  38010. /**
  38011. * Adds a vec2 to the uniform buffer.
  38012. * @param name Name of the uniform, as used in the uniform block in the shader.
  38013. * @param x Define the x component value of the vec2
  38014. * @param y Define the y component value of the vec2
  38015. */
  38016. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  38017. var temp = [x, y];
  38018. this.addUniform(name, temp);
  38019. };
  38020. /**
  38021. * Adds a vec3 to the uniform buffer.
  38022. * @param name Name of the uniform, as used in the uniform block in the shader.
  38023. * @param x Define the x component value of the vec3
  38024. * @param y Define the y component value of the vec3
  38025. * @param z Define the z component value of the vec3
  38026. */
  38027. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  38028. var temp = [x, y, z];
  38029. this.addUniform(name, temp);
  38030. };
  38031. /**
  38032. * Adds a vec3 to the uniform buffer.
  38033. * @param name Name of the uniform, as used in the uniform block in the shader.
  38034. * @param color Define the vec3 from a Color
  38035. */
  38036. UniformBuffer.prototype.addColor3 = function (name, color) {
  38037. var temp = new Array();
  38038. color.toArray(temp);
  38039. this.addUniform(name, temp);
  38040. };
  38041. /**
  38042. * Adds a vec4 to the uniform buffer.
  38043. * @param name Name of the uniform, as used in the uniform block in the shader.
  38044. * @param color Define the rgb components from a Color
  38045. * @param alpha Define the a component of the vec4
  38046. */
  38047. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  38048. var temp = new Array();
  38049. color.toArray(temp);
  38050. temp.push(alpha);
  38051. this.addUniform(name, temp);
  38052. };
  38053. /**
  38054. * Adds a vec3 to the uniform buffer.
  38055. * @param name Name of the uniform, as used in the uniform block in the shader.
  38056. * @param vector Define the vec3 components from a Vector
  38057. */
  38058. UniformBuffer.prototype.addVector3 = function (name, vector) {
  38059. var temp = new Array();
  38060. vector.toArray(temp);
  38061. this.addUniform(name, temp);
  38062. };
  38063. /**
  38064. * Adds a Matrix 3x3 to the uniform buffer.
  38065. * @param name Name of the uniform, as used in the uniform block in the shader.
  38066. */
  38067. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  38068. this.addUniform(name, 12);
  38069. };
  38070. /**
  38071. * Adds a Matrix 2x2 to the uniform buffer.
  38072. * @param name Name of the uniform, as used in the uniform block in the shader.
  38073. */
  38074. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  38075. this.addUniform(name, 8);
  38076. };
  38077. /**
  38078. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  38079. */
  38080. UniformBuffer.prototype.create = function () {
  38081. if (this._noUBO) {
  38082. return;
  38083. }
  38084. if (this._buffer) {
  38085. return; // nothing to do
  38086. }
  38087. // See spec, alignment must be filled as a vec4
  38088. this._fillAlignment(4);
  38089. this._bufferData = new Float32Array(this._data);
  38090. this._rebuild();
  38091. this._needSync = true;
  38092. };
  38093. /** @hidden */
  38094. UniformBuffer.prototype._rebuild = function () {
  38095. if (this._noUBO) {
  38096. return;
  38097. }
  38098. if (this._dynamic) {
  38099. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  38100. }
  38101. else {
  38102. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  38103. }
  38104. };
  38105. /**
  38106. * Updates the WebGL Uniform Buffer on the GPU.
  38107. * If the `dynamic` flag is set to true, no cache comparison is done.
  38108. * Otherwise, the buffer will be updated only if the cache differs.
  38109. */
  38110. UniformBuffer.prototype.update = function () {
  38111. if (!this._buffer) {
  38112. this.create();
  38113. return;
  38114. }
  38115. if (!this._dynamic && !this._needSync) {
  38116. return;
  38117. }
  38118. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  38119. this._needSync = false;
  38120. };
  38121. /**
  38122. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  38123. * @param uniformName Define the name of the uniform, as used in the uniform block in the shader.
  38124. * @param data Define the flattened data
  38125. * @param size Define the size of the data.
  38126. */
  38127. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  38128. var location = this._uniformLocations[uniformName];
  38129. if (location === undefined) {
  38130. if (this._buffer) {
  38131. // Cannot add an uniform if the buffer is already created
  38132. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  38133. return;
  38134. }
  38135. this.addUniform(uniformName, size);
  38136. location = this._uniformLocations[uniformName];
  38137. }
  38138. if (!this._buffer) {
  38139. this.create();
  38140. }
  38141. if (!this._dynamic) {
  38142. // Cache for static uniform buffers
  38143. var changed = false;
  38144. for (var i = 0; i < size; i++) {
  38145. if (this._bufferData[location + i] !== data[i]) {
  38146. changed = true;
  38147. this._bufferData[location + i] = data[i];
  38148. }
  38149. }
  38150. this._needSync = this._needSync || changed;
  38151. }
  38152. else {
  38153. // No cache for dynamic
  38154. for (var i = 0; i < size; i++) {
  38155. this._bufferData[location + i] = data[i];
  38156. }
  38157. }
  38158. };
  38159. // Update methods
  38160. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  38161. // To match std140, matrix must be realigned
  38162. for (var i = 0; i < 3; i++) {
  38163. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  38164. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  38165. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  38166. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  38167. }
  38168. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  38169. };
  38170. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  38171. this._currentEffect.setMatrix3x3(name, matrix);
  38172. };
  38173. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  38174. this._currentEffect.setMatrix2x2(name, matrix);
  38175. };
  38176. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  38177. // To match std140, matrix must be realigned
  38178. for (var i = 0; i < 2; i++) {
  38179. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  38180. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  38181. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  38182. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  38183. }
  38184. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  38185. };
  38186. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  38187. this._currentEffect.setFloat(name, x);
  38188. };
  38189. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  38190. UniformBuffer._tempBuffer[0] = x;
  38191. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  38192. };
  38193. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  38194. if (suffix === void 0) { suffix = ""; }
  38195. this._currentEffect.setFloat2(name + suffix, x, y);
  38196. };
  38197. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  38198. if (suffix === void 0) { suffix = ""; }
  38199. UniformBuffer._tempBuffer[0] = x;
  38200. UniformBuffer._tempBuffer[1] = y;
  38201. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  38202. };
  38203. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  38204. if (suffix === void 0) { suffix = ""; }
  38205. this._currentEffect.setFloat3(name + suffix, x, y, z);
  38206. };
  38207. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  38208. if (suffix === void 0) { suffix = ""; }
  38209. UniformBuffer._tempBuffer[0] = x;
  38210. UniformBuffer._tempBuffer[1] = y;
  38211. UniformBuffer._tempBuffer[2] = z;
  38212. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  38213. };
  38214. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  38215. if (suffix === void 0) { suffix = ""; }
  38216. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  38217. };
  38218. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  38219. if (suffix === void 0) { suffix = ""; }
  38220. UniformBuffer._tempBuffer[0] = x;
  38221. UniformBuffer._tempBuffer[1] = y;
  38222. UniformBuffer._tempBuffer[2] = z;
  38223. UniformBuffer._tempBuffer[3] = w;
  38224. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  38225. };
  38226. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  38227. this._currentEffect.setMatrix(name, mat);
  38228. };
  38229. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  38230. this.updateUniform(name, mat.toArray(), 16);
  38231. };
  38232. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  38233. this._currentEffect.setVector3(name, vector);
  38234. };
  38235. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  38236. vector.toArray(UniformBuffer._tempBuffer);
  38237. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  38238. };
  38239. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  38240. this._currentEffect.setVector4(name, vector);
  38241. };
  38242. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  38243. vector.toArray(UniformBuffer._tempBuffer);
  38244. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  38245. };
  38246. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  38247. if (suffix === void 0) { suffix = ""; }
  38248. this._currentEffect.setColor3(name + suffix, color);
  38249. };
  38250. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  38251. if (suffix === void 0) { suffix = ""; }
  38252. color.toArray(UniformBuffer._tempBuffer);
  38253. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  38254. };
  38255. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  38256. if (suffix === void 0) { suffix = ""; }
  38257. this._currentEffect.setColor4(name + suffix, color, alpha);
  38258. };
  38259. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  38260. if (suffix === void 0) { suffix = ""; }
  38261. color.toArray(UniformBuffer._tempBuffer);
  38262. UniformBuffer._tempBuffer[3] = alpha;
  38263. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  38264. };
  38265. /**
  38266. * Sets a sampler uniform on the effect.
  38267. * @param name Define the name of the sampler.
  38268. * @param texture Define the texture to set in the sampler
  38269. */
  38270. UniformBuffer.prototype.setTexture = function (name, texture) {
  38271. this._currentEffect.setTexture(name, texture);
  38272. };
  38273. /**
  38274. * Directly updates the value of the uniform in the cache AND on the GPU.
  38275. * @param uniformName Define the name of the uniform, as used in the uniform block in the shader.
  38276. * @param data Define the flattened data
  38277. */
  38278. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  38279. this.updateUniform(uniformName, data, data.length);
  38280. this.update();
  38281. };
  38282. /**
  38283. * Binds this uniform buffer to an effect.
  38284. * @param effect Define the effect to bind the buffer to
  38285. * @param name Name of the uniform block in the shader.
  38286. */
  38287. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  38288. this._currentEffect = effect;
  38289. if (this._noUBO || !this._buffer) {
  38290. return;
  38291. }
  38292. effect.bindUniformBuffer(this._buffer, name);
  38293. };
  38294. /**
  38295. * Disposes the uniform buffer.
  38296. */
  38297. UniformBuffer.prototype.dispose = function () {
  38298. if (this._noUBO) {
  38299. return;
  38300. }
  38301. var uniformBuffers = this._engine._uniformBuffers;
  38302. var index = uniformBuffers.indexOf(this);
  38303. if (index !== -1) {
  38304. uniformBuffers[index] = uniformBuffers[uniformBuffers.length - 1];
  38305. uniformBuffers.pop();
  38306. }
  38307. if (!this._buffer) {
  38308. return;
  38309. }
  38310. if (this._engine._releaseBuffer(this._buffer)) {
  38311. this._buffer = null;
  38312. }
  38313. };
  38314. // Pool for avoiding memory leaks
  38315. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  38316. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  38317. return UniformBuffer;
  38318. }());
  38319. BABYLON.UniformBuffer = UniformBuffer;
  38320. })(BABYLON || (BABYLON = {}));
  38321. //# sourceMappingURL=babylon.uniformBuffer.js.map
  38322. var BABYLON;
  38323. (function (BABYLON) {
  38324. /**
  38325. * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance
  38326. */
  38327. var VertexData = /** @class */ (function () {
  38328. function VertexData() {
  38329. }
  38330. /**
  38331. * Uses the passed data array to set the set the values for the specified kind of data
  38332. * @param data a linear array of floating numbers
  38333. * @param kind the type of data that is being set, eg positions, colors etc
  38334. */
  38335. VertexData.prototype.set = function (data, kind) {
  38336. switch (kind) {
  38337. case BABYLON.VertexBuffer.PositionKind:
  38338. this.positions = data;
  38339. break;
  38340. case BABYLON.VertexBuffer.NormalKind:
  38341. this.normals = data;
  38342. break;
  38343. case BABYLON.VertexBuffer.TangentKind:
  38344. this.tangents = data;
  38345. break;
  38346. case BABYLON.VertexBuffer.UVKind:
  38347. this.uvs = data;
  38348. break;
  38349. case BABYLON.VertexBuffer.UV2Kind:
  38350. this.uvs2 = data;
  38351. break;
  38352. case BABYLON.VertexBuffer.UV3Kind:
  38353. this.uvs3 = data;
  38354. break;
  38355. case BABYLON.VertexBuffer.UV4Kind:
  38356. this.uvs4 = data;
  38357. break;
  38358. case BABYLON.VertexBuffer.UV5Kind:
  38359. this.uvs5 = data;
  38360. break;
  38361. case BABYLON.VertexBuffer.UV6Kind:
  38362. this.uvs6 = data;
  38363. break;
  38364. case BABYLON.VertexBuffer.ColorKind:
  38365. this.colors = data;
  38366. break;
  38367. case BABYLON.VertexBuffer.MatricesIndicesKind:
  38368. this.matricesIndices = data;
  38369. break;
  38370. case BABYLON.VertexBuffer.MatricesWeightsKind:
  38371. this.matricesWeights = data;
  38372. break;
  38373. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  38374. this.matricesIndicesExtra = data;
  38375. break;
  38376. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  38377. this.matricesWeightsExtra = data;
  38378. break;
  38379. }
  38380. };
  38381. /**
  38382. * Associates the vertexData to the passed Mesh.
  38383. * Sets it as updatable or not (default `false`)
  38384. * @param mesh the mesh the vertexData is applied to
  38385. * @param updatable when used and having the value true allows new data to update the vertexData
  38386. * @returns the VertexData
  38387. */
  38388. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  38389. this._applyTo(mesh, updatable);
  38390. return this;
  38391. };
  38392. /**
  38393. * Associates the vertexData to the passed Geometry.
  38394. * Sets it as updatable or not (default `false`)
  38395. * @param geometry the geometry the vertexData is applied to
  38396. * @param updatable when used and having the value true allows new data to update the vertexData
  38397. * @returns VertexData
  38398. */
  38399. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  38400. this._applyTo(geometry, updatable);
  38401. return this;
  38402. };
  38403. /**
  38404. * Updates the associated mesh
  38405. * @param mesh the mesh to be updated
  38406. * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false
  38407. * @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
  38408. * @returns VertexData
  38409. */
  38410. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  38411. this._update(mesh);
  38412. return this;
  38413. };
  38414. /**
  38415. * Updates the associated geometry
  38416. * @param geometry the geometry to be updated
  38417. * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false
  38418. * @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
  38419. * @returns VertexData.
  38420. */
  38421. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  38422. this._update(geometry);
  38423. return this;
  38424. };
  38425. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  38426. if (updatable === void 0) { updatable = false; }
  38427. if (this.positions) {
  38428. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  38429. }
  38430. if (this.normals) {
  38431. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  38432. }
  38433. if (this.tangents) {
  38434. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  38435. }
  38436. if (this.uvs) {
  38437. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  38438. }
  38439. if (this.uvs2) {
  38440. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  38441. }
  38442. if (this.uvs3) {
  38443. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  38444. }
  38445. if (this.uvs4) {
  38446. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  38447. }
  38448. if (this.uvs5) {
  38449. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  38450. }
  38451. if (this.uvs6) {
  38452. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  38453. }
  38454. if (this.colors) {
  38455. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  38456. }
  38457. if (this.matricesIndices) {
  38458. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  38459. }
  38460. if (this.matricesWeights) {
  38461. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  38462. }
  38463. if (this.matricesIndicesExtra) {
  38464. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  38465. }
  38466. if (this.matricesWeightsExtra) {
  38467. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  38468. }
  38469. if (this.indices) {
  38470. meshOrGeometry.setIndices(this.indices, null, updatable);
  38471. }
  38472. else {
  38473. meshOrGeometry.setIndices([], null);
  38474. }
  38475. return this;
  38476. };
  38477. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  38478. if (this.positions) {
  38479. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  38480. }
  38481. if (this.normals) {
  38482. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  38483. }
  38484. if (this.tangents) {
  38485. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  38486. }
  38487. if (this.uvs) {
  38488. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  38489. }
  38490. if (this.uvs2) {
  38491. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  38492. }
  38493. if (this.uvs3) {
  38494. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  38495. }
  38496. if (this.uvs4) {
  38497. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  38498. }
  38499. if (this.uvs5) {
  38500. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  38501. }
  38502. if (this.uvs6) {
  38503. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  38504. }
  38505. if (this.colors) {
  38506. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  38507. }
  38508. if (this.matricesIndices) {
  38509. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  38510. }
  38511. if (this.matricesWeights) {
  38512. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  38513. }
  38514. if (this.matricesIndicesExtra) {
  38515. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  38516. }
  38517. if (this.matricesWeightsExtra) {
  38518. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  38519. }
  38520. if (this.indices) {
  38521. meshOrGeometry.setIndices(this.indices, null);
  38522. }
  38523. return this;
  38524. };
  38525. /**
  38526. * Transforms each position and each normal of the vertexData according to the passed Matrix
  38527. * @param matrix the transforming matrix
  38528. * @returns the VertexData
  38529. */
  38530. VertexData.prototype.transform = function (matrix) {
  38531. var flip = matrix.m[0] * matrix.m[5] * matrix.m[10] < 0;
  38532. var transformed = BABYLON.Vector3.Zero();
  38533. var index;
  38534. if (this.positions) {
  38535. var position = BABYLON.Vector3.Zero();
  38536. for (index = 0; index < this.positions.length; index += 3) {
  38537. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  38538. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  38539. this.positions[index] = transformed.x;
  38540. this.positions[index + 1] = transformed.y;
  38541. this.positions[index + 2] = transformed.z;
  38542. }
  38543. }
  38544. if (this.normals) {
  38545. var normal = BABYLON.Vector3.Zero();
  38546. for (index = 0; index < this.normals.length; index += 3) {
  38547. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  38548. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  38549. this.normals[index] = transformed.x;
  38550. this.normals[index + 1] = transformed.y;
  38551. this.normals[index + 2] = transformed.z;
  38552. }
  38553. }
  38554. if (this.tangents) {
  38555. var tangent = BABYLON.Vector4.Zero();
  38556. var tangentTransformed = BABYLON.Vector4.Zero();
  38557. for (index = 0; index < this.tangents.length; index += 4) {
  38558. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  38559. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  38560. this.tangents[index] = tangentTransformed.x;
  38561. this.tangents[index + 1] = tangentTransformed.y;
  38562. this.tangents[index + 2] = tangentTransformed.z;
  38563. this.tangents[index + 3] = tangentTransformed.w;
  38564. }
  38565. }
  38566. if (flip && this.indices) {
  38567. for (index = 0; index < this.indices.length; index += 3) {
  38568. var tmp = this.indices[index + 1];
  38569. this.indices[index + 1] = this.indices[index + 2];
  38570. this.indices[index + 2] = tmp;
  38571. }
  38572. }
  38573. return this;
  38574. };
  38575. /**
  38576. * Merges the passed VertexData into the current one
  38577. * @param other the VertexData to be merged into the current one
  38578. * @param use32BitsIndices defines a boolean indicating if indices must be store in a 32 bits array
  38579. * @returns the modified VertexData
  38580. */
  38581. VertexData.prototype.merge = function (other, use32BitsIndices) {
  38582. if (use32BitsIndices === void 0) { use32BitsIndices = false; }
  38583. this._validate();
  38584. other._validate();
  38585. if (!this.normals !== !other.normals ||
  38586. !this.tangents !== !other.tangents ||
  38587. !this.uvs !== !other.uvs ||
  38588. !this.uvs2 !== !other.uvs2 ||
  38589. !this.uvs3 !== !other.uvs3 ||
  38590. !this.uvs4 !== !other.uvs4 ||
  38591. !this.uvs5 !== !other.uvs5 ||
  38592. !this.uvs6 !== !other.uvs6 ||
  38593. !this.colors !== !other.colors ||
  38594. !this.matricesIndices !== !other.matricesIndices ||
  38595. !this.matricesWeights !== !other.matricesWeights ||
  38596. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  38597. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  38598. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  38599. }
  38600. if (other.indices) {
  38601. if (!this.indices) {
  38602. this.indices = [];
  38603. }
  38604. var offset = this.positions ? this.positions.length / 3 : 0;
  38605. var isSrcTypedArray = this.indices.BYTES_PER_ELEMENT !== undefined;
  38606. if (isSrcTypedArray) {
  38607. var len = this.indices.length + other.indices.length;
  38608. var temp = use32BitsIndices || this.indices instanceof Uint32Array ? new Uint32Array(len) : new Uint16Array(len);
  38609. temp.set(this.indices);
  38610. var decal = this.indices.length;
  38611. for (var index = 0; index < other.indices.length; index++) {
  38612. temp[decal + index] = other.indices[index] + offset;
  38613. }
  38614. this.indices = temp;
  38615. }
  38616. else {
  38617. for (var index = 0; index < other.indices.length; index++) {
  38618. this.indices.push(other.indices[index] + offset);
  38619. }
  38620. }
  38621. }
  38622. this.positions = this._mergeElement(this.positions, other.positions);
  38623. this.normals = this._mergeElement(this.normals, other.normals);
  38624. this.tangents = this._mergeElement(this.tangents, other.tangents);
  38625. this.uvs = this._mergeElement(this.uvs, other.uvs);
  38626. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  38627. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  38628. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  38629. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  38630. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  38631. this.colors = this._mergeElement(this.colors, other.colors);
  38632. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  38633. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  38634. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  38635. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  38636. return this;
  38637. };
  38638. VertexData.prototype._mergeElement = function (source, other) {
  38639. if (!source) {
  38640. return other;
  38641. }
  38642. if (!other) {
  38643. return source;
  38644. }
  38645. var len = other.length + source.length;
  38646. var isSrcTypedArray = source instanceof Float32Array;
  38647. var isOthTypedArray = other instanceof Float32Array;
  38648. // use non-loop method when the source is Float32Array
  38649. if (isSrcTypedArray) {
  38650. var ret32 = new Float32Array(len);
  38651. ret32.set(source);
  38652. ret32.set(other, source.length);
  38653. return ret32;
  38654. // source is number[], when other is also use concat
  38655. }
  38656. else if (!isOthTypedArray) {
  38657. return source.concat(other);
  38658. // source is a number[], but other is a Float32Array, loop required
  38659. }
  38660. else {
  38661. var ret = source.slice(0); // copy source to a separate array
  38662. for (var i = 0, len = other.length; i < len; i++) {
  38663. ret.push(other[i]);
  38664. }
  38665. return ret;
  38666. }
  38667. };
  38668. VertexData.prototype._validate = function () {
  38669. if (!this.positions) {
  38670. throw new Error("Positions are required");
  38671. }
  38672. var getElementCount = function (kind, values) {
  38673. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  38674. if ((values.length % stride) !== 0) {
  38675. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  38676. }
  38677. return values.length / stride;
  38678. };
  38679. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  38680. var validateElementCount = function (kind, values) {
  38681. var elementCount = getElementCount(kind, values);
  38682. if (elementCount !== positionsElementCount) {
  38683. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  38684. }
  38685. };
  38686. if (this.normals) {
  38687. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  38688. }
  38689. if (this.tangents) {
  38690. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  38691. }
  38692. if (this.uvs) {
  38693. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  38694. }
  38695. if (this.uvs2) {
  38696. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  38697. }
  38698. if (this.uvs3) {
  38699. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  38700. }
  38701. if (this.uvs4) {
  38702. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  38703. }
  38704. if (this.uvs5) {
  38705. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  38706. }
  38707. if (this.uvs6) {
  38708. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  38709. }
  38710. if (this.colors) {
  38711. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  38712. }
  38713. if (this.matricesIndices) {
  38714. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  38715. }
  38716. if (this.matricesWeights) {
  38717. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  38718. }
  38719. if (this.matricesIndicesExtra) {
  38720. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  38721. }
  38722. if (this.matricesWeightsExtra) {
  38723. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  38724. }
  38725. };
  38726. /**
  38727. * Serializes the VertexData
  38728. * @returns a serialized object
  38729. */
  38730. VertexData.prototype.serialize = function () {
  38731. var serializationObject = this.serialize();
  38732. if (this.positions) {
  38733. serializationObject.positions = this.positions;
  38734. }
  38735. if (this.normals) {
  38736. serializationObject.normals = this.normals;
  38737. }
  38738. if (this.tangents) {
  38739. serializationObject.tangents = this.tangents;
  38740. }
  38741. if (this.uvs) {
  38742. serializationObject.uvs = this.uvs;
  38743. }
  38744. if (this.uvs2) {
  38745. serializationObject.uvs2 = this.uvs2;
  38746. }
  38747. if (this.uvs3) {
  38748. serializationObject.uvs3 = this.uvs3;
  38749. }
  38750. if (this.uvs4) {
  38751. serializationObject.uvs4 = this.uvs4;
  38752. }
  38753. if (this.uvs5) {
  38754. serializationObject.uvs5 = this.uvs5;
  38755. }
  38756. if (this.uvs6) {
  38757. serializationObject.uvs6 = this.uvs6;
  38758. }
  38759. if (this.colors) {
  38760. serializationObject.colors = this.colors;
  38761. }
  38762. if (this.matricesIndices) {
  38763. serializationObject.matricesIndices = this.matricesIndices;
  38764. serializationObject.matricesIndices._isExpanded = true;
  38765. }
  38766. if (this.matricesWeights) {
  38767. serializationObject.matricesWeights = this.matricesWeights;
  38768. }
  38769. if (this.matricesIndicesExtra) {
  38770. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  38771. serializationObject.matricesIndicesExtra._isExpanded = true;
  38772. }
  38773. if (this.matricesWeightsExtra) {
  38774. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  38775. }
  38776. serializationObject.indices = this.indices;
  38777. return serializationObject;
  38778. };
  38779. // Statics
  38780. /**
  38781. * Extracts the vertexData from a mesh
  38782. * @param mesh the mesh from which to extract the VertexData
  38783. * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false
  38784. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  38785. * @returns the object VertexData associated to the passed mesh
  38786. */
  38787. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  38788. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  38789. };
  38790. /**
  38791. * Extracts the vertexData from the geometry
  38792. * @param geometry the geometry from which to extract the VertexData
  38793. * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false
  38794. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  38795. * @returns the object VertexData associated to the passed mesh
  38796. */
  38797. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  38798. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  38799. };
  38800. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  38801. var result = new VertexData();
  38802. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  38803. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  38804. }
  38805. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  38806. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  38807. }
  38808. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  38809. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  38810. }
  38811. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  38812. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  38813. }
  38814. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  38815. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  38816. }
  38817. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  38818. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  38819. }
  38820. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  38821. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  38822. }
  38823. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  38824. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  38825. }
  38826. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  38827. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  38828. }
  38829. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  38830. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  38831. }
  38832. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  38833. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  38834. }
  38835. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  38836. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  38837. }
  38838. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  38839. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  38840. }
  38841. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  38842. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  38843. }
  38844. result.indices = meshOrGeometry.getIndices(copyWhenShared, forceCopy);
  38845. return result;
  38846. };
  38847. /**
  38848. * Creates the VertexData for a Ribbon
  38849. * @param options an object used to set the following optional parameters for the ribbon, required but can be empty
  38850. * * pathArray array of paths, each of which an array of successive Vector3
  38851. * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false
  38852. * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false
  38853. * * 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
  38854. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38855. * * 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)
  38856. * * 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)
  38857. * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false
  38858. * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional
  38859. * * colors a linear array, of length 4 * number of vertices, of custom color values, optional
  38860. * @returns the VertexData of the ribbon
  38861. */
  38862. VertexData.CreateRibbon = function (options) {
  38863. var pathArray = options.pathArray;
  38864. var closeArray = options.closeArray || false;
  38865. var closePath = options.closePath || false;
  38866. var invertUV = options.invertUV || false;
  38867. var defaultOffset = Math.floor(pathArray[0].length / 2);
  38868. var offset = options.offset || defaultOffset;
  38869. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  38870. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38871. var customUV = options.uvs;
  38872. var customColors = options.colors;
  38873. var positions = [];
  38874. var indices = [];
  38875. var normals = [];
  38876. var uvs = [];
  38877. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  38878. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  38879. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  38880. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  38881. var minlg; // minimal length among all paths from pathArray
  38882. var lg = []; // array of path lengths : nb of vertex per path
  38883. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  38884. var p; // path iterator
  38885. var i; // point iterator
  38886. var j; // point iterator
  38887. // if single path in pathArray
  38888. if (pathArray.length < 2) {
  38889. var ar1 = [];
  38890. var ar2 = [];
  38891. for (i = 0; i < pathArray[0].length - offset; i++) {
  38892. ar1.push(pathArray[0][i]);
  38893. ar2.push(pathArray[0][i + offset]);
  38894. }
  38895. pathArray = [ar1, ar2];
  38896. }
  38897. // positions and horizontal distances (u)
  38898. var idc = 0;
  38899. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  38900. var path;
  38901. var l;
  38902. minlg = pathArray[0].length;
  38903. var vectlg;
  38904. var dist;
  38905. for (p = 0; p < pathArray.length; p++) {
  38906. uTotalDistance[p] = 0;
  38907. us[p] = [0];
  38908. path = pathArray[p];
  38909. l = path.length;
  38910. minlg = (minlg < l) ? minlg : l;
  38911. j = 0;
  38912. while (j < l) {
  38913. positions.push(path[j].x, path[j].y, path[j].z);
  38914. if (j > 0) {
  38915. vectlg = path[j].subtract(path[j - 1]).length();
  38916. dist = vectlg + uTotalDistance[p];
  38917. us[p].push(dist);
  38918. uTotalDistance[p] = dist;
  38919. }
  38920. j++;
  38921. }
  38922. if (closePath) { // an extra hidden vertex is added in the "positions" array
  38923. j--;
  38924. positions.push(path[0].x, path[0].y, path[0].z);
  38925. vectlg = path[j].subtract(path[0]).length();
  38926. dist = vectlg + uTotalDistance[p];
  38927. us[p].push(dist);
  38928. uTotalDistance[p] = dist;
  38929. }
  38930. lg[p] = l + closePathCorr;
  38931. idx[p] = idc;
  38932. idc += (l + closePathCorr);
  38933. }
  38934. // vertical distances (v)
  38935. var path1;
  38936. var path2;
  38937. var vertex1 = null;
  38938. var vertex2 = null;
  38939. for (i = 0; i < minlg + closePathCorr; i++) {
  38940. vTotalDistance[i] = 0;
  38941. vs[i] = [0];
  38942. for (p = 0; p < pathArray.length - 1; p++) {
  38943. path1 = pathArray[p];
  38944. path2 = pathArray[p + 1];
  38945. if (i === minlg) { // closePath
  38946. vertex1 = path1[0];
  38947. vertex2 = path2[0];
  38948. }
  38949. else {
  38950. vertex1 = path1[i];
  38951. vertex2 = path2[i];
  38952. }
  38953. vectlg = vertex2.subtract(vertex1).length();
  38954. dist = vectlg + vTotalDistance[i];
  38955. vs[i].push(dist);
  38956. vTotalDistance[i] = dist;
  38957. }
  38958. if (closeArray && vertex2 && vertex1) {
  38959. path1 = pathArray[p];
  38960. path2 = pathArray[0];
  38961. if (i === minlg) { // closePath
  38962. vertex2 = path2[0];
  38963. }
  38964. vectlg = vertex2.subtract(vertex1).length();
  38965. dist = vectlg + vTotalDistance[i];
  38966. vTotalDistance[i] = dist;
  38967. }
  38968. }
  38969. // uvs
  38970. var u;
  38971. var v;
  38972. if (customUV) {
  38973. for (p = 0; p < customUV.length; p++) {
  38974. uvs.push(customUV[p].x, customUV[p].y);
  38975. }
  38976. }
  38977. else {
  38978. for (p = 0; p < pathArray.length; p++) {
  38979. for (i = 0; i < minlg + closePathCorr; i++) {
  38980. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  38981. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  38982. if (invertUV) {
  38983. uvs.push(v, u);
  38984. }
  38985. else {
  38986. uvs.push(u, v);
  38987. }
  38988. }
  38989. }
  38990. }
  38991. // indices
  38992. p = 0; // path index
  38993. var pi = 0; // positions array index
  38994. var l1 = lg[p] - 1; // path1 length
  38995. var l2 = lg[p + 1] - 1; // path2 length
  38996. var min = (l1 < l2) ? l1 : l2; // current path stop index
  38997. var shft = idx[1] - idx[0]; // shift
  38998. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  38999. while (pi <= min && p < path1nb) { // stay under min and don't go over next to last path
  39000. // 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
  39001. indices.push(pi, pi + shft, pi + 1);
  39002. indices.push(pi + shft + 1, pi + 1, pi + shft);
  39003. pi += 1;
  39004. if (pi === min) { // if end of one of two consecutive paths reached, go to next existing path
  39005. p++;
  39006. if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true
  39007. shft = idx[0] - idx[p];
  39008. l1 = lg[p] - 1;
  39009. l2 = lg[0] - 1;
  39010. }
  39011. else {
  39012. shft = idx[p + 1] - idx[p];
  39013. l1 = lg[p] - 1;
  39014. l2 = lg[p + 1] - 1;
  39015. }
  39016. pi = idx[p];
  39017. min = (l1 < l2) ? l1 + pi : l2 + pi;
  39018. }
  39019. }
  39020. // normals
  39021. VertexData.ComputeNormals(positions, indices, normals);
  39022. if (closePath) { // update both the first and last vertex normals to their average value
  39023. var indexFirst = 0;
  39024. var indexLast = 0;
  39025. for (p = 0; p < pathArray.length; p++) {
  39026. indexFirst = idx[p] * 3;
  39027. if (p + 1 < pathArray.length) {
  39028. indexLast = (idx[p + 1] - 1) * 3;
  39029. }
  39030. else {
  39031. indexLast = normals.length - 3;
  39032. }
  39033. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  39034. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  39035. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  39036. normals[indexLast] = normals[indexFirst];
  39037. normals[indexLast + 1] = normals[indexFirst + 1];
  39038. normals[indexLast + 2] = normals[indexFirst + 2];
  39039. }
  39040. }
  39041. // sides
  39042. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  39043. // Colors
  39044. var colors = null;
  39045. if (customColors) {
  39046. colors = new Float32Array(customColors.length * 4);
  39047. for (var c = 0; c < customColors.length; c++) {
  39048. colors[c * 4] = customColors[c].r;
  39049. colors[c * 4 + 1] = customColors[c].g;
  39050. colors[c * 4 + 2] = customColors[c].b;
  39051. colors[c * 4 + 3] = customColors[c].a;
  39052. }
  39053. }
  39054. // Result
  39055. var vertexData = new VertexData();
  39056. var positions32 = new Float32Array(positions);
  39057. var normals32 = new Float32Array(normals);
  39058. var uvs32 = new Float32Array(uvs);
  39059. vertexData.indices = indices;
  39060. vertexData.positions = positions32;
  39061. vertexData.normals = normals32;
  39062. vertexData.uvs = uvs32;
  39063. if (colors) {
  39064. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  39065. }
  39066. if (closePath) {
  39067. vertexData._idx = idx;
  39068. }
  39069. return vertexData;
  39070. };
  39071. /**
  39072. * Creates the VertexData for a box
  39073. * @param options an object used to set the following optional parameters for the box, required but can be empty
  39074. * * size sets the width, height and depth of the box to the value of size, optional default 1
  39075. * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size
  39076. * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size
  39077. * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size
  39078. * * faceUV an array of 6 Vector4 elements used to set different images to each box side
  39079. * * faceColors an array of 6 Color3 elements used to set different colors to each box side
  39080. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39081. * * 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)
  39082. * * 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)
  39083. * @returns the VertexData of the box
  39084. */
  39085. VertexData.CreateBox = function (options) {
  39086. var normalsSource = [
  39087. new BABYLON.Vector3(0, 0, 1),
  39088. new BABYLON.Vector3(0, 0, -1),
  39089. new BABYLON.Vector3(1, 0, 0),
  39090. new BABYLON.Vector3(-1, 0, 0),
  39091. new BABYLON.Vector3(0, 1, 0),
  39092. new BABYLON.Vector3(0, -1, 0)
  39093. ];
  39094. var indices = [];
  39095. var positions = [];
  39096. var normals = [];
  39097. var uvs = [];
  39098. var width = options.width || options.size || 1;
  39099. var height = options.height || options.size || 1;
  39100. var depth = options.depth || options.size || 1;
  39101. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  39102. var faceUV = options.faceUV || new Array(6);
  39103. var faceColors = options.faceColors;
  39104. var colors = [];
  39105. // default face colors and UV if undefined
  39106. for (var f = 0; f < 6; f++) {
  39107. if (faceUV[f] === undefined) {
  39108. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  39109. }
  39110. if (faceColors && faceColors[f] === undefined) {
  39111. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  39112. }
  39113. }
  39114. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  39115. // Create each face in turn.
  39116. for (var index = 0; index < normalsSource.length; index++) {
  39117. var normal = normalsSource[index];
  39118. // Get two vectors perpendicular to the face normal and to each other.
  39119. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  39120. var side2 = BABYLON.Vector3.Cross(normal, side1);
  39121. // Six indices (two triangles) per face.
  39122. var verticesLength = positions.length / 3;
  39123. indices.push(verticesLength);
  39124. indices.push(verticesLength + 1);
  39125. indices.push(verticesLength + 2);
  39126. indices.push(verticesLength);
  39127. indices.push(verticesLength + 2);
  39128. indices.push(verticesLength + 3);
  39129. // Four vertices per face.
  39130. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  39131. positions.push(vertex.x, vertex.y, vertex.z);
  39132. normals.push(normal.x, normal.y, normal.z);
  39133. uvs.push(faceUV[index].z, faceUV[index].w);
  39134. if (faceColors) {
  39135. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  39136. }
  39137. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  39138. positions.push(vertex.x, vertex.y, vertex.z);
  39139. normals.push(normal.x, normal.y, normal.z);
  39140. uvs.push(faceUV[index].x, faceUV[index].w);
  39141. if (faceColors) {
  39142. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  39143. }
  39144. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  39145. positions.push(vertex.x, vertex.y, vertex.z);
  39146. normals.push(normal.x, normal.y, normal.z);
  39147. uvs.push(faceUV[index].x, faceUV[index].y);
  39148. if (faceColors) {
  39149. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  39150. }
  39151. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  39152. positions.push(vertex.x, vertex.y, vertex.z);
  39153. normals.push(normal.x, normal.y, normal.z);
  39154. uvs.push(faceUV[index].z, faceUV[index].y);
  39155. if (faceColors) {
  39156. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  39157. }
  39158. }
  39159. // sides
  39160. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  39161. // Result
  39162. var vertexData = new VertexData();
  39163. vertexData.indices = indices;
  39164. vertexData.positions = positions;
  39165. vertexData.normals = normals;
  39166. vertexData.uvs = uvs;
  39167. if (faceColors) {
  39168. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  39169. vertexData.colors = totalColors;
  39170. }
  39171. return vertexData;
  39172. };
  39173. /**
  39174. * Creates the VertexData for an ellipsoid, defaults to a sphere
  39175. * @param options an object used to set the following optional parameters for the box, required but can be empty
  39176. * * segments sets the number of horizontal strips optional, default 32
  39177. * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1
  39178. * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter
  39179. * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter
  39180. * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter
  39181. * * 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
  39182. * * 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
  39183. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39184. * * 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)
  39185. * * 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)
  39186. * @returns the VertexData of the ellipsoid
  39187. */
  39188. VertexData.CreateSphere = function (options) {
  39189. var segments = options.segments || 32;
  39190. var diameterX = options.diameterX || options.diameter || 1;
  39191. var diameterY = options.diameterY || options.diameter || 1;
  39192. var diameterZ = options.diameterZ || options.diameter || 1;
  39193. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  39194. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  39195. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  39196. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  39197. var totalZRotationSteps = 2 + segments;
  39198. var totalYRotationSteps = 2 * totalZRotationSteps;
  39199. var indices = [];
  39200. var positions = [];
  39201. var normals = [];
  39202. var uvs = [];
  39203. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  39204. var normalizedZ = zRotationStep / totalZRotationSteps;
  39205. var angleZ = normalizedZ * Math.PI * slice;
  39206. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  39207. var normalizedY = yRotationStep / totalYRotationSteps;
  39208. var angleY = normalizedY * Math.PI * 2 * arc;
  39209. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  39210. var rotationY = BABYLON.Matrix.RotationY(angleY);
  39211. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  39212. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  39213. var vertex = complete.multiply(radius);
  39214. var normal = complete.divide(radius).normalize();
  39215. positions.push(vertex.x, vertex.y, vertex.z);
  39216. normals.push(normal.x, normal.y, normal.z);
  39217. uvs.push(normalizedY, normalizedZ);
  39218. }
  39219. if (zRotationStep > 0) {
  39220. var verticesCount = positions.length / 3;
  39221. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  39222. indices.push((firstIndex));
  39223. indices.push((firstIndex + 1));
  39224. indices.push(firstIndex + totalYRotationSteps + 1);
  39225. indices.push((firstIndex + totalYRotationSteps + 1));
  39226. indices.push((firstIndex + 1));
  39227. indices.push((firstIndex + totalYRotationSteps + 2));
  39228. }
  39229. }
  39230. }
  39231. // Sides
  39232. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  39233. // Result
  39234. var vertexData = new VertexData();
  39235. vertexData.indices = indices;
  39236. vertexData.positions = positions;
  39237. vertexData.normals = normals;
  39238. vertexData.uvs = uvs;
  39239. return vertexData;
  39240. };
  39241. /**
  39242. * Creates the VertexData for a cylinder, cone or prism
  39243. * @param options an object used to set the following optional parameters for the box, required but can be empty
  39244. * * height sets the height (y direction) of the cylinder, optional, default 2
  39245. * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter
  39246. * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter
  39247. * * diameter sets the diameter of the top and bottom of the cone, optional default 1
  39248. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  39249. * * subdivisions` the number of rings along the cylinder height, optional, default 1
  39250. * * 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
  39251. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  39252. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  39253. * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false
  39254. * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake
  39255. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39256. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  39257. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  39258. * @returns the VertexData of the cylinder, cone or prism
  39259. */
  39260. VertexData.CreateCylinder = function (options) {
  39261. var height = options.height || 2;
  39262. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  39263. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  39264. var tessellation = options.tessellation || 24;
  39265. var subdivisions = options.subdivisions || 1;
  39266. var hasRings = options.hasRings ? true : false;
  39267. var enclose = options.enclose ? true : false;
  39268. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  39269. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  39270. var faceUV = options.faceUV || new Array(3);
  39271. var faceColors = options.faceColors;
  39272. // default face colors and UV if undefined
  39273. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  39274. var ringNb = (hasRings) ? subdivisions : 1;
  39275. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  39276. var f;
  39277. for (f = 0; f < surfaceNb; f++) {
  39278. if (faceColors && faceColors[f] === undefined) {
  39279. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  39280. }
  39281. }
  39282. for (f = 0; f < surfaceNb; f++) {
  39283. if (faceUV && faceUV[f] === undefined) {
  39284. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  39285. }
  39286. }
  39287. var indices = new Array();
  39288. var positions = new Array();
  39289. var normals = new Array();
  39290. var uvs = new Array();
  39291. var colors = new Array();
  39292. var angle_step = Math.PI * 2 * arc / tessellation;
  39293. var angle;
  39294. var h;
  39295. var radius;
  39296. var tan = (diameterBottom - diameterTop) / 2 / height;
  39297. var ringVertex = BABYLON.Vector3.Zero();
  39298. var ringNormal = BABYLON.Vector3.Zero();
  39299. var ringFirstVertex = BABYLON.Vector3.Zero();
  39300. var ringFirstNormal = BABYLON.Vector3.Zero();
  39301. var quadNormal = BABYLON.Vector3.Zero();
  39302. var Y = BABYLON.Axis.Y;
  39303. // positions, normals, uvs
  39304. var i;
  39305. var j;
  39306. var r;
  39307. var ringIdx = 1;
  39308. var s = 1; // surface index
  39309. var cs = 0;
  39310. var v = 0;
  39311. for (i = 0; i <= subdivisions; i++) {
  39312. h = i / subdivisions;
  39313. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  39314. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  39315. for (r = 0; r < ringIdx; r++) {
  39316. if (hasRings) {
  39317. s += r;
  39318. }
  39319. if (enclose) {
  39320. s += 2 * r;
  39321. }
  39322. for (j = 0; j <= tessellation; j++) {
  39323. angle = j * angle_step;
  39324. // position
  39325. ringVertex.x = Math.cos(-angle) * radius;
  39326. ringVertex.y = -height / 2 + h * height;
  39327. ringVertex.z = Math.sin(-angle) * radius;
  39328. // normal
  39329. if (diameterTop === 0 && i === subdivisions) {
  39330. // if no top cap, reuse former normals
  39331. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  39332. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  39333. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  39334. }
  39335. else {
  39336. ringNormal.x = ringVertex.x;
  39337. ringNormal.z = ringVertex.z;
  39338. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  39339. ringNormal.normalize();
  39340. }
  39341. // keep first ring vertex values for enclose
  39342. if (j === 0) {
  39343. ringFirstVertex.copyFrom(ringVertex);
  39344. ringFirstNormal.copyFrom(ringNormal);
  39345. }
  39346. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  39347. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  39348. if (hasRings) {
  39349. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  39350. }
  39351. else {
  39352. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  39353. }
  39354. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  39355. if (faceColors) {
  39356. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  39357. }
  39358. }
  39359. // if enclose, add four vertices and their dedicated normals
  39360. if (arc !== 1 && enclose) {
  39361. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  39362. positions.push(0, ringVertex.y, 0);
  39363. positions.push(0, ringVertex.y, 0);
  39364. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  39365. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  39366. quadNormal.normalize();
  39367. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  39368. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  39369. quadNormal.normalize();
  39370. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  39371. if (hasRings) {
  39372. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  39373. }
  39374. else {
  39375. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  39376. }
  39377. uvs.push(faceUV[s + 1].x, v);
  39378. uvs.push(faceUV[s + 1].z, v);
  39379. if (hasRings) {
  39380. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  39381. }
  39382. else {
  39383. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  39384. }
  39385. uvs.push(faceUV[s + 2].x, v);
  39386. uvs.push(faceUV[s + 2].z, v);
  39387. if (faceColors) {
  39388. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  39389. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  39390. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  39391. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  39392. }
  39393. }
  39394. if (cs !== s) {
  39395. cs = s;
  39396. }
  39397. }
  39398. }
  39399. // indices
  39400. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  39401. var s;
  39402. i = 0;
  39403. for (s = 0; s < subdivisions; s++) {
  39404. var i0 = 0;
  39405. var i1 = 0;
  39406. var i2 = 0;
  39407. var i3 = 0;
  39408. for (j = 0; j < tessellation; j++) {
  39409. i0 = i * (e + 1) + j;
  39410. i1 = (i + 1) * (e + 1) + j;
  39411. i2 = i * (e + 1) + (j + 1);
  39412. i3 = (i + 1) * (e + 1) + (j + 1);
  39413. indices.push(i0, i1, i2);
  39414. indices.push(i3, i2, i1);
  39415. }
  39416. if (arc !== 1 && enclose) { // if enclose, add two quads
  39417. indices.push(i0 + 2, i1 + 2, i2 + 2);
  39418. indices.push(i3 + 2, i2 + 2, i1 + 2);
  39419. indices.push(i0 + 4, i1 + 4, i2 + 4);
  39420. indices.push(i3 + 4, i2 + 4, i1 + 4);
  39421. }
  39422. i = (hasRings) ? (i + 2) : (i + 1);
  39423. }
  39424. // Caps
  39425. var createCylinderCap = function (isTop) {
  39426. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  39427. if (radius === 0) {
  39428. return;
  39429. }
  39430. // Cap positions, normals & uvs
  39431. var angle;
  39432. var circleVector;
  39433. var i;
  39434. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  39435. var c = null;
  39436. if (faceColors) {
  39437. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  39438. }
  39439. // cap center
  39440. var vbase = positions.length / 3;
  39441. var offset = isTop ? height / 2 : -height / 2;
  39442. var center = new BABYLON.Vector3(0, offset, 0);
  39443. positions.push(center.x, center.y, center.z);
  39444. normals.push(0, isTop ? 1 : -1, 0);
  39445. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  39446. if (c) {
  39447. colors.push(c.r, c.g, c.b, c.a);
  39448. }
  39449. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  39450. for (i = 0; i <= tessellation; i++) {
  39451. angle = Math.PI * 2 * i * arc / tessellation;
  39452. var cos = Math.cos(-angle);
  39453. var sin = Math.sin(-angle);
  39454. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  39455. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  39456. positions.push(circleVector.x, circleVector.y, circleVector.z);
  39457. normals.push(0, isTop ? 1 : -1, 0);
  39458. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  39459. if (c) {
  39460. colors.push(c.r, c.g, c.b, c.a);
  39461. }
  39462. }
  39463. // Cap indices
  39464. for (i = 0; i < tessellation; i++) {
  39465. if (!isTop) {
  39466. indices.push(vbase);
  39467. indices.push(vbase + (i + 1));
  39468. indices.push(vbase + (i + 2));
  39469. }
  39470. else {
  39471. indices.push(vbase);
  39472. indices.push(vbase + (i + 2));
  39473. indices.push(vbase + (i + 1));
  39474. }
  39475. }
  39476. };
  39477. // add caps to geometry
  39478. createCylinderCap(false);
  39479. createCylinderCap(true);
  39480. // Sides
  39481. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  39482. var vertexData = new VertexData();
  39483. vertexData.indices = indices;
  39484. vertexData.positions = positions;
  39485. vertexData.normals = normals;
  39486. vertexData.uvs = uvs;
  39487. if (faceColors) {
  39488. vertexData.colors = colors;
  39489. }
  39490. return vertexData;
  39491. };
  39492. /**
  39493. * Creates the VertexData for a torus
  39494. * @param options an object used to set the following optional parameters for the box, required but can be empty
  39495. * * diameter the diameter of the torus, optional default 1
  39496. * * thickness the diameter of the tube forming the torus, optional default 0.5
  39497. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  39498. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39499. * * 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)
  39500. * * 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)
  39501. * @returns the VertexData of the torus
  39502. */
  39503. VertexData.CreateTorus = function (options) {
  39504. var indices = [];
  39505. var positions = [];
  39506. var normals = [];
  39507. var uvs = [];
  39508. var diameter = options.diameter || 1;
  39509. var thickness = options.thickness || 0.5;
  39510. var tessellation = options.tessellation || 16;
  39511. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  39512. var stride = tessellation + 1;
  39513. for (var i = 0; i <= tessellation; i++) {
  39514. var u = i / tessellation;
  39515. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  39516. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  39517. for (var j = 0; j <= tessellation; j++) {
  39518. var v = 1 - j / tessellation;
  39519. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  39520. var dx = Math.cos(innerAngle);
  39521. var dy = Math.sin(innerAngle);
  39522. // Create a vertex.
  39523. var normal = new BABYLON.Vector3(dx, dy, 0);
  39524. var position = normal.scale(thickness / 2);
  39525. var textureCoordinate = new BABYLON.Vector2(u, v);
  39526. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  39527. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  39528. positions.push(position.x, position.y, position.z);
  39529. normals.push(normal.x, normal.y, normal.z);
  39530. uvs.push(textureCoordinate.x, textureCoordinate.y);
  39531. // And create indices for two triangles.
  39532. var nextI = (i + 1) % stride;
  39533. var nextJ = (j + 1) % stride;
  39534. indices.push(i * stride + j);
  39535. indices.push(i * stride + nextJ);
  39536. indices.push(nextI * stride + j);
  39537. indices.push(i * stride + nextJ);
  39538. indices.push(nextI * stride + nextJ);
  39539. indices.push(nextI * stride + j);
  39540. }
  39541. }
  39542. // Sides
  39543. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  39544. // Result
  39545. var vertexData = new VertexData();
  39546. vertexData.indices = indices;
  39547. vertexData.positions = positions;
  39548. vertexData.normals = normals;
  39549. vertexData.uvs = uvs;
  39550. return vertexData;
  39551. };
  39552. /**
  39553. * Creates the VertexData of the LineSystem
  39554. * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty
  39555. * - lines an array of lines, each line being an array of successive Vector3
  39556. * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point
  39557. * @returns the VertexData of the LineSystem
  39558. */
  39559. VertexData.CreateLineSystem = function (options) {
  39560. var indices = [];
  39561. var positions = [];
  39562. var lines = options.lines;
  39563. var colors = options.colors;
  39564. var vertexColors = [];
  39565. var idx = 0;
  39566. for (var l = 0; l < lines.length; l++) {
  39567. var points = lines[l];
  39568. for (var index = 0; index < points.length; index++) {
  39569. positions.push(points[index].x, points[index].y, points[index].z);
  39570. if (colors) {
  39571. var color = colors[l];
  39572. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  39573. }
  39574. if (index > 0) {
  39575. indices.push(idx - 1);
  39576. indices.push(idx);
  39577. }
  39578. idx++;
  39579. }
  39580. }
  39581. var vertexData = new VertexData();
  39582. vertexData.indices = indices;
  39583. vertexData.positions = positions;
  39584. if (colors) {
  39585. vertexData.colors = vertexColors;
  39586. }
  39587. return vertexData;
  39588. };
  39589. /**
  39590. * Create the VertexData for a DashedLines
  39591. * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty
  39592. * - points an array successive Vector3
  39593. * - dashSize the size of the dashes relative to the dash number, optional, default 3
  39594. * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1
  39595. * - dashNb the intended total number of dashes, optional, default 200
  39596. * @returns the VertexData for the DashedLines
  39597. */
  39598. VertexData.CreateDashedLines = function (options) {
  39599. var dashSize = options.dashSize || 3;
  39600. var gapSize = options.gapSize || 1;
  39601. var dashNb = options.dashNb || 200;
  39602. var points = options.points;
  39603. var positions = new Array();
  39604. var indices = new Array();
  39605. var curvect = BABYLON.Vector3.Zero();
  39606. var lg = 0;
  39607. var nb = 0;
  39608. var shft = 0;
  39609. var dashshft = 0;
  39610. var curshft = 0;
  39611. var idx = 0;
  39612. var i = 0;
  39613. for (i = 0; i < points.length - 1; i++) {
  39614. points[i + 1].subtractToRef(points[i], curvect);
  39615. lg += curvect.length();
  39616. }
  39617. shft = lg / dashNb;
  39618. dashshft = dashSize * shft / (dashSize + gapSize);
  39619. for (i = 0; i < points.length - 1; i++) {
  39620. points[i + 1].subtractToRef(points[i], curvect);
  39621. nb = Math.floor(curvect.length() / shft);
  39622. curvect.normalize();
  39623. for (var j = 0; j < nb; j++) {
  39624. curshft = shft * j;
  39625. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  39626. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  39627. indices.push(idx, idx + 1);
  39628. idx += 2;
  39629. }
  39630. }
  39631. // Result
  39632. var vertexData = new VertexData();
  39633. vertexData.positions = positions;
  39634. vertexData.indices = indices;
  39635. return vertexData;
  39636. };
  39637. /**
  39638. * Creates the VertexData for a Ground
  39639. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  39640. * - width the width (x direction) of the ground, optional, default 1
  39641. * - height the height (z direction) of the ground, optional, default 1
  39642. * - subdivisions the number of subdivisions per side, optional, default 1
  39643. * @returns the VertexData of the Ground
  39644. */
  39645. VertexData.CreateGround = function (options) {
  39646. var indices = [];
  39647. var positions = [];
  39648. var normals = [];
  39649. var uvs = [];
  39650. var row, col;
  39651. var width = options.width || 1;
  39652. var height = options.height || 1;
  39653. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  39654. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  39655. for (row = 0; row <= subdivisionsY; row++) {
  39656. for (col = 0; col <= subdivisionsX; col++) {
  39657. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  39658. var normal = new BABYLON.Vector3(0, 1.0, 0);
  39659. positions.push(position.x, position.y, position.z);
  39660. normals.push(normal.x, normal.y, normal.z);
  39661. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  39662. }
  39663. }
  39664. for (row = 0; row < subdivisionsY; row++) {
  39665. for (col = 0; col < subdivisionsX; col++) {
  39666. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  39667. indices.push(col + 1 + row * (subdivisionsX + 1));
  39668. indices.push(col + row * (subdivisionsX + 1));
  39669. indices.push(col + (row + 1) * (subdivisionsX + 1));
  39670. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  39671. indices.push(col + row * (subdivisionsX + 1));
  39672. }
  39673. }
  39674. // Result
  39675. var vertexData = new VertexData();
  39676. vertexData.indices = indices;
  39677. vertexData.positions = positions;
  39678. vertexData.normals = normals;
  39679. vertexData.uvs = uvs;
  39680. return vertexData;
  39681. };
  39682. /**
  39683. * Creates the VertexData for a TiledGround by subdividing the ground into tiles
  39684. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  39685. * * xmin the ground minimum X coordinate, optional, default -1
  39686. * * zmin the ground minimum Z coordinate, optional, default -1
  39687. * * xmax the ground maximum X coordinate, optional, default 1
  39688. * * zmax the ground maximum Z coordinate, optional, default 1
  39689. * * 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}
  39690. * * 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}
  39691. * @returns the VertexData of the TiledGround
  39692. */
  39693. VertexData.CreateTiledGround = function (options) {
  39694. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  39695. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  39696. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  39697. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  39698. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  39699. var precision = options.precision || { w: 1, h: 1 };
  39700. var indices = new Array();
  39701. var positions = new Array();
  39702. var normals = new Array();
  39703. var uvs = new Array();
  39704. var row, col, tileRow, tileCol;
  39705. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  39706. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  39707. precision.w = (precision.w < 1) ? 1 : precision.w;
  39708. precision.h = (precision.h < 1) ? 1 : precision.h;
  39709. var tileSize = {
  39710. 'w': (xmax - xmin) / subdivisions.w,
  39711. 'h': (zmax - zmin) / subdivisions.h
  39712. };
  39713. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  39714. // Indices
  39715. var base = positions.length / 3;
  39716. var rowLength = precision.w + 1;
  39717. for (row = 0; row < precision.h; row++) {
  39718. for (col = 0; col < precision.w; col++) {
  39719. var square = [
  39720. base + col + row * rowLength,
  39721. base + (col + 1) + row * rowLength,
  39722. base + (col + 1) + (row + 1) * rowLength,
  39723. base + col + (row + 1) * rowLength
  39724. ];
  39725. indices.push(square[1]);
  39726. indices.push(square[2]);
  39727. indices.push(square[3]);
  39728. indices.push(square[0]);
  39729. indices.push(square[1]);
  39730. indices.push(square[3]);
  39731. }
  39732. }
  39733. // Position, normals and uvs
  39734. var position = BABYLON.Vector3.Zero();
  39735. var normal = new BABYLON.Vector3(0, 1.0, 0);
  39736. for (row = 0; row <= precision.h; row++) {
  39737. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  39738. for (col = 0; col <= precision.w; col++) {
  39739. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  39740. position.y = 0;
  39741. positions.push(position.x, position.y, position.z);
  39742. normals.push(normal.x, normal.y, normal.z);
  39743. uvs.push(col / precision.w, row / precision.h);
  39744. }
  39745. }
  39746. }
  39747. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  39748. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  39749. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  39750. }
  39751. }
  39752. // Result
  39753. var vertexData = new VertexData();
  39754. vertexData.indices = indices;
  39755. vertexData.positions = positions;
  39756. vertexData.normals = normals;
  39757. vertexData.uvs = uvs;
  39758. return vertexData;
  39759. };
  39760. /**
  39761. * Creates the VertexData of the Ground designed from a heightmap
  39762. * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap
  39763. * * width the width (x direction) of the ground
  39764. * * height the height (z direction) of the ground
  39765. * * subdivisions the number of subdivisions per side
  39766. * * minHeight the minimum altitude on the ground, optional, default 0
  39767. * * maxHeight the maximum altitude on the ground, optional default 1
  39768. * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)
  39769. * * buffer the array holding the image color data
  39770. * * bufferWidth the width of image
  39771. * * bufferHeight the height of image
  39772. * * alphaFilter Remove any data where the alpha channel is below this value, defaults 0 (all data visible)
  39773. * @returns the VertexData of the Ground designed from a heightmap
  39774. */
  39775. VertexData.CreateGroundFromHeightMap = function (options) {
  39776. var indices = [];
  39777. var positions = [];
  39778. var normals = [];
  39779. var uvs = [];
  39780. var row, col;
  39781. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  39782. var alphaFilter = options.alphaFilter || 0.0;
  39783. // Vertices
  39784. for (row = 0; row <= options.subdivisions; row++) {
  39785. for (col = 0; col <= options.subdivisions; col++) {
  39786. 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));
  39787. // Compute height
  39788. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  39789. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  39790. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  39791. var r = options.buffer[pos] / 255.0;
  39792. var g = options.buffer[pos + 1] / 255.0;
  39793. var b = options.buffer[pos + 2] / 255.0;
  39794. var a = options.buffer[pos + 3] / 255.0;
  39795. var gradient = r * filter.r + g * filter.g + b * filter.b;
  39796. // If our alpha channel is not within our filter then we will assign a 'special' height
  39797. // Then when building the indices, we will ignore any vertex that is using the special height
  39798. if (a >= alphaFilter) {
  39799. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  39800. }
  39801. else {
  39802. position.y = options.minHeight - BABYLON.Epsilon; // We can't have a height below minHeight, normally.
  39803. }
  39804. // Add vertex
  39805. positions.push(position.x, position.y, position.z);
  39806. normals.push(0, 0, 0);
  39807. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  39808. }
  39809. }
  39810. // Indices
  39811. for (row = 0; row < options.subdivisions; row++) {
  39812. for (col = 0; col < options.subdivisions; col++) {
  39813. // Calculate Indices
  39814. var idx1 = (col + 1 + (row + 1) * (options.subdivisions + 1));
  39815. var idx2 = (col + 1 + row * (options.subdivisions + 1));
  39816. var idx3 = (col + row * (options.subdivisions + 1));
  39817. var idx4 = (col + (row + 1) * (options.subdivisions + 1));
  39818. // Check that all indices are visible (based on our special height)
  39819. // Only display the vertex if all Indices are visible
  39820. // Positions are stored x,y,z for each vertex, hence the * 3 and + 1 for height
  39821. var isVisibleIdx1 = positions[idx1 * 3 + 1] >= options.minHeight;
  39822. var isVisibleIdx2 = positions[idx2 * 3 + 1] >= options.minHeight;
  39823. var isVisibleIdx3 = positions[idx3 * 3 + 1] >= options.minHeight;
  39824. if (isVisibleIdx1 && isVisibleIdx2 && isVisibleIdx3) {
  39825. indices.push(idx1);
  39826. indices.push(idx2);
  39827. indices.push(idx3);
  39828. }
  39829. var isVisibleIdx4 = positions[idx4 * 3 + 1] >= options.minHeight;
  39830. if (isVisibleIdx4 && isVisibleIdx1 && isVisibleIdx3) {
  39831. indices.push(idx4);
  39832. indices.push(idx1);
  39833. indices.push(idx3);
  39834. }
  39835. }
  39836. }
  39837. // Normals
  39838. VertexData.ComputeNormals(positions, indices, normals);
  39839. // Result
  39840. var vertexData = new VertexData();
  39841. vertexData.indices = indices;
  39842. vertexData.positions = positions;
  39843. vertexData.normals = normals;
  39844. vertexData.uvs = uvs;
  39845. return vertexData;
  39846. };
  39847. /**
  39848. * Creates the VertexData for a Plane
  39849. * @param options an object used to set the following optional parameters for the plane, required but can be empty
  39850. * * size sets the width and height of the plane to the value of size, optional default 1
  39851. * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size
  39852. * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size
  39853. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39854. * * 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)
  39855. * * 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)
  39856. * @returns the VertexData of the box
  39857. */
  39858. VertexData.CreatePlane = function (options) {
  39859. var indices = [];
  39860. var positions = [];
  39861. var normals = [];
  39862. var uvs = [];
  39863. var width = options.width || options.size || 1;
  39864. var height = options.height || options.size || 1;
  39865. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  39866. // Vertices
  39867. var halfWidth = width / 2.0;
  39868. var halfHeight = height / 2.0;
  39869. positions.push(-halfWidth, -halfHeight, 0);
  39870. normals.push(0, 0, -1.0);
  39871. uvs.push(0.0, 0.0);
  39872. positions.push(halfWidth, -halfHeight, 0);
  39873. normals.push(0, 0, -1.0);
  39874. uvs.push(1.0, 0.0);
  39875. positions.push(halfWidth, halfHeight, 0);
  39876. normals.push(0, 0, -1.0);
  39877. uvs.push(1.0, 1.0);
  39878. positions.push(-halfWidth, halfHeight, 0);
  39879. normals.push(0, 0, -1.0);
  39880. uvs.push(0.0, 1.0);
  39881. // Indices
  39882. indices.push(0);
  39883. indices.push(1);
  39884. indices.push(2);
  39885. indices.push(0);
  39886. indices.push(2);
  39887. indices.push(3);
  39888. // Sides
  39889. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  39890. // Result
  39891. var vertexData = new VertexData();
  39892. vertexData.indices = indices;
  39893. vertexData.positions = positions;
  39894. vertexData.normals = normals;
  39895. vertexData.uvs = uvs;
  39896. return vertexData;
  39897. };
  39898. /**
  39899. * Creates the VertexData of the Disc or regular Polygon
  39900. * @param options an object used to set the following optional parameters for the disc, required but can be empty
  39901. * * radius the radius of the disc, optional default 0.5
  39902. * * tessellation the number of polygon sides, optional, default 64
  39903. * * 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
  39904. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39905. * * 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)
  39906. * * 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)
  39907. * @returns the VertexData of the box
  39908. */
  39909. VertexData.CreateDisc = function (options) {
  39910. var positions = new Array();
  39911. var indices = new Array();
  39912. var normals = new Array();
  39913. var uvs = new Array();
  39914. var radius = options.radius || 0.5;
  39915. var tessellation = options.tessellation || 64;
  39916. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  39917. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  39918. // positions and uvs
  39919. positions.push(0, 0, 0); // disc center first
  39920. uvs.push(0.5, 0.5);
  39921. var theta = Math.PI * 2 * arc;
  39922. var step = theta / tessellation;
  39923. for (var a = 0; a < theta; a += step) {
  39924. var x = Math.cos(a);
  39925. var y = Math.sin(a);
  39926. var u = (x + 1) / 2;
  39927. var v = (1 - y) / 2;
  39928. positions.push(radius * x, radius * y, 0);
  39929. uvs.push(u, v);
  39930. }
  39931. if (arc === 1) {
  39932. positions.push(positions[3], positions[4], positions[5]); // close the circle
  39933. uvs.push(uvs[2], uvs[3]);
  39934. }
  39935. //indices
  39936. var vertexNb = positions.length / 3;
  39937. for (var i = 1; i < vertexNb - 1; i++) {
  39938. indices.push(i + 1, 0, i);
  39939. }
  39940. // result
  39941. VertexData.ComputeNormals(positions, indices, normals);
  39942. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  39943. var vertexData = new VertexData();
  39944. vertexData.indices = indices;
  39945. vertexData.positions = positions;
  39946. vertexData.normals = normals;
  39947. vertexData.uvs = uvs;
  39948. return vertexData;
  39949. };
  39950. /**
  39951. * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()
  39952. * All parameters are provided by MeshBuilder.CreatePolygon as needed
  39953. * @param polygon a mesh built from polygonTriangulation.build()
  39954. * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39955. * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  39956. * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  39957. * @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)
  39958. * @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)
  39959. * @returns the VertexData of the Polygon
  39960. */
  39961. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  39962. var faceUV = fUV || new Array(3);
  39963. var faceColors = fColors;
  39964. var colors = [];
  39965. // default face colors and UV if undefined
  39966. for (var f = 0; f < 3; f++) {
  39967. if (faceUV[f] === undefined) {
  39968. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  39969. }
  39970. if (faceColors && faceColors[f] === undefined) {
  39971. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  39972. }
  39973. }
  39974. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39975. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  39976. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  39977. var indices = polygon.getIndices();
  39978. // set face colours and textures
  39979. var idx = 0;
  39980. var face = 0;
  39981. for (var index = 0; index < normals.length; index += 3) {
  39982. //Edge Face no. 1
  39983. if (Math.abs(normals[index + 1]) < 0.001) {
  39984. face = 1;
  39985. }
  39986. //Top Face no. 0
  39987. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  39988. face = 0;
  39989. }
  39990. //Bottom Face no. 2
  39991. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  39992. face = 2;
  39993. }
  39994. idx = index / 3;
  39995. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  39996. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  39997. if (faceColors) {
  39998. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  39999. }
  40000. }
  40001. // sides
  40002. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  40003. // Result
  40004. var vertexData = new VertexData();
  40005. vertexData.indices = indices;
  40006. vertexData.positions = positions;
  40007. vertexData.normals = normals;
  40008. vertexData.uvs = uvs;
  40009. if (faceColors) {
  40010. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  40011. vertexData.colors = totalColors;
  40012. }
  40013. return vertexData;
  40014. };
  40015. /**
  40016. * Creates the VertexData of the IcoSphere
  40017. * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty
  40018. * * radius the radius of the IcoSphere, optional default 1
  40019. * * radiusX allows stretching in the x direction, optional, default radius
  40020. * * radiusY allows stretching in the y direction, optional, default radius
  40021. * * radiusZ allows stretching in the z direction, optional, default radius
  40022. * * flat when true creates a flat shaded mesh, optional, default true
  40023. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  40024. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  40025. * * 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)
  40026. * * 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)
  40027. * @returns the VertexData of the IcoSphere
  40028. */
  40029. VertexData.CreateIcoSphere = function (options) {
  40030. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  40031. var radius = options.radius || 1;
  40032. var flat = (options.flat === undefined) ? true : options.flat;
  40033. var subdivisions = options.subdivisions || 4;
  40034. var radiusX = options.radiusX || radius;
  40035. var radiusY = options.radiusY || radius;
  40036. var radiusZ = options.radiusZ || radius;
  40037. var t = (1 + Math.sqrt(5)) / 2;
  40038. // 12 vertex x,y,z
  40039. var ico_vertices = [
  40040. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  40041. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  40042. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  40043. ];
  40044. // index of 3 vertex makes a face of icopshere
  40045. var ico_indices = [
  40046. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  40047. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  40048. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  40049. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  40050. ];
  40051. // vertex for uv have aliased position, not for UV
  40052. var vertices_unalias_id = [
  40053. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  40054. // vertex alias
  40055. 0,
  40056. 2,
  40057. 3,
  40058. 3,
  40059. 3,
  40060. 4,
  40061. 7,
  40062. 8,
  40063. 9,
  40064. 9,
  40065. 10,
  40066. 11 // 23: B + 12
  40067. ];
  40068. // uv as integer step (not pixels !)
  40069. var ico_vertexuv = [
  40070. 5, 1, 3, 1, 6, 4, 0, 0,
  40071. 5, 3, 4, 2, 2, 2, 4, 0,
  40072. 2, 0, 1, 1, 6, 0, 6, 2,
  40073. // vertex alias (for same vertex on different faces)
  40074. 0, 4,
  40075. 3, 3,
  40076. 4, 4,
  40077. 3, 1,
  40078. 4, 2,
  40079. 4, 4,
  40080. 0, 2,
  40081. 1, 1,
  40082. 2, 2,
  40083. 3, 3,
  40084. 1, 3,
  40085. 2, 4 // 23: B + 12
  40086. ];
  40087. // Vertices[0, 1, ...9, A, B] : position on UV plane
  40088. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  40089. // First island of uv mapping
  40090. // v = 4h 3+ 2
  40091. // v = 3h 9+ 4
  40092. // v = 2h 9+ 5 B
  40093. // v = 1h 9 1 0
  40094. // v = 0h 3 8 7 A
  40095. // u = 0 1 2 3 4 5 6 *a
  40096. // Second island of uv mapping
  40097. // v = 4h 0+ B+ 4+
  40098. // v = 3h A+ 2+
  40099. // v = 2h 7+ 6 3+
  40100. // v = 1h 8+ 3+
  40101. // v = 0h
  40102. // u = 0 1 2 3 4 5 6 *a
  40103. // Face layout on texture UV mapping
  40104. // ============
  40105. // \ 4 /\ 16 / ======
  40106. // \ / \ / /\ 11 /
  40107. // \/ 7 \/ / \ /
  40108. // ======= / 10 \/
  40109. // /\ 17 /\ =======
  40110. // / \ / \ \ 15 /\
  40111. // / 8 \/ 12 \ \ / \
  40112. // ============ \/ 6 \
  40113. // \ 18 /\ ============
  40114. // \ / \ \ 5 /\ 0 /
  40115. // \/ 13 \ \ / \ /
  40116. // ======= \/ 1 \/
  40117. // =============
  40118. // /\ 19 /\ 2 /\
  40119. // / \ / \ / \
  40120. // / 14 \/ 9 \/ 3 \
  40121. // ===================
  40122. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  40123. var ustep = 138 / 1024;
  40124. var vstep = 239 / 1024;
  40125. var uoffset = 60 / 1024;
  40126. var voffset = 26 / 1024;
  40127. // Second island should have margin, not to touch the first island
  40128. // avoid any borderline artefact in pixel rounding
  40129. var island_u_offset = -40 / 1024;
  40130. var island_v_offset = +20 / 1024;
  40131. // face is either island 0 or 1 :
  40132. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  40133. var island = [
  40134. 0, 0, 0, 0, 1,
  40135. 0, 0, 1, 1, 0,
  40136. 0, 0, 1, 1, 0,
  40137. 0, 1, 1, 1, 0 // 15 - 19
  40138. ];
  40139. var indices = new Array();
  40140. var positions = new Array();
  40141. var normals = new Array();
  40142. var uvs = new Array();
  40143. var current_indice = 0;
  40144. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  40145. var face_vertex_pos = new Array(3);
  40146. var face_vertex_uv = new Array(3);
  40147. var v012;
  40148. for (v012 = 0; v012 < 3; v012++) {
  40149. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  40150. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  40151. }
  40152. // create all with normals
  40153. for (var face = 0; face < 20; face++) {
  40154. // 3 vertex per face
  40155. for (v012 = 0; v012 < 3; v012++) {
  40156. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  40157. var v_id = ico_indices[3 * face + v012];
  40158. // vertex have 3D position (x,y,z)
  40159. 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]);
  40160. // Normalize to get normal, then scale to radius
  40161. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  40162. // uv Coordinates from vertex ID
  40163. 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);
  40164. }
  40165. // Subdivide the face (interpolate pos, norm, uv)
  40166. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  40167. // - norm is linear interpolation of vertex corner normal
  40168. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  40169. // - uv is linear interpolation
  40170. //
  40171. // Topology is as below for sub-divide by 2
  40172. // vertex shown as v0,v1,v2
  40173. // interp index is i1 to progress in range [v0,v1[
  40174. // interp index is i2 to progress in range [v0,v2[
  40175. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  40176. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  40177. //
  40178. //
  40179. // i2 v2
  40180. // ^ ^
  40181. // / / \
  40182. // / / \
  40183. // / / \
  40184. // / / (0,1) \
  40185. // / #---------\
  40186. // / / \ (0,0)'/ \
  40187. // / / \ / \
  40188. // / / \ / \
  40189. // / / (0,0) \ / (1,0) \
  40190. // / #---------#---------\
  40191. // v0 v1
  40192. //
  40193. // --------------------> i1
  40194. //
  40195. // interp of (i1,i2):
  40196. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  40197. // along i1 : lerp(x0,x1, i1/(S-i2))
  40198. //
  40199. // centroid of triangle is needed to get help normal computation
  40200. // (c1,c2) are used for centroid location
  40201. var interp_vertex = function (i1, i2, c1, c2) {
  40202. // vertex is interpolated from
  40203. // - face_vertex_pos[0..2]
  40204. // - face_vertex_uv[0..2]
  40205. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  40206. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  40207. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  40208. pos_interp.normalize();
  40209. var vertex_normal;
  40210. if (flat) {
  40211. // in flat mode, recalculate normal as face centroid normal
  40212. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  40213. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  40214. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  40215. }
  40216. else {
  40217. // in smooth mode, recalculate normal from each single vertex position
  40218. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  40219. }
  40220. // Vertex normal need correction due to X,Y,Z radius scaling
  40221. vertex_normal.x /= radiusX;
  40222. vertex_normal.y /= radiusY;
  40223. vertex_normal.z /= radiusZ;
  40224. vertex_normal.normalize();
  40225. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  40226. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  40227. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  40228. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  40229. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  40230. uvs.push(uv_interp.x, uv_interp.y);
  40231. // push each vertex has member of a face
  40232. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  40233. indices.push(current_indice);
  40234. current_indice++;
  40235. };
  40236. for (var i2 = 0; i2 < subdivisions; i2++) {
  40237. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  40238. // face : (i1,i2) for /\ :
  40239. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  40240. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  40241. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  40242. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  40243. if (i1 + i2 + 1 < subdivisions) {
  40244. // face : (i1,i2)' for \/ :
  40245. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  40246. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  40247. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  40248. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  40249. }
  40250. }
  40251. }
  40252. }
  40253. // Sides
  40254. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  40255. // Result
  40256. var vertexData = new VertexData();
  40257. vertexData.indices = indices;
  40258. vertexData.positions = positions;
  40259. vertexData.normals = normals;
  40260. vertexData.uvs = uvs;
  40261. return vertexData;
  40262. };
  40263. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  40264. /**
  40265. * Creates the VertexData for a Polyhedron
  40266. * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty
  40267. * * type provided types are:
  40268. * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  40269. * * 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)
  40270. * * size the size of the IcoSphere, optional default 1
  40271. * * sizeX allows stretching in the x direction, optional, default size
  40272. * * sizeY allows stretching in the y direction, optional, default size
  40273. * * sizeZ allows stretching in the z direction, optional, default size
  40274. * * 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
  40275. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  40276. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  40277. * * flat when true creates a flat shaded mesh, optional, default true
  40278. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  40279. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  40280. * * 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)
  40281. * * 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)
  40282. * @returns the VertexData of the Polyhedron
  40283. */
  40284. VertexData.CreatePolyhedron = function (options) {
  40285. // provided polyhedron types :
  40286. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  40287. // 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)
  40288. var polyhedra = [];
  40289. 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]] };
  40290. 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]] };
  40291. polyhedra[2] = {
  40292. 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]],
  40293. 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]]
  40294. };
  40295. polyhedra[3] = {
  40296. 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]],
  40297. 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]]
  40298. };
  40299. polyhedra[4] = {
  40300. 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]],
  40301. 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]]
  40302. };
  40303. 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]] };
  40304. 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]] };
  40305. 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]] };
  40306. 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]] };
  40307. 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]] };
  40308. 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]] };
  40309. 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]] };
  40310. 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]] };
  40311. 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]] };
  40312. polyhedra[14] = {
  40313. 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]],
  40314. 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]]
  40315. };
  40316. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  40317. var size = options.size;
  40318. var sizeX = options.sizeX || size || 1;
  40319. var sizeY = options.sizeY || size || 1;
  40320. var sizeZ = options.sizeZ || size || 1;
  40321. var data = options.custom || polyhedra[type];
  40322. var nbfaces = data.face.length;
  40323. var faceUV = options.faceUV || new Array(nbfaces);
  40324. var faceColors = options.faceColors;
  40325. var flat = (options.flat === undefined) ? true : options.flat;
  40326. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  40327. var positions = new Array();
  40328. var indices = new Array();
  40329. var normals = new Array();
  40330. var uvs = new Array();
  40331. var colors = new Array();
  40332. var index = 0;
  40333. var faceIdx = 0; // face cursor in the array "indexes"
  40334. var indexes = new Array();
  40335. var i = 0;
  40336. var f = 0;
  40337. var u, v, ang, x, y, tmp;
  40338. // default face colors and UV if undefined
  40339. if (flat) {
  40340. for (f = 0; f < nbfaces; f++) {
  40341. if (faceColors && faceColors[f] === undefined) {
  40342. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  40343. }
  40344. if (faceUV && faceUV[f] === undefined) {
  40345. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  40346. }
  40347. }
  40348. }
  40349. if (!flat) {
  40350. for (i = 0; i < data.vertex.length; i++) {
  40351. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  40352. uvs.push(0, 0);
  40353. }
  40354. for (f = 0; f < nbfaces; f++) {
  40355. for (i = 0; i < data.face[f].length - 2; i++) {
  40356. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  40357. }
  40358. }
  40359. }
  40360. else {
  40361. for (f = 0; f < nbfaces; f++) {
  40362. var fl = data.face[f].length; // number of vertices of the current face
  40363. ang = 2 * Math.PI / fl;
  40364. x = 0.5 * Math.tan(ang / 2);
  40365. y = 0.5;
  40366. // positions, uvs, colors
  40367. for (i = 0; i < fl; i++) {
  40368. // positions
  40369. 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);
  40370. indexes.push(index);
  40371. index++;
  40372. // uvs
  40373. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  40374. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  40375. uvs.push(u, v);
  40376. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  40377. y = x * Math.sin(ang) + y * Math.cos(ang);
  40378. x = tmp;
  40379. // colors
  40380. if (faceColors) {
  40381. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  40382. }
  40383. }
  40384. // indices from indexes
  40385. for (i = 0; i < fl - 2; i++) {
  40386. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  40387. }
  40388. faceIdx += fl;
  40389. }
  40390. }
  40391. VertexData.ComputeNormals(positions, indices, normals);
  40392. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  40393. var vertexData = new VertexData();
  40394. vertexData.positions = positions;
  40395. vertexData.indices = indices;
  40396. vertexData.normals = normals;
  40397. vertexData.uvs = uvs;
  40398. if (faceColors && flat) {
  40399. vertexData.colors = colors;
  40400. }
  40401. return vertexData;
  40402. };
  40403. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  40404. /**
  40405. * Creates the VertexData for a TorusKnot
  40406. * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty
  40407. * * radius the radius of the torus knot, optional, default 2
  40408. * * tube the thickness of the tube, optional, default 0.5
  40409. * * radialSegments the number of sides on each tube segments, optional, default 32
  40410. * * tubularSegments the number of tubes to decompose the knot into, optional, default 32
  40411. * * p the number of windings around the z axis, optional, default 2
  40412. * * q the number of windings around the x axis, optional, default 3
  40413. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  40414. * * 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)
  40415. * * 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)
  40416. * @returns the VertexData of the Torus Knot
  40417. */
  40418. VertexData.CreateTorusKnot = function (options) {
  40419. var indices = new Array();
  40420. var positions = new Array();
  40421. var normals = new Array();
  40422. var uvs = new Array();
  40423. var radius = options.radius || 2;
  40424. var tube = options.tube || 0.5;
  40425. var radialSegments = options.radialSegments || 32;
  40426. var tubularSegments = options.tubularSegments || 32;
  40427. var p = options.p || 2;
  40428. var q = options.q || 3;
  40429. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  40430. // Helper
  40431. var getPos = function (angle) {
  40432. var cu = Math.cos(angle);
  40433. var su = Math.sin(angle);
  40434. var quOverP = q / p * angle;
  40435. var cs = Math.cos(quOverP);
  40436. var tx = radius * (2 + cs) * 0.5 * cu;
  40437. var ty = radius * (2 + cs) * su * 0.5;
  40438. var tz = radius * Math.sin(quOverP) * 0.5;
  40439. return new BABYLON.Vector3(tx, ty, tz);
  40440. };
  40441. // Vertices
  40442. var i;
  40443. var j;
  40444. for (i = 0; i <= radialSegments; i++) {
  40445. var modI = i % radialSegments;
  40446. var u = modI / radialSegments * 2 * p * Math.PI;
  40447. var p1 = getPos(u);
  40448. var p2 = getPos(u + 0.01);
  40449. var tang = p2.subtract(p1);
  40450. var n = p2.add(p1);
  40451. var bitan = BABYLON.Vector3.Cross(tang, n);
  40452. n = BABYLON.Vector3.Cross(bitan, tang);
  40453. bitan.normalize();
  40454. n.normalize();
  40455. for (j = 0; j < tubularSegments; j++) {
  40456. var modJ = j % tubularSegments;
  40457. var v = modJ / tubularSegments * 2 * Math.PI;
  40458. var cx = -tube * Math.cos(v);
  40459. var cy = tube * Math.sin(v);
  40460. positions.push(p1.x + cx * n.x + cy * bitan.x);
  40461. positions.push(p1.y + cx * n.y + cy * bitan.y);
  40462. positions.push(p1.z + cx * n.z + cy * bitan.z);
  40463. uvs.push(i / radialSegments);
  40464. uvs.push(j / tubularSegments);
  40465. }
  40466. }
  40467. for (i = 0; i < radialSegments; i++) {
  40468. for (j = 0; j < tubularSegments; j++) {
  40469. var jNext = (j + 1) % tubularSegments;
  40470. var a = i * tubularSegments + j;
  40471. var b = (i + 1) * tubularSegments + j;
  40472. var c = (i + 1) * tubularSegments + jNext;
  40473. var d = i * tubularSegments + jNext;
  40474. indices.push(d);
  40475. indices.push(b);
  40476. indices.push(a);
  40477. indices.push(d);
  40478. indices.push(c);
  40479. indices.push(b);
  40480. }
  40481. }
  40482. // Normals
  40483. VertexData.ComputeNormals(positions, indices, normals);
  40484. // Sides
  40485. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  40486. // Result
  40487. var vertexData = new VertexData();
  40488. vertexData.indices = indices;
  40489. vertexData.positions = positions;
  40490. vertexData.normals = normals;
  40491. vertexData.uvs = uvs;
  40492. return vertexData;
  40493. };
  40494. // Tools
  40495. /**
  40496. * Compute normals for given positions and indices
  40497. * @param positions an array of vertex positions, [...., x, y, z, ......]
  40498. * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]
  40499. * @param normals an array of vertex normals, [...., x, y, z, ......]
  40500. * @param options an object used to set the following optional parameters for the TorusKnot, optional
  40501. * * facetNormals : optional array of facet normals (vector3)
  40502. * * facetPositions : optional array of facet positions (vector3)
  40503. * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  40504. * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  40505. * * bInfo : optional bounding info, required for facetPartitioning computation
  40506. * * bbSize : optional bounding box size data, required for facetPartitioning computation
  40507. * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  40508. * * useRightHandedSystem: optional boolean to for right handed system computation
  40509. * * depthSort : optional boolean to enable the facet depth sort computation
  40510. * * distanceTo : optional Vector3 to compute the facet depth from this location
  40511. * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  40512. */
  40513. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  40514. // temporary scalar variables
  40515. var index = 0; // facet index
  40516. var p1p2x = 0.0; // p1p2 vector x coordinate
  40517. var p1p2y = 0.0; // p1p2 vector y coordinate
  40518. var p1p2z = 0.0; // p1p2 vector z coordinate
  40519. var p3p2x = 0.0; // p3p2 vector x coordinate
  40520. var p3p2y = 0.0; // p3p2 vector y coordinate
  40521. var p3p2z = 0.0; // p3p2 vector z coordinate
  40522. var faceNormalx = 0.0; // facet normal x coordinate
  40523. var faceNormaly = 0.0; // facet normal y coordinate
  40524. var faceNormalz = 0.0; // facet normal z coordinate
  40525. var length = 0.0; // facet normal length before normalization
  40526. var v1x = 0; // vector1 x index in the positions array
  40527. var v1y = 0; // vector1 y index in the positions array
  40528. var v1z = 0; // vector1 z index in the positions array
  40529. var v2x = 0; // vector2 x index in the positions array
  40530. var v2y = 0; // vector2 y index in the positions array
  40531. var v2z = 0; // vector2 z index in the positions array
  40532. var v3x = 0; // vector3 x index in the positions array
  40533. var v3y = 0; // vector3 y index in the positions array
  40534. var v3z = 0; // vector3 z index in the positions array
  40535. var computeFacetNormals = false;
  40536. var computeFacetPositions = false;
  40537. var computeFacetPartitioning = false;
  40538. var computeDepthSort = false;
  40539. var faceNormalSign = 1;
  40540. var ratio = 0;
  40541. var distanceTo = null;
  40542. if (options) {
  40543. computeFacetNormals = (options.facetNormals) ? true : false;
  40544. computeFacetPositions = (options.facetPositions) ? true : false;
  40545. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  40546. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  40547. ratio = options.ratio || 0;
  40548. computeDepthSort = (options.depthSort) ? true : false;
  40549. distanceTo = (options.distanceTo);
  40550. if (computeDepthSort) {
  40551. if (distanceTo === undefined) {
  40552. distanceTo = BABYLON.Vector3.Zero();
  40553. }
  40554. var depthSortedFacets = options.depthSortedFacets;
  40555. }
  40556. }
  40557. // facetPartitioning reinit if needed
  40558. var xSubRatio = 0;
  40559. var ySubRatio = 0;
  40560. var zSubRatio = 0;
  40561. var subSq = 0;
  40562. if (computeFacetPartitioning && options && options.bbSize) {
  40563. var ox = 0; // X partitioning index for facet position
  40564. var oy = 0; // Y partinioning index for facet position
  40565. var oz = 0; // Z partinioning index for facet position
  40566. var b1x = 0; // X partitioning index for facet v1 vertex
  40567. var b1y = 0; // Y partitioning index for facet v1 vertex
  40568. var b1z = 0; // z partitioning index for facet v1 vertex
  40569. var b2x = 0; // X partitioning index for facet v2 vertex
  40570. var b2y = 0; // Y partitioning index for facet v2 vertex
  40571. var b2z = 0; // Z partitioning index for facet v2 vertex
  40572. var b3x = 0; // X partitioning index for facet v3 vertex
  40573. var b3y = 0; // Y partitioning index for facet v3 vertex
  40574. var b3z = 0; // Z partitioning index for facet v3 vertex
  40575. var block_idx_o = 0; // facet barycenter block index
  40576. var block_idx_v1 = 0; // v1 vertex block index
  40577. var block_idx_v2 = 0; // v2 vertex block index
  40578. var block_idx_v3 = 0; // v3 vertex block index
  40579. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  40580. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  40581. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  40582. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  40583. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  40584. subSq = options.subDiv.max * options.subDiv.max;
  40585. options.facetPartitioning.length = 0;
  40586. }
  40587. // reset the normals
  40588. for (index = 0; index < positions.length; index++) {
  40589. normals[index] = 0.0;
  40590. }
  40591. // Loop : 1 indice triplet = 1 facet
  40592. var nbFaces = (indices.length / 3) | 0;
  40593. for (index = 0; index < nbFaces; index++) {
  40594. // get the indexes of the coordinates of each vertex of the facet
  40595. v1x = indices[index * 3] * 3;
  40596. v1y = v1x + 1;
  40597. v1z = v1x + 2;
  40598. v2x = indices[index * 3 + 1] * 3;
  40599. v2y = v2x + 1;
  40600. v2z = v2x + 2;
  40601. v3x = indices[index * 3 + 2] * 3;
  40602. v3y = v3x + 1;
  40603. v3z = v3x + 2;
  40604. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  40605. p1p2y = positions[v1y] - positions[v2y];
  40606. p1p2z = positions[v1z] - positions[v2z];
  40607. p3p2x = positions[v3x] - positions[v2x];
  40608. p3p2y = positions[v3y] - positions[v2y];
  40609. p3p2z = positions[v3z] - positions[v2z];
  40610. // compute the face normal with the cross product
  40611. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  40612. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  40613. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  40614. // normalize this normal and store it in the array facetData
  40615. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  40616. length = (length === 0) ? 1.0 : length;
  40617. faceNormalx /= length;
  40618. faceNormaly /= length;
  40619. faceNormalz /= length;
  40620. if (computeFacetNormals && options) {
  40621. options.facetNormals[index].x = faceNormalx;
  40622. options.facetNormals[index].y = faceNormaly;
  40623. options.facetNormals[index].z = faceNormalz;
  40624. }
  40625. if (computeFacetPositions && options) {
  40626. // compute and the facet barycenter coordinates in the array facetPositions
  40627. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  40628. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  40629. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  40630. }
  40631. if (computeFacetPartitioning && options) {
  40632. // store the facet indexes in arrays in the main facetPartitioning array :
  40633. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  40634. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  40635. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  40636. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  40637. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  40638. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  40639. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  40640. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  40641. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  40642. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  40643. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  40644. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  40645. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  40646. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  40647. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  40648. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  40649. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  40650. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  40651. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  40652. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  40653. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  40654. // push each facet index in each block containing the vertex
  40655. options.facetPartitioning[block_idx_v1].push(index);
  40656. if (block_idx_v2 != block_idx_v1) {
  40657. options.facetPartitioning[block_idx_v2].push(index);
  40658. }
  40659. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  40660. options.facetPartitioning[block_idx_v3].push(index);
  40661. }
  40662. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  40663. options.facetPartitioning[block_idx_o].push(index);
  40664. }
  40665. }
  40666. if (computeDepthSort && options && options.facetPositions) {
  40667. var dsf = depthSortedFacets[index];
  40668. dsf.ind = index * 3;
  40669. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  40670. }
  40671. // compute the normals anyway
  40672. normals[v1x] += faceNormalx; // accumulate all the normals per face
  40673. normals[v1y] += faceNormaly;
  40674. normals[v1z] += faceNormalz;
  40675. normals[v2x] += faceNormalx;
  40676. normals[v2y] += faceNormaly;
  40677. normals[v2z] += faceNormalz;
  40678. normals[v3x] += faceNormalx;
  40679. normals[v3y] += faceNormaly;
  40680. normals[v3z] += faceNormalz;
  40681. }
  40682. // last normalization of each normal
  40683. for (index = 0; index < normals.length / 3; index++) {
  40684. faceNormalx = normals[index * 3];
  40685. faceNormaly = normals[index * 3 + 1];
  40686. faceNormalz = normals[index * 3 + 2];
  40687. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  40688. length = (length === 0) ? 1.0 : length;
  40689. faceNormalx /= length;
  40690. faceNormaly /= length;
  40691. faceNormalz /= length;
  40692. normals[index * 3] = faceNormalx;
  40693. normals[index * 3 + 1] = faceNormaly;
  40694. normals[index * 3 + 2] = faceNormalz;
  40695. }
  40696. };
  40697. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  40698. var li = indices.length;
  40699. var ln = normals.length;
  40700. var i;
  40701. var n;
  40702. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  40703. switch (sideOrientation) {
  40704. case BABYLON.Mesh.FRONTSIDE:
  40705. // nothing changed
  40706. break;
  40707. case BABYLON.Mesh.BACKSIDE:
  40708. var tmp;
  40709. // indices
  40710. for (i = 0; i < li; i += 3) {
  40711. tmp = indices[i];
  40712. indices[i] = indices[i + 2];
  40713. indices[i + 2] = tmp;
  40714. }
  40715. // normals
  40716. for (n = 0; n < ln; n++) {
  40717. normals[n] = -normals[n];
  40718. }
  40719. break;
  40720. case BABYLON.Mesh.DOUBLESIDE:
  40721. // positions
  40722. var lp = positions.length;
  40723. var l = lp / 3;
  40724. for (var p = 0; p < lp; p++) {
  40725. positions[lp + p] = positions[p];
  40726. }
  40727. // indices
  40728. for (i = 0; i < li; i += 3) {
  40729. indices[i + li] = indices[i + 2] + l;
  40730. indices[i + 1 + li] = indices[i + 1] + l;
  40731. indices[i + 2 + li] = indices[i] + l;
  40732. }
  40733. // normals
  40734. for (n = 0; n < ln; n++) {
  40735. normals[ln + n] = -normals[n];
  40736. }
  40737. // uvs
  40738. var lu = uvs.length;
  40739. var u = 0;
  40740. for (u = 0; u < lu; u++) {
  40741. uvs[u + lu] = uvs[u];
  40742. }
  40743. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  40744. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  40745. u = 0;
  40746. for (i = 0; i < lu / 2; i++) {
  40747. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  40748. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  40749. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  40750. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  40751. u += 2;
  40752. }
  40753. break;
  40754. }
  40755. };
  40756. /**
  40757. * Applies VertexData created from the imported parameters to the geometry
  40758. * @param parsedVertexData the parsed data from an imported file
  40759. * @param geometry the geometry to apply the VertexData to
  40760. */
  40761. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  40762. var vertexData = new VertexData();
  40763. // positions
  40764. var positions = parsedVertexData.positions;
  40765. if (positions) {
  40766. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  40767. }
  40768. // normals
  40769. var normals = parsedVertexData.normals;
  40770. if (normals) {
  40771. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  40772. }
  40773. // tangents
  40774. var tangents = parsedVertexData.tangents;
  40775. if (tangents) {
  40776. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  40777. }
  40778. // uvs
  40779. var uvs = parsedVertexData.uvs;
  40780. if (uvs) {
  40781. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  40782. }
  40783. // uv2s
  40784. var uv2s = parsedVertexData.uv2s;
  40785. if (uv2s) {
  40786. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  40787. }
  40788. // uv3s
  40789. var uv3s = parsedVertexData.uv3s;
  40790. if (uv3s) {
  40791. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  40792. }
  40793. // uv4s
  40794. var uv4s = parsedVertexData.uv4s;
  40795. if (uv4s) {
  40796. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  40797. }
  40798. // uv5s
  40799. var uv5s = parsedVertexData.uv5s;
  40800. if (uv5s) {
  40801. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  40802. }
  40803. // uv6s
  40804. var uv6s = parsedVertexData.uv6s;
  40805. if (uv6s) {
  40806. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  40807. }
  40808. // colors
  40809. var colors = parsedVertexData.colors;
  40810. if (colors) {
  40811. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  40812. }
  40813. // matricesIndices
  40814. var matricesIndices = parsedVertexData.matricesIndices;
  40815. if (matricesIndices) {
  40816. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  40817. }
  40818. // matricesWeights
  40819. var matricesWeights = parsedVertexData.matricesWeights;
  40820. if (matricesWeights) {
  40821. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  40822. }
  40823. // indices
  40824. var indices = parsedVertexData.indices;
  40825. if (indices) {
  40826. vertexData.indices = indices;
  40827. }
  40828. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  40829. };
  40830. return VertexData;
  40831. }());
  40832. BABYLON.VertexData = VertexData;
  40833. })(BABYLON || (BABYLON = {}));
  40834. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  40835. var BABYLON;
  40836. (function (BABYLON) {
  40837. /**
  40838. * Class used to store geometry data (vertex buffers + index buffer)
  40839. */
  40840. var Geometry = /** @class */ (function () {
  40841. /**
  40842. * Creates a new geometry
  40843. * @param id defines the unique ID
  40844. * @param scene defines the hosting scene
  40845. * @param vertexData defines the VertexData used to get geometry data
  40846. * @param updatable defines if geometry must be updatable (false by default)
  40847. * @param mesh defines the mesh that will be associated with the geometry
  40848. */
  40849. function Geometry(id, scene, vertexData, updatable, mesh) {
  40850. if (updatable === void 0) { updatable = false; }
  40851. if (mesh === void 0) { mesh = null; }
  40852. /**
  40853. * Gets the delay loading state of the geometry (none by default which means not delayed)
  40854. */
  40855. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  40856. this._totalVertices = 0;
  40857. this._isDisposed = false;
  40858. this._indexBufferIsUpdatable = false;
  40859. this.id = id;
  40860. this.uniqueId = scene.getUniqueId();
  40861. this._engine = scene.getEngine();
  40862. this._meshes = [];
  40863. this._scene = scene;
  40864. //Init vertex buffer cache
  40865. this._vertexBuffers = {};
  40866. this._indices = [];
  40867. this._updatable = updatable;
  40868. // vertexData
  40869. if (vertexData) {
  40870. this.setAllVerticesData(vertexData, updatable);
  40871. }
  40872. else {
  40873. this._totalVertices = 0;
  40874. this._indices = [];
  40875. }
  40876. if (this._engine.getCaps().vertexArrayObject) {
  40877. this._vertexArrayObjects = {};
  40878. }
  40879. // applyToMesh
  40880. if (mesh) {
  40881. this.applyToMesh(mesh);
  40882. mesh.computeWorldMatrix(true);
  40883. }
  40884. }
  40885. Object.defineProperty(Geometry.prototype, "boundingBias", {
  40886. /**
  40887. * 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
  40888. */
  40889. get: function () {
  40890. return this._boundingBias;
  40891. },
  40892. /**
  40893. * 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
  40894. */
  40895. set: function (value) {
  40896. if (this._boundingBias) {
  40897. this._boundingBias.copyFrom(value);
  40898. }
  40899. else {
  40900. this._boundingBias = value.clone();
  40901. }
  40902. this._updateBoundingInfo(true, null);
  40903. },
  40904. enumerable: true,
  40905. configurable: true
  40906. });
  40907. /**
  40908. * Static function used to attach a new empty geometry to a mesh
  40909. * @param mesh defines the mesh to attach the geometry to
  40910. * @returns the new Geometry
  40911. */
  40912. Geometry.CreateGeometryForMesh = function (mesh) {
  40913. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  40914. geometry.applyToMesh(mesh);
  40915. return geometry;
  40916. };
  40917. Object.defineProperty(Geometry.prototype, "extend", {
  40918. /**
  40919. * Gets the current extend of the geometry
  40920. */
  40921. get: function () {
  40922. return this._extend;
  40923. },
  40924. enumerable: true,
  40925. configurable: true
  40926. });
  40927. /**
  40928. * Gets the hosting scene
  40929. * @returns the hosting Scene
  40930. */
  40931. Geometry.prototype.getScene = function () {
  40932. return this._scene;
  40933. };
  40934. /**
  40935. * Gets the hosting engine
  40936. * @returns the hosting Engine
  40937. */
  40938. Geometry.prototype.getEngine = function () {
  40939. return this._engine;
  40940. };
  40941. /**
  40942. * Defines if the geometry is ready to use
  40943. * @returns true if the geometry is ready to be used
  40944. */
  40945. Geometry.prototype.isReady = function () {
  40946. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  40947. };
  40948. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  40949. /**
  40950. * Gets a value indicating that the geometry should not be serialized
  40951. */
  40952. get: function () {
  40953. for (var index = 0; index < this._meshes.length; index++) {
  40954. if (!this._meshes[index].doNotSerialize) {
  40955. return false;
  40956. }
  40957. }
  40958. return true;
  40959. },
  40960. enumerable: true,
  40961. configurable: true
  40962. });
  40963. /** @hidden */
  40964. Geometry.prototype._rebuild = function () {
  40965. if (this._vertexArrayObjects) {
  40966. this._vertexArrayObjects = {};
  40967. }
  40968. // Index buffer
  40969. if (this._meshes.length !== 0 && this._indices) {
  40970. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  40971. }
  40972. // Vertex buffers
  40973. for (var key in this._vertexBuffers) {
  40974. var vertexBuffer = this._vertexBuffers[key];
  40975. vertexBuffer._rebuild();
  40976. }
  40977. };
  40978. /**
  40979. * Affects all geometry data in one call
  40980. * @param vertexData defines the geometry data
  40981. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  40982. */
  40983. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  40984. vertexData.applyToGeometry(this, updatable);
  40985. this.notifyUpdate();
  40986. };
  40987. /**
  40988. * Set specific vertex data
  40989. * @param kind defines the data kind (Position, normal, etc...)
  40990. * @param data defines the vertex data to use
  40991. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  40992. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  40993. */
  40994. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  40995. if (updatable === void 0) { updatable = false; }
  40996. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  40997. this.setVerticesBuffer(buffer);
  40998. };
  40999. /**
  41000. * Removes a specific vertex data
  41001. * @param kind defines the data kind (Position, normal, etc...)
  41002. */
  41003. Geometry.prototype.removeVerticesData = function (kind) {
  41004. if (this._vertexBuffers[kind]) {
  41005. this._vertexBuffers[kind].dispose();
  41006. delete this._vertexBuffers[kind];
  41007. }
  41008. };
  41009. /**
  41010. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  41011. * @param buffer defines the vertex buffer to use
  41012. * @param totalVertices defines the total number of vertices for position kind (could be null)
  41013. */
  41014. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  41015. if (totalVertices === void 0) { totalVertices = null; }
  41016. var kind = buffer.getKind();
  41017. if (this._vertexBuffers[kind]) {
  41018. this._vertexBuffers[kind].dispose();
  41019. }
  41020. this._vertexBuffers[kind] = buffer;
  41021. if (kind === BABYLON.VertexBuffer.PositionKind) {
  41022. var data = buffer.getData();
  41023. if (totalVertices != null) {
  41024. this._totalVertices = totalVertices;
  41025. }
  41026. else {
  41027. if (data != null) {
  41028. this._totalVertices = data.length / (buffer.byteStride / 4);
  41029. }
  41030. }
  41031. this._updateExtend(data);
  41032. this._resetPointsArrayCache();
  41033. var meshes = this._meshes;
  41034. var numOfMeshes = meshes.length;
  41035. for (var index = 0; index < numOfMeshes; index++) {
  41036. var mesh = meshes[index];
  41037. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  41038. mesh._createGlobalSubMesh(false);
  41039. mesh.computeWorldMatrix(true);
  41040. }
  41041. }
  41042. this.notifyUpdate(kind);
  41043. if (this._vertexArrayObjects) {
  41044. this._disposeVertexArrayObjects();
  41045. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  41046. }
  41047. };
  41048. /**
  41049. * Update a specific vertex buffer
  41050. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  41051. * It will do nothing if the buffer is not updatable
  41052. * @param kind defines the data kind (Position, normal, etc...)
  41053. * @param data defines the data to use
  41054. * @param offset defines the offset in the target buffer where to store the data
  41055. * @param useBytes set to true if the offset is in bytes
  41056. */
  41057. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) {
  41058. if (useBytes === void 0) { useBytes = false; }
  41059. var vertexBuffer = this.getVertexBuffer(kind);
  41060. if (!vertexBuffer) {
  41061. return;
  41062. }
  41063. vertexBuffer.updateDirectly(data, offset, useBytes);
  41064. this.notifyUpdate(kind);
  41065. };
  41066. /**
  41067. * Update a specific vertex buffer
  41068. * This function will create a new buffer if the current one is not updatable
  41069. * @param kind defines the data kind (Position, normal, etc...)
  41070. * @param data defines the data to use
  41071. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  41072. */
  41073. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  41074. if (updateExtends === void 0) { updateExtends = false; }
  41075. var vertexBuffer = this.getVertexBuffer(kind);
  41076. if (!vertexBuffer) {
  41077. return;
  41078. }
  41079. vertexBuffer.update(data);
  41080. if (kind === BABYLON.VertexBuffer.PositionKind) {
  41081. this._updateBoundingInfo(updateExtends, data);
  41082. }
  41083. this.notifyUpdate(kind);
  41084. };
  41085. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  41086. if (updateExtends) {
  41087. this._updateExtend(data);
  41088. }
  41089. this._resetPointsArrayCache();
  41090. if (updateExtends) {
  41091. var meshes = this._meshes;
  41092. for (var _i = 0, meshes_1 = meshes; _i < meshes_1.length; _i++) {
  41093. var mesh = meshes_1[_i];
  41094. if (mesh._boundingInfo) {
  41095. mesh._boundingInfo.reConstruct(this._extend.minimum, this._extend.maximum);
  41096. }
  41097. else {
  41098. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  41099. }
  41100. var subMeshes = mesh.subMeshes;
  41101. for (var _a = 0, subMeshes_1 = subMeshes; _a < subMeshes_1.length; _a++) {
  41102. var subMesh = subMeshes_1[_a];
  41103. subMesh.refreshBoundingInfo();
  41104. }
  41105. }
  41106. }
  41107. };
  41108. /** @hidden */
  41109. Geometry.prototype._bind = function (effect, indexToBind) {
  41110. if (!effect) {
  41111. return;
  41112. }
  41113. if (indexToBind === undefined) {
  41114. indexToBind = this._indexBuffer;
  41115. }
  41116. var vbs = this.getVertexBuffers();
  41117. if (!vbs) {
  41118. return;
  41119. }
  41120. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  41121. this._engine.bindBuffers(vbs, indexToBind, effect);
  41122. return;
  41123. }
  41124. // Using VAO
  41125. if (!this._vertexArrayObjects[effect.key]) {
  41126. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  41127. }
  41128. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  41129. };
  41130. /**
  41131. * Gets total number of vertices
  41132. * @returns the total number of vertices
  41133. */
  41134. Geometry.prototype.getTotalVertices = function () {
  41135. if (!this.isReady()) {
  41136. return 0;
  41137. }
  41138. return this._totalVertices;
  41139. };
  41140. /**
  41141. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  41142. * @param kind defines the data kind (Position, normal, etc...)
  41143. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  41144. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  41145. * @returns a float array containing vertex data
  41146. */
  41147. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  41148. var vertexBuffer = this.getVertexBuffer(kind);
  41149. if (!vertexBuffer) {
  41150. return null;
  41151. }
  41152. var data = vertexBuffer.getData();
  41153. if (!data) {
  41154. return null;
  41155. }
  41156. var tightlyPackedByteStride = vertexBuffer.getSize() * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  41157. var count = this._totalVertices * vertexBuffer.getSize();
  41158. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== tightlyPackedByteStride) {
  41159. var copy_1 = [];
  41160. vertexBuffer.forEach(count, function (value) { return copy_1.push(value); });
  41161. return copy_1;
  41162. }
  41163. if (!((data instanceof Array) || (data instanceof Float32Array)) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  41164. if (data instanceof Array) {
  41165. var offset = vertexBuffer.byteOffset / 4;
  41166. return BABYLON.Tools.Slice(data, offset, offset + count);
  41167. }
  41168. else if (data instanceof ArrayBuffer) {
  41169. return new Float32Array(data, vertexBuffer.byteOffset, count);
  41170. }
  41171. else {
  41172. var offset = data.byteOffset + vertexBuffer.byteOffset;
  41173. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  41174. var result = new Float32Array(count);
  41175. var source = new Float32Array(data.buffer, offset, count);
  41176. result.set(source);
  41177. return result;
  41178. }
  41179. return new Float32Array(data.buffer, offset, count);
  41180. }
  41181. }
  41182. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  41183. return BABYLON.Tools.Slice(data);
  41184. }
  41185. return data;
  41186. };
  41187. /**
  41188. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  41189. * @param kind defines the data kind (Position, normal, etc...)
  41190. * @returns true if the vertex buffer with the specified kind is updatable
  41191. */
  41192. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  41193. var vb = this._vertexBuffers[kind];
  41194. if (!vb) {
  41195. return false;
  41196. }
  41197. return vb.isUpdatable();
  41198. };
  41199. /**
  41200. * Gets a specific vertex buffer
  41201. * @param kind defines the data kind (Position, normal, etc...)
  41202. * @returns a VertexBuffer
  41203. */
  41204. Geometry.prototype.getVertexBuffer = function (kind) {
  41205. if (!this.isReady()) {
  41206. return null;
  41207. }
  41208. return this._vertexBuffers[kind];
  41209. };
  41210. /**
  41211. * Returns all vertex buffers
  41212. * @return an object holding all vertex buffers indexed by kind
  41213. */
  41214. Geometry.prototype.getVertexBuffers = function () {
  41215. if (!this.isReady()) {
  41216. return null;
  41217. }
  41218. return this._vertexBuffers;
  41219. };
  41220. /**
  41221. * Gets a boolean indicating if specific vertex buffer is present
  41222. * @param kind defines the data kind (Position, normal, etc...)
  41223. * @returns true if data is present
  41224. */
  41225. Geometry.prototype.isVerticesDataPresent = function (kind) {
  41226. if (!this._vertexBuffers) {
  41227. if (this._delayInfo) {
  41228. return this._delayInfo.indexOf(kind) !== -1;
  41229. }
  41230. return false;
  41231. }
  41232. return this._vertexBuffers[kind] !== undefined;
  41233. };
  41234. /**
  41235. * Gets a list of all attached data kinds (Position, normal, etc...)
  41236. * @returns a list of string containing all kinds
  41237. */
  41238. Geometry.prototype.getVerticesDataKinds = function () {
  41239. var result = [];
  41240. var kind;
  41241. if (!this._vertexBuffers && this._delayInfo) {
  41242. for (kind in this._delayInfo) {
  41243. result.push(kind);
  41244. }
  41245. }
  41246. else {
  41247. for (kind in this._vertexBuffers) {
  41248. result.push(kind);
  41249. }
  41250. }
  41251. return result;
  41252. };
  41253. /**
  41254. * Update index buffer
  41255. * @param indices defines the indices to store in the index buffer
  41256. * @param offset defines the offset in the target buffer where to store the data
  41257. */
  41258. Geometry.prototype.updateIndices = function (indices, offset) {
  41259. if (!this._indexBuffer) {
  41260. return;
  41261. }
  41262. if (!this._indexBufferIsUpdatable) {
  41263. this.setIndices(indices, null, true);
  41264. }
  41265. else {
  41266. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  41267. }
  41268. };
  41269. /**
  41270. * Creates a new index buffer
  41271. * @param indices defines the indices to store in the index buffer
  41272. * @param totalVertices defines the total number of vertices (could be null)
  41273. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  41274. */
  41275. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  41276. if (totalVertices === void 0) { totalVertices = null; }
  41277. if (updatable === void 0) { updatable = false; }
  41278. if (this._indexBuffer) {
  41279. this._engine._releaseBuffer(this._indexBuffer);
  41280. }
  41281. this._disposeVertexArrayObjects();
  41282. this._indices = indices;
  41283. this._indexBufferIsUpdatable = updatable;
  41284. if (this._meshes.length !== 0 && this._indices) {
  41285. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  41286. }
  41287. if (totalVertices != undefined) { // including null and undefined
  41288. this._totalVertices = totalVertices;
  41289. }
  41290. var meshes = this._meshes;
  41291. var numOfMeshes = meshes.length;
  41292. for (var index = 0; index < numOfMeshes; index++) {
  41293. meshes[index]._createGlobalSubMesh(true);
  41294. }
  41295. this.notifyUpdate();
  41296. };
  41297. /**
  41298. * Return the total number of indices
  41299. * @returns the total number of indices
  41300. */
  41301. Geometry.prototype.getTotalIndices = function () {
  41302. if (!this.isReady()) {
  41303. return 0;
  41304. }
  41305. return this._indices.length;
  41306. };
  41307. /**
  41308. * Gets the index buffer array
  41309. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  41310. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  41311. * @returns the index buffer array
  41312. */
  41313. Geometry.prototype.getIndices = function (copyWhenShared, forceCopy) {
  41314. if (!this.isReady()) {
  41315. return null;
  41316. }
  41317. var orig = this._indices;
  41318. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  41319. return orig;
  41320. }
  41321. else {
  41322. var len = orig.length;
  41323. var copy = [];
  41324. for (var i = 0; i < len; i++) {
  41325. copy.push(orig[i]);
  41326. }
  41327. return copy;
  41328. }
  41329. };
  41330. /**
  41331. * Gets the index buffer
  41332. * @return the index buffer
  41333. */
  41334. Geometry.prototype.getIndexBuffer = function () {
  41335. if (!this.isReady()) {
  41336. return null;
  41337. }
  41338. return this._indexBuffer;
  41339. };
  41340. /** @hidden */
  41341. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  41342. if (effect === void 0) { effect = null; }
  41343. if (!effect || !this._vertexArrayObjects) {
  41344. return;
  41345. }
  41346. if (this._vertexArrayObjects[effect.key]) {
  41347. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  41348. delete this._vertexArrayObjects[effect.key];
  41349. }
  41350. };
  41351. /**
  41352. * Release the associated resources for a specific mesh
  41353. * @param mesh defines the source mesh
  41354. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  41355. */
  41356. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  41357. var meshes = this._meshes;
  41358. var index = meshes.indexOf(mesh);
  41359. if (index === -1) {
  41360. return;
  41361. }
  41362. meshes.splice(index, 1);
  41363. mesh._geometry = null;
  41364. if (meshes.length === 0 && shouldDispose) {
  41365. this.dispose();
  41366. }
  41367. };
  41368. /**
  41369. * Apply current geometry to a given mesh
  41370. * @param mesh defines the mesh to apply geometry to
  41371. */
  41372. Geometry.prototype.applyToMesh = function (mesh) {
  41373. if (mesh._geometry === this) {
  41374. return;
  41375. }
  41376. var previousGeometry = mesh._geometry;
  41377. if (previousGeometry) {
  41378. previousGeometry.releaseForMesh(mesh);
  41379. }
  41380. var meshes = this._meshes;
  41381. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  41382. mesh._geometry = this;
  41383. this._scene.pushGeometry(this);
  41384. meshes.push(mesh);
  41385. if (this.isReady()) {
  41386. this._applyToMesh(mesh);
  41387. }
  41388. else {
  41389. mesh._boundingInfo = this._boundingInfo;
  41390. }
  41391. };
  41392. Geometry.prototype._updateExtend = function (data) {
  41393. if (data === void 0) { data = null; }
  41394. if (!data) {
  41395. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  41396. }
  41397. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  41398. };
  41399. Geometry.prototype._applyToMesh = function (mesh) {
  41400. var numOfMeshes = this._meshes.length;
  41401. // vertexBuffers
  41402. for (var kind in this._vertexBuffers) {
  41403. if (numOfMeshes === 1) {
  41404. this._vertexBuffers[kind].create();
  41405. }
  41406. var buffer = this._vertexBuffers[kind].getBuffer();
  41407. if (buffer) {
  41408. buffer.references = numOfMeshes;
  41409. }
  41410. if (kind === BABYLON.VertexBuffer.PositionKind) {
  41411. if (!this._extend) {
  41412. this._updateExtend();
  41413. }
  41414. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  41415. mesh._createGlobalSubMesh(false);
  41416. //bounding info was just created again, world matrix should be applied again.
  41417. mesh._updateBoundingInfo();
  41418. }
  41419. }
  41420. // indexBuffer
  41421. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  41422. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  41423. }
  41424. if (this._indexBuffer) {
  41425. this._indexBuffer.references = numOfMeshes;
  41426. }
  41427. // morphTargets
  41428. mesh._syncGeometryWithMorphTargetManager();
  41429. // instances
  41430. mesh.synchronizeInstances();
  41431. };
  41432. Geometry.prototype.notifyUpdate = function (kind) {
  41433. if (this.onGeometryUpdated) {
  41434. this.onGeometryUpdated(this, kind);
  41435. }
  41436. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  41437. var mesh = _a[_i];
  41438. mesh._markSubMeshesAsAttributesDirty();
  41439. }
  41440. };
  41441. /**
  41442. * Load the geometry if it was flagged as delay loaded
  41443. * @param scene defines the hosting scene
  41444. * @param onLoaded defines a callback called when the geometry is loaded
  41445. */
  41446. Geometry.prototype.load = function (scene, onLoaded) {
  41447. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  41448. return;
  41449. }
  41450. if (this.isReady()) {
  41451. if (onLoaded) {
  41452. onLoaded();
  41453. }
  41454. return;
  41455. }
  41456. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  41457. this._queueLoad(scene, onLoaded);
  41458. };
  41459. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  41460. var _this = this;
  41461. if (!this.delayLoadingFile) {
  41462. return;
  41463. }
  41464. scene._addPendingData(this);
  41465. scene._loadFile(this.delayLoadingFile, function (data) {
  41466. if (!_this._delayLoadingFunction) {
  41467. return;
  41468. }
  41469. _this._delayLoadingFunction(JSON.parse(data), _this);
  41470. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  41471. _this._delayInfo = [];
  41472. scene._removePendingData(_this);
  41473. var meshes = _this._meshes;
  41474. var numOfMeshes = meshes.length;
  41475. for (var index = 0; index < numOfMeshes; index++) {
  41476. _this._applyToMesh(meshes[index]);
  41477. }
  41478. if (onLoaded) {
  41479. onLoaded();
  41480. }
  41481. }, undefined, true);
  41482. };
  41483. /**
  41484. * Invert the geometry to move from a right handed system to a left handed one.
  41485. */
  41486. Geometry.prototype.toLeftHanded = function () {
  41487. // Flip faces
  41488. var tIndices = this.getIndices(false);
  41489. if (tIndices != null && tIndices.length > 0) {
  41490. for (var i = 0; i < tIndices.length; i += 3) {
  41491. var tTemp = tIndices[i + 0];
  41492. tIndices[i + 0] = tIndices[i + 2];
  41493. tIndices[i + 2] = tTemp;
  41494. }
  41495. this.setIndices(tIndices);
  41496. }
  41497. // Negate position.z
  41498. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  41499. if (tPositions != null && tPositions.length > 0) {
  41500. for (var i = 0; i < tPositions.length; i += 3) {
  41501. tPositions[i + 2] = -tPositions[i + 2];
  41502. }
  41503. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  41504. }
  41505. // Negate normal.z
  41506. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  41507. if (tNormals != null && tNormals.length > 0) {
  41508. for (var i = 0; i < tNormals.length; i += 3) {
  41509. tNormals[i + 2] = -tNormals[i + 2];
  41510. }
  41511. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  41512. }
  41513. };
  41514. // Cache
  41515. /** @hidden */
  41516. Geometry.prototype._resetPointsArrayCache = function () {
  41517. this._positions = null;
  41518. };
  41519. /** @hidden */
  41520. Geometry.prototype._generatePointsArray = function () {
  41521. if (this._positions) {
  41522. return true;
  41523. }
  41524. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  41525. if (!data || data.length === 0) {
  41526. return false;
  41527. }
  41528. this._positions = [];
  41529. for (var index = 0; index < data.length; index += 3) {
  41530. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  41531. }
  41532. return true;
  41533. };
  41534. /**
  41535. * Gets a value indicating if the geometry is disposed
  41536. * @returns true if the geometry was disposed
  41537. */
  41538. Geometry.prototype.isDisposed = function () {
  41539. return this._isDisposed;
  41540. };
  41541. Geometry.prototype._disposeVertexArrayObjects = function () {
  41542. if (this._vertexArrayObjects) {
  41543. for (var kind in this._vertexArrayObjects) {
  41544. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  41545. }
  41546. this._vertexArrayObjects = {};
  41547. }
  41548. };
  41549. /**
  41550. * Free all associated resources
  41551. */
  41552. Geometry.prototype.dispose = function () {
  41553. var meshes = this._meshes;
  41554. var numOfMeshes = meshes.length;
  41555. var index;
  41556. for (index = 0; index < numOfMeshes; index++) {
  41557. this.releaseForMesh(meshes[index]);
  41558. }
  41559. this._meshes = [];
  41560. this._disposeVertexArrayObjects();
  41561. for (var kind in this._vertexBuffers) {
  41562. this._vertexBuffers[kind].dispose();
  41563. }
  41564. this._vertexBuffers = {};
  41565. this._totalVertices = 0;
  41566. if (this._indexBuffer) {
  41567. this._engine._releaseBuffer(this._indexBuffer);
  41568. }
  41569. this._indexBuffer = null;
  41570. this._indices = [];
  41571. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  41572. this.delayLoadingFile = null;
  41573. this._delayLoadingFunction = null;
  41574. this._delayInfo = [];
  41575. this._boundingInfo = null;
  41576. this._scene.removeGeometry(this);
  41577. this._isDisposed = true;
  41578. };
  41579. /**
  41580. * Clone the current geometry into a new geometry
  41581. * @param id defines the unique ID of the new geometry
  41582. * @returns a new geometry object
  41583. */
  41584. Geometry.prototype.copy = function (id) {
  41585. var vertexData = new BABYLON.VertexData();
  41586. vertexData.indices = [];
  41587. var indices = this.getIndices();
  41588. if (indices) {
  41589. for (var index = 0; index < indices.length; index++) {
  41590. vertexData.indices.push(indices[index]);
  41591. }
  41592. }
  41593. var updatable = false;
  41594. var stopChecking = false;
  41595. var kind;
  41596. for (kind in this._vertexBuffers) {
  41597. // using slice() to make a copy of the array and not just reference it
  41598. var data = this.getVerticesData(kind);
  41599. if (data instanceof Float32Array) {
  41600. vertexData.set(new Float32Array(data), kind);
  41601. }
  41602. else {
  41603. vertexData.set(data.slice(0), kind);
  41604. }
  41605. if (!stopChecking) {
  41606. var vb = this.getVertexBuffer(kind);
  41607. if (vb) {
  41608. updatable = vb.isUpdatable();
  41609. stopChecking = !updatable;
  41610. }
  41611. }
  41612. }
  41613. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  41614. geometry.delayLoadState = this.delayLoadState;
  41615. geometry.delayLoadingFile = this.delayLoadingFile;
  41616. geometry._delayLoadingFunction = this._delayLoadingFunction;
  41617. for (kind in this._delayInfo) {
  41618. geometry._delayInfo = geometry._delayInfo || [];
  41619. geometry._delayInfo.push(kind);
  41620. }
  41621. // Bounding info
  41622. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  41623. return geometry;
  41624. };
  41625. /**
  41626. * Serialize the current geometry info (and not the vertices data) into a JSON object
  41627. * @return a JSON representation of the current geometry data (without the vertices data)
  41628. */
  41629. Geometry.prototype.serialize = function () {
  41630. var serializationObject = {};
  41631. serializationObject.id = this.id;
  41632. serializationObject.updatable = this._updatable;
  41633. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  41634. serializationObject.tags = BABYLON.Tags.GetTags(this);
  41635. }
  41636. return serializationObject;
  41637. };
  41638. Geometry.prototype.toNumberArray = function (origin) {
  41639. if (Array.isArray(origin)) {
  41640. return origin;
  41641. }
  41642. else {
  41643. return Array.prototype.slice.call(origin);
  41644. }
  41645. };
  41646. /**
  41647. * Serialize all vertices data into a JSON oject
  41648. * @returns a JSON representation of the current geometry data
  41649. */
  41650. Geometry.prototype.serializeVerticeData = function () {
  41651. var serializationObject = this.serialize();
  41652. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  41653. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  41654. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  41655. serializationObject.positions._updatable = true;
  41656. }
  41657. }
  41658. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  41659. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  41660. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  41661. serializationObject.normals._updatable = true;
  41662. }
  41663. }
  41664. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  41665. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  41666. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  41667. serializationObject.tangets._updatable = true;
  41668. }
  41669. }
  41670. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  41671. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  41672. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  41673. serializationObject.uvs._updatable = true;
  41674. }
  41675. }
  41676. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  41677. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  41678. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  41679. serializationObject.uv2s._updatable = true;
  41680. }
  41681. }
  41682. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  41683. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  41684. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  41685. serializationObject.uv3s._updatable = true;
  41686. }
  41687. }
  41688. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  41689. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  41690. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  41691. serializationObject.uv4s._updatable = true;
  41692. }
  41693. }
  41694. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  41695. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  41696. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  41697. serializationObject.uv5s._updatable = true;
  41698. }
  41699. }
  41700. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  41701. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  41702. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  41703. serializationObject.uv6s._updatable = true;
  41704. }
  41705. }
  41706. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  41707. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  41708. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  41709. serializationObject.colors._updatable = true;
  41710. }
  41711. }
  41712. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  41713. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  41714. serializationObject.matricesIndices._isExpanded = true;
  41715. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  41716. serializationObject.matricesIndices._updatable = true;
  41717. }
  41718. }
  41719. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  41720. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  41721. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  41722. serializationObject.matricesWeights._updatable = true;
  41723. }
  41724. }
  41725. serializationObject.indices = this.toNumberArray(this.getIndices());
  41726. return serializationObject;
  41727. };
  41728. // Statics
  41729. /**
  41730. * Extracts a clone of a mesh geometry
  41731. * @param mesh defines the source mesh
  41732. * @param id defines the unique ID of the new geometry object
  41733. * @returns the new geometry object
  41734. */
  41735. Geometry.ExtractFromMesh = function (mesh, id) {
  41736. var geometry = mesh._geometry;
  41737. if (!geometry) {
  41738. return null;
  41739. }
  41740. return geometry.copy(id);
  41741. };
  41742. /**
  41743. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  41744. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  41745. * Be aware Math.random() could cause collisions, but:
  41746. * "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"
  41747. * @returns a string containing a new GUID
  41748. */
  41749. Geometry.RandomId = function () {
  41750. return BABYLON.Tools.RandomId();
  41751. };
  41752. /** @hidden */
  41753. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  41754. var scene = mesh.getScene();
  41755. // Geometry
  41756. var geometryId = parsedGeometry.geometryId;
  41757. if (geometryId) {
  41758. var geometry = scene.getGeometryByID(geometryId);
  41759. if (geometry) {
  41760. geometry.applyToMesh(mesh);
  41761. }
  41762. }
  41763. else if (parsedGeometry instanceof ArrayBuffer) {
  41764. var binaryInfo = mesh._binaryInfo;
  41765. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  41766. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  41767. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  41768. }
  41769. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  41770. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  41771. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  41772. }
  41773. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  41774. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  41775. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  41776. }
  41777. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  41778. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  41779. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  41780. }
  41781. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  41782. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  41783. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  41784. }
  41785. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  41786. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  41787. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  41788. }
  41789. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  41790. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  41791. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  41792. }
  41793. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  41794. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  41795. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  41796. }
  41797. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  41798. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  41799. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  41800. }
  41801. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  41802. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  41803. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  41804. }
  41805. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  41806. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  41807. var floatIndices = [];
  41808. for (var i = 0; i < matricesIndicesData.length; i++) {
  41809. var index = matricesIndicesData[i];
  41810. floatIndices.push(index & 0x000000FF);
  41811. floatIndices.push((index & 0x0000FF00) >> 8);
  41812. floatIndices.push((index & 0x00FF0000) >> 16);
  41813. floatIndices.push(index >> 24);
  41814. }
  41815. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  41816. }
  41817. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  41818. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  41819. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  41820. }
  41821. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  41822. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  41823. mesh.setIndices(indicesData, null);
  41824. }
  41825. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  41826. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  41827. mesh.subMeshes = [];
  41828. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  41829. var materialIndex = subMeshesData[(i * 5) + 0];
  41830. var verticesStart = subMeshesData[(i * 5) + 1];
  41831. var verticesCount = subMeshesData[(i * 5) + 2];
  41832. var indexStart = subMeshesData[(i * 5) + 3];
  41833. var indexCount = subMeshesData[(i * 5) + 4];
  41834. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  41835. }
  41836. }
  41837. }
  41838. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  41839. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  41840. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  41841. if (parsedGeometry.tangents) {
  41842. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  41843. }
  41844. if (parsedGeometry.uvs) {
  41845. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  41846. }
  41847. if (parsedGeometry.uvs2) {
  41848. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  41849. }
  41850. if (parsedGeometry.uvs3) {
  41851. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  41852. }
  41853. if (parsedGeometry.uvs4) {
  41854. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  41855. }
  41856. if (parsedGeometry.uvs5) {
  41857. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  41858. }
  41859. if (parsedGeometry.uvs6) {
  41860. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  41861. }
  41862. if (parsedGeometry.colors) {
  41863. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  41864. }
  41865. if (parsedGeometry.matricesIndices) {
  41866. if (!parsedGeometry.matricesIndices._isExpanded) {
  41867. var floatIndices = [];
  41868. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  41869. var matricesIndex = parsedGeometry.matricesIndices[i];
  41870. floatIndices.push(matricesIndex & 0x000000FF);
  41871. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  41872. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  41873. floatIndices.push(matricesIndex >> 24);
  41874. }
  41875. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  41876. }
  41877. else {
  41878. delete parsedGeometry.matricesIndices._isExpanded;
  41879. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  41880. }
  41881. }
  41882. if (parsedGeometry.matricesIndicesExtra) {
  41883. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  41884. var floatIndices = [];
  41885. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  41886. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  41887. floatIndices.push(matricesIndex & 0x000000FF);
  41888. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  41889. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  41890. floatIndices.push(matricesIndex >> 24);
  41891. }
  41892. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  41893. }
  41894. else {
  41895. delete parsedGeometry.matricesIndices._isExpanded;
  41896. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  41897. }
  41898. }
  41899. if (parsedGeometry.matricesWeights) {
  41900. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  41901. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  41902. }
  41903. if (parsedGeometry.matricesWeightsExtra) {
  41904. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  41905. }
  41906. mesh.setIndices(parsedGeometry.indices, null);
  41907. }
  41908. // SubMeshes
  41909. if (parsedGeometry.subMeshes) {
  41910. mesh.subMeshes = [];
  41911. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  41912. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  41913. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  41914. }
  41915. }
  41916. // Flat shading
  41917. if (mesh._shouldGenerateFlatShading) {
  41918. mesh.convertToFlatShadedMesh();
  41919. delete mesh._shouldGenerateFlatShading;
  41920. }
  41921. // Update
  41922. mesh.computeWorldMatrix(true);
  41923. scene.onMeshImportedObservable.notifyObservers(mesh);
  41924. };
  41925. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  41926. var epsilon = 1e-3;
  41927. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  41928. return;
  41929. }
  41930. var noInfluenceBoneIndex = 0.0;
  41931. if (parsedGeometry.skeletonId > -1) {
  41932. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  41933. if (!skeleton) {
  41934. return;
  41935. }
  41936. noInfluenceBoneIndex = skeleton.bones.length;
  41937. }
  41938. else {
  41939. return;
  41940. }
  41941. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  41942. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  41943. var matricesWeights = parsedGeometry.matricesWeights;
  41944. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  41945. var influencers = parsedGeometry.numBoneInfluencer;
  41946. var size = matricesWeights.length;
  41947. for (var i = 0; i < size; i += 4) {
  41948. var weight = 0.0;
  41949. var firstZeroWeight = -1;
  41950. for (var j = 0; j < 4; j++) {
  41951. var w = matricesWeights[i + j];
  41952. weight += w;
  41953. if (w < epsilon && firstZeroWeight < 0) {
  41954. firstZeroWeight = j;
  41955. }
  41956. }
  41957. if (matricesWeightsExtra) {
  41958. for (var j = 0; j < 4; j++) {
  41959. var w = matricesWeightsExtra[i + j];
  41960. weight += w;
  41961. if (w < epsilon && firstZeroWeight < 0) {
  41962. firstZeroWeight = j + 4;
  41963. }
  41964. }
  41965. }
  41966. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  41967. firstZeroWeight = influencers - 1;
  41968. }
  41969. if (weight > epsilon) {
  41970. var mweight = 1.0 / weight;
  41971. for (var j = 0; j < 4; j++) {
  41972. matricesWeights[i + j] *= mweight;
  41973. }
  41974. if (matricesWeightsExtra) {
  41975. for (var j = 0; j < 4; j++) {
  41976. matricesWeightsExtra[i + j] *= mweight;
  41977. }
  41978. }
  41979. }
  41980. else {
  41981. if (firstZeroWeight >= 4) {
  41982. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  41983. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  41984. }
  41985. else {
  41986. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  41987. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  41988. }
  41989. }
  41990. }
  41991. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  41992. if (parsedGeometry.matricesWeightsExtra) {
  41993. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  41994. }
  41995. };
  41996. /**
  41997. * Create a new geometry from persisted data (Using .babylon file format)
  41998. * @param parsedVertexData defines the persisted data
  41999. * @param scene defines the hosting scene
  42000. * @param rootUrl defines the root url to use to load assets (like delayed data)
  42001. * @returns the new geometry object
  42002. */
  42003. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  42004. if (scene.getGeometryByID(parsedVertexData.id)) {
  42005. return null; // null since geometry could be something else than a box...
  42006. }
  42007. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  42008. if (BABYLON.Tags) {
  42009. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  42010. }
  42011. if (parsedVertexData.delayLoadingFile) {
  42012. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  42013. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  42014. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  42015. geometry._delayInfo = [];
  42016. if (parsedVertexData.hasUVs) {
  42017. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  42018. }
  42019. if (parsedVertexData.hasUVs2) {
  42020. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  42021. }
  42022. if (parsedVertexData.hasUVs3) {
  42023. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  42024. }
  42025. if (parsedVertexData.hasUVs4) {
  42026. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  42027. }
  42028. if (parsedVertexData.hasUVs5) {
  42029. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  42030. }
  42031. if (parsedVertexData.hasUVs6) {
  42032. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  42033. }
  42034. if (parsedVertexData.hasColors) {
  42035. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  42036. }
  42037. if (parsedVertexData.hasMatricesIndices) {
  42038. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  42039. }
  42040. if (parsedVertexData.hasMatricesWeights) {
  42041. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  42042. }
  42043. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  42044. }
  42045. else {
  42046. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  42047. }
  42048. scene.pushGeometry(geometry, true);
  42049. return geometry;
  42050. };
  42051. return Geometry;
  42052. }());
  42053. BABYLON.Geometry = Geometry;
  42054. // Primitives
  42055. /// Abstract class
  42056. /**
  42057. * Abstract class used to provide common services for all typed geometries
  42058. * @hidden
  42059. */
  42060. var _PrimitiveGeometry = /** @class */ (function (_super) {
  42061. __extends(_PrimitiveGeometry, _super);
  42062. /**
  42063. * Creates a new typed geometry
  42064. * @param id defines the unique ID of the geometry
  42065. * @param scene defines the hosting scene
  42066. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  42067. * @param mesh defines the hosting mesh (can be null)
  42068. */
  42069. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  42070. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  42071. if (mesh === void 0) { mesh = null; }
  42072. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  42073. _this._canBeRegenerated = _canBeRegenerated;
  42074. _this._beingRegenerated = true;
  42075. _this.regenerate();
  42076. _this._beingRegenerated = false;
  42077. return _this;
  42078. }
  42079. /**
  42080. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  42081. * @returns true if the geometry can be regenerated
  42082. */
  42083. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  42084. return this._canBeRegenerated;
  42085. };
  42086. /**
  42087. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  42088. */
  42089. _PrimitiveGeometry.prototype.regenerate = function () {
  42090. if (!this._canBeRegenerated) {
  42091. return;
  42092. }
  42093. this._beingRegenerated = true;
  42094. this.setAllVerticesData(this._regenerateVertexData(), false);
  42095. this._beingRegenerated = false;
  42096. };
  42097. /**
  42098. * Clone the geometry
  42099. * @param id defines the unique ID of the new geometry
  42100. * @returns the new geometry
  42101. */
  42102. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  42103. return _super.prototype.copy.call(this, id);
  42104. };
  42105. // overrides
  42106. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  42107. if (!this._beingRegenerated) {
  42108. return;
  42109. }
  42110. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  42111. };
  42112. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  42113. if (!this._beingRegenerated) {
  42114. return;
  42115. }
  42116. _super.prototype.setVerticesData.call(this, kind, data, false);
  42117. };
  42118. // to override
  42119. /** @hidden */
  42120. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  42121. throw new Error("Abstract method");
  42122. };
  42123. _PrimitiveGeometry.prototype.copy = function (id) {
  42124. throw new Error("Must be overriden in sub-classes.");
  42125. };
  42126. _PrimitiveGeometry.prototype.serialize = function () {
  42127. var serializationObject = _super.prototype.serialize.call(this);
  42128. serializationObject.canBeRegenerated = this.canBeRegenerated();
  42129. return serializationObject;
  42130. };
  42131. return _PrimitiveGeometry;
  42132. }(Geometry));
  42133. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  42134. /**
  42135. * Creates a ribbon geometry
  42136. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  42137. */
  42138. var RibbonGeometry = /** @class */ (function (_super) {
  42139. __extends(RibbonGeometry, _super);
  42140. /**
  42141. * Creates a ribbon geometry
  42142. * @param id defines the unique ID of the geometry
  42143. * @param scene defines the hosting scene
  42144. * @param pathArray defines the array of paths to use
  42145. * @param closeArray defines if the last path and the first path must be joined
  42146. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  42147. * @param offset defines the offset between points
  42148. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  42149. * @param mesh defines the hosting mesh (can be null)
  42150. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  42151. */
  42152. function RibbonGeometry(id, scene,
  42153. /**
  42154. * Defines the array of paths to use
  42155. */
  42156. pathArray,
  42157. /**
  42158. * Defines if the last and first points of each path in your pathArray must be joined
  42159. */
  42160. closeArray,
  42161. /**
  42162. * Defines if the last and first points of each path in your pathArray must be joined
  42163. */
  42164. closePath,
  42165. /**
  42166. * Defines the offset between points
  42167. */
  42168. offset, canBeRegenerated, mesh,
  42169. /**
  42170. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  42171. */
  42172. side) {
  42173. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  42174. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  42175. _this.pathArray = pathArray;
  42176. _this.closeArray = closeArray;
  42177. _this.closePath = closePath;
  42178. _this.offset = offset;
  42179. _this.side = side;
  42180. return _this;
  42181. }
  42182. /** @hidden */
  42183. RibbonGeometry.prototype._regenerateVertexData = function () {
  42184. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  42185. };
  42186. RibbonGeometry.prototype.copy = function (id) {
  42187. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  42188. };
  42189. return RibbonGeometry;
  42190. }(_PrimitiveGeometry));
  42191. BABYLON.RibbonGeometry = RibbonGeometry;
  42192. /**
  42193. * Creates a box geometry
  42194. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  42195. */
  42196. var BoxGeometry = /** @class */ (function (_super) {
  42197. __extends(BoxGeometry, _super);
  42198. /**
  42199. * Creates a box geometry
  42200. * @param id defines the unique ID of the geometry
  42201. * @param scene defines the hosting scene
  42202. * @param size defines the zise of the box (width, height and depth are the same)
  42203. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  42204. * @param mesh defines the hosting mesh (can be null)
  42205. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  42206. */
  42207. function BoxGeometry(id, scene,
  42208. /**
  42209. * Defines the zise of the box (width, height and depth are the same)
  42210. */
  42211. size, canBeRegenerated, mesh,
  42212. /**
  42213. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  42214. */
  42215. side) {
  42216. if (mesh === void 0) { mesh = null; }
  42217. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  42218. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  42219. _this.size = size;
  42220. _this.side = side;
  42221. return _this;
  42222. }
  42223. /** @hidden */
  42224. BoxGeometry.prototype._regenerateVertexData = function () {
  42225. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  42226. };
  42227. BoxGeometry.prototype.copy = function (id) {
  42228. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  42229. };
  42230. BoxGeometry.prototype.serialize = function () {
  42231. var serializationObject = _super.prototype.serialize.call(this);
  42232. serializationObject.size = this.size;
  42233. return serializationObject;
  42234. };
  42235. BoxGeometry.Parse = function (parsedBox, scene) {
  42236. if (scene.getGeometryByID(parsedBox.id)) {
  42237. return null; // null since geometry could be something else than a box...
  42238. }
  42239. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  42240. if (BABYLON.Tags) {
  42241. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  42242. }
  42243. scene.pushGeometry(box, true);
  42244. return box;
  42245. };
  42246. return BoxGeometry;
  42247. }(_PrimitiveGeometry));
  42248. BABYLON.BoxGeometry = BoxGeometry;
  42249. /**
  42250. * Creates a sphere geometry
  42251. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  42252. */
  42253. var SphereGeometry = /** @class */ (function (_super) {
  42254. __extends(SphereGeometry, _super);
  42255. /**
  42256. * Create a new sphere geometry
  42257. * @param id defines the unique ID of the geometry
  42258. * @param scene defines the hosting scene
  42259. * @param segments defines the number of segments to use to create the sphere
  42260. * @param diameter defines the diameter of the sphere
  42261. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  42262. * @param mesh defines the hosting mesh (can be null)
  42263. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  42264. */
  42265. function SphereGeometry(id, scene,
  42266. /**
  42267. * Defines the number of segments to use to create the sphere
  42268. */
  42269. segments,
  42270. /**
  42271. * Defines the diameter of the sphere
  42272. */
  42273. diameter, canBeRegenerated, mesh,
  42274. /**
  42275. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  42276. */
  42277. side) {
  42278. if (mesh === void 0) { mesh = null; }
  42279. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  42280. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  42281. _this.segments = segments;
  42282. _this.diameter = diameter;
  42283. _this.side = side;
  42284. return _this;
  42285. }
  42286. /** @hidden */
  42287. SphereGeometry.prototype._regenerateVertexData = function () {
  42288. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  42289. };
  42290. SphereGeometry.prototype.copy = function (id) {
  42291. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  42292. };
  42293. SphereGeometry.prototype.serialize = function () {
  42294. var serializationObject = _super.prototype.serialize.call(this);
  42295. serializationObject.segments = this.segments;
  42296. serializationObject.diameter = this.diameter;
  42297. return serializationObject;
  42298. };
  42299. SphereGeometry.Parse = function (parsedSphere, scene) {
  42300. if (scene.getGeometryByID(parsedSphere.id)) {
  42301. return null; // null since geometry could be something else than a sphere...
  42302. }
  42303. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  42304. if (BABYLON.Tags) {
  42305. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  42306. }
  42307. scene.pushGeometry(sphere, true);
  42308. return sphere;
  42309. };
  42310. return SphereGeometry;
  42311. }(_PrimitiveGeometry));
  42312. BABYLON.SphereGeometry = SphereGeometry;
  42313. /**
  42314. * Creates a disc geometry
  42315. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  42316. */
  42317. var DiscGeometry = /** @class */ (function (_super) {
  42318. __extends(DiscGeometry, _super);
  42319. /**
  42320. * Creates a new disc geometry
  42321. * @param id defines the unique ID of the geometry
  42322. * @param scene defines the hosting scene
  42323. * @param radius defines the radius of the disc
  42324. * @param tessellation defines the tesselation factor to apply to the disc
  42325. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  42326. * @param mesh defines the hosting mesh (can be null)
  42327. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  42328. */
  42329. function DiscGeometry(id, scene,
  42330. /**
  42331. * Defines the radius of the disc
  42332. */
  42333. radius,
  42334. /**
  42335. * Defines the tesselation factor to apply to the disc
  42336. */
  42337. tessellation, canBeRegenerated, mesh,
  42338. /**
  42339. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  42340. */
  42341. side) {
  42342. if (mesh === void 0) { mesh = null; }
  42343. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  42344. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  42345. _this.radius = radius;
  42346. _this.tessellation = tessellation;
  42347. _this.side = side;
  42348. return _this;
  42349. }
  42350. /** @hidden */
  42351. DiscGeometry.prototype._regenerateVertexData = function () {
  42352. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  42353. };
  42354. DiscGeometry.prototype.copy = function (id) {
  42355. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  42356. };
  42357. return DiscGeometry;
  42358. }(_PrimitiveGeometry));
  42359. BABYLON.DiscGeometry = DiscGeometry;
  42360. /**
  42361. * Creates a new cylinder geometry
  42362. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  42363. */
  42364. var CylinderGeometry = /** @class */ (function (_super) {
  42365. __extends(CylinderGeometry, _super);
  42366. /**
  42367. * Creates a new cylinder geometry
  42368. * @param id defines the unique ID of the geometry
  42369. * @param scene defines the hosting scene
  42370. * @param height defines the height of the cylinder
  42371. * @param diameterTop defines the diameter of the cylinder's top cap
  42372. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  42373. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  42374. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  42375. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  42376. * @param mesh defines the hosting mesh (can be null)
  42377. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  42378. */
  42379. function CylinderGeometry(id, scene,
  42380. /**
  42381. * Defines the height of the cylinder
  42382. */
  42383. height,
  42384. /**
  42385. * Defines the diameter of the cylinder's top cap
  42386. */
  42387. diameterTop,
  42388. /**
  42389. * Defines the diameter of the cylinder's bottom cap
  42390. */
  42391. diameterBottom,
  42392. /**
  42393. * Defines the tessellation factor to apply to the cylinder
  42394. */
  42395. tessellation,
  42396. /**
  42397. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  42398. */
  42399. subdivisions, canBeRegenerated, mesh,
  42400. /**
  42401. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  42402. */
  42403. side) {
  42404. if (subdivisions === void 0) { subdivisions = 1; }
  42405. if (mesh === void 0) { mesh = null; }
  42406. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  42407. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  42408. _this.height = height;
  42409. _this.diameterTop = diameterTop;
  42410. _this.diameterBottom = diameterBottom;
  42411. _this.tessellation = tessellation;
  42412. _this.subdivisions = subdivisions;
  42413. _this.side = side;
  42414. return _this;
  42415. }
  42416. /** @hidden */
  42417. CylinderGeometry.prototype._regenerateVertexData = function () {
  42418. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  42419. };
  42420. CylinderGeometry.prototype.copy = function (id) {
  42421. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  42422. };
  42423. CylinderGeometry.prototype.serialize = function () {
  42424. var serializationObject = _super.prototype.serialize.call(this);
  42425. serializationObject.height = this.height;
  42426. serializationObject.diameterTop = this.diameterTop;
  42427. serializationObject.diameterBottom = this.diameterBottom;
  42428. serializationObject.tessellation = this.tessellation;
  42429. return serializationObject;
  42430. };
  42431. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  42432. if (scene.getGeometryByID(parsedCylinder.id)) {
  42433. return null; // null since geometry could be something else than a cylinder...
  42434. }
  42435. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  42436. if (BABYLON.Tags) {
  42437. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  42438. }
  42439. scene.pushGeometry(cylinder, true);
  42440. return cylinder;
  42441. };
  42442. return CylinderGeometry;
  42443. }(_PrimitiveGeometry));
  42444. BABYLON.CylinderGeometry = CylinderGeometry;
  42445. /**
  42446. * Creates a new torus geometry
  42447. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  42448. */
  42449. var TorusGeometry = /** @class */ (function (_super) {
  42450. __extends(TorusGeometry, _super);
  42451. /**
  42452. * Creates a new torus geometry
  42453. * @param id defines the unique ID of the geometry
  42454. * @param scene defines the hosting scene
  42455. * @param diameter defines the diameter of the torus
  42456. * @param thickness defines the thickness of the torus (ie. internal diameter)
  42457. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  42458. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  42459. * @param mesh defines the hosting mesh (can be null)
  42460. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  42461. */
  42462. function TorusGeometry(id, scene,
  42463. /**
  42464. * Defines the diameter of the torus
  42465. */
  42466. diameter,
  42467. /**
  42468. * Defines the thickness of the torus (ie. internal diameter)
  42469. */
  42470. thickness,
  42471. /**
  42472. * Defines the tesselation factor to apply to the torus
  42473. */
  42474. tessellation, canBeRegenerated, mesh,
  42475. /**
  42476. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  42477. */
  42478. side) {
  42479. if (mesh === void 0) { mesh = null; }
  42480. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  42481. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  42482. _this.diameter = diameter;
  42483. _this.thickness = thickness;
  42484. _this.tessellation = tessellation;
  42485. _this.side = side;
  42486. return _this;
  42487. }
  42488. /** @hidden */
  42489. TorusGeometry.prototype._regenerateVertexData = function () {
  42490. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  42491. };
  42492. TorusGeometry.prototype.copy = function (id) {
  42493. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  42494. };
  42495. TorusGeometry.prototype.serialize = function () {
  42496. var serializationObject = _super.prototype.serialize.call(this);
  42497. serializationObject.diameter = this.diameter;
  42498. serializationObject.thickness = this.thickness;
  42499. serializationObject.tessellation = this.tessellation;
  42500. return serializationObject;
  42501. };
  42502. TorusGeometry.Parse = function (parsedTorus, scene) {
  42503. if (scene.getGeometryByID(parsedTorus.id)) {
  42504. return null; // null since geometry could be something else than a torus...
  42505. }
  42506. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  42507. if (BABYLON.Tags) {
  42508. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  42509. }
  42510. scene.pushGeometry(torus, true);
  42511. return torus;
  42512. };
  42513. return TorusGeometry;
  42514. }(_PrimitiveGeometry));
  42515. BABYLON.TorusGeometry = TorusGeometry;
  42516. /**
  42517. * Creates a new ground geometry
  42518. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  42519. */
  42520. var GroundGeometry = /** @class */ (function (_super) {
  42521. __extends(GroundGeometry, _super);
  42522. /**
  42523. * Creates a new ground geometry
  42524. * @param id defines the unique ID of the geometry
  42525. * @param scene defines the hosting scene
  42526. * @param width defines the width of the ground
  42527. * @param height defines the height of the ground
  42528. * @param subdivisions defines the subdivisions to apply to the ground
  42529. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  42530. * @param mesh defines the hosting mesh (can be null)
  42531. */
  42532. function GroundGeometry(id, scene,
  42533. /**
  42534. * Defines the width of the ground
  42535. */
  42536. width,
  42537. /**
  42538. * Defines the height of the ground
  42539. */
  42540. height,
  42541. /**
  42542. * Defines the subdivisions to apply to the ground
  42543. */
  42544. subdivisions, canBeRegenerated, mesh) {
  42545. if (mesh === void 0) { mesh = null; }
  42546. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  42547. _this.width = width;
  42548. _this.height = height;
  42549. _this.subdivisions = subdivisions;
  42550. return _this;
  42551. }
  42552. /** @hidden */
  42553. GroundGeometry.prototype._regenerateVertexData = function () {
  42554. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  42555. };
  42556. GroundGeometry.prototype.copy = function (id) {
  42557. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  42558. };
  42559. GroundGeometry.prototype.serialize = function () {
  42560. var serializationObject = _super.prototype.serialize.call(this);
  42561. serializationObject.width = this.width;
  42562. serializationObject.height = this.height;
  42563. serializationObject.subdivisions = this.subdivisions;
  42564. return serializationObject;
  42565. };
  42566. GroundGeometry.Parse = function (parsedGround, scene) {
  42567. if (scene.getGeometryByID(parsedGround.id)) {
  42568. return null; // null since geometry could be something else than a ground...
  42569. }
  42570. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  42571. if (BABYLON.Tags) {
  42572. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  42573. }
  42574. scene.pushGeometry(ground, true);
  42575. return ground;
  42576. };
  42577. return GroundGeometry;
  42578. }(_PrimitiveGeometry));
  42579. BABYLON.GroundGeometry = GroundGeometry;
  42580. /**
  42581. * Creates a tiled ground geometry
  42582. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  42583. */
  42584. var TiledGroundGeometry = /** @class */ (function (_super) {
  42585. __extends(TiledGroundGeometry, _super);
  42586. /**
  42587. * Creates a tiled ground geometry
  42588. * @param id defines the unique ID of the geometry
  42589. * @param scene defines the hosting scene
  42590. * @param xmin defines the minimum value on X axis
  42591. * @param zmin defines the minimum value on Z axis
  42592. * @param xmax defines the maximum value on X axis
  42593. * @param zmax defines the maximum value on Z axis
  42594. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  42595. * @param precision defines the precision to use when computing the tiles
  42596. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  42597. * @param mesh defines the hosting mesh (can be null)
  42598. */
  42599. function TiledGroundGeometry(id, scene,
  42600. /**
  42601. * Defines the minimum value on X axis
  42602. */
  42603. xmin,
  42604. /**
  42605. * Defines the minimum value on Z axis
  42606. */
  42607. zmin,
  42608. /**
  42609. * Defines the maximum value on X axis
  42610. */
  42611. xmax,
  42612. /**
  42613. * Defines the maximum value on Z axis
  42614. */
  42615. zmax,
  42616. /**
  42617. * Defines the subdivisions to apply to the ground
  42618. */
  42619. subdivisions,
  42620. /**
  42621. * Defines the precision to use when computing the tiles
  42622. */
  42623. precision, canBeRegenerated, mesh) {
  42624. if (mesh === void 0) { mesh = null; }
  42625. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  42626. _this.xmin = xmin;
  42627. _this.zmin = zmin;
  42628. _this.xmax = xmax;
  42629. _this.zmax = zmax;
  42630. _this.subdivisions = subdivisions;
  42631. _this.precision = precision;
  42632. return _this;
  42633. }
  42634. /** @hidden */
  42635. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  42636. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  42637. };
  42638. TiledGroundGeometry.prototype.copy = function (id) {
  42639. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  42640. };
  42641. return TiledGroundGeometry;
  42642. }(_PrimitiveGeometry));
  42643. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  42644. /**
  42645. * Creates a plane geometry
  42646. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  42647. */
  42648. var PlaneGeometry = /** @class */ (function (_super) {
  42649. __extends(PlaneGeometry, _super);
  42650. /**
  42651. * Creates a plane geometry
  42652. * @param id defines the unique ID of the geometry
  42653. * @param scene defines the hosting scene
  42654. * @param size defines the size of the plane (width === height)
  42655. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  42656. * @param mesh defines the hosting mesh (can be null)
  42657. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  42658. */
  42659. function PlaneGeometry(id, scene,
  42660. /**
  42661. * Defines the size of the plane (width === height)
  42662. */
  42663. size, canBeRegenerated, mesh,
  42664. /**
  42665. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  42666. */
  42667. side) {
  42668. if (mesh === void 0) { mesh = null; }
  42669. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  42670. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  42671. _this.size = size;
  42672. _this.side = side;
  42673. return _this;
  42674. }
  42675. /** @hidden */
  42676. PlaneGeometry.prototype._regenerateVertexData = function () {
  42677. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  42678. };
  42679. PlaneGeometry.prototype.copy = function (id) {
  42680. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  42681. };
  42682. PlaneGeometry.prototype.serialize = function () {
  42683. var serializationObject = _super.prototype.serialize.call(this);
  42684. serializationObject.size = this.size;
  42685. return serializationObject;
  42686. };
  42687. PlaneGeometry.Parse = function (parsedPlane, scene) {
  42688. if (scene.getGeometryByID(parsedPlane.id)) {
  42689. return null; // null since geometry could be something else than a ground...
  42690. }
  42691. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  42692. if (BABYLON.Tags) {
  42693. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  42694. }
  42695. scene.pushGeometry(plane, true);
  42696. return plane;
  42697. };
  42698. return PlaneGeometry;
  42699. }(_PrimitiveGeometry));
  42700. BABYLON.PlaneGeometry = PlaneGeometry;
  42701. /**
  42702. * Creates a torus knot geometry
  42703. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  42704. */
  42705. var TorusKnotGeometry = /** @class */ (function (_super) {
  42706. __extends(TorusKnotGeometry, _super);
  42707. /**
  42708. * Creates a torus knot geometry
  42709. * @param id defines the unique ID of the geometry
  42710. * @param scene defines the hosting scene
  42711. * @param radius defines the radius of the torus knot
  42712. * @param tube defines the thickness of the torus knot tube
  42713. * @param radialSegments defines the number of radial segments
  42714. * @param tubularSegments defines the number of tubular segments
  42715. * @param p defines the first number of windings
  42716. * @param q defines the second number of windings
  42717. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  42718. * @param mesh defines the hosting mesh (can be null)
  42719. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  42720. */
  42721. function TorusKnotGeometry(id, scene,
  42722. /**
  42723. * Defines the radius of the torus knot
  42724. */
  42725. radius,
  42726. /**
  42727. * Defines the thickness of the torus knot tube
  42728. */
  42729. tube,
  42730. /**
  42731. * Defines the number of radial segments
  42732. */
  42733. radialSegments,
  42734. /**
  42735. * Defines the number of tubular segments
  42736. */
  42737. tubularSegments,
  42738. /**
  42739. * Defines the first number of windings
  42740. */
  42741. p,
  42742. /**
  42743. * Defines the second number of windings
  42744. */
  42745. q, canBeRegenerated, mesh,
  42746. /**
  42747. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  42748. */
  42749. side) {
  42750. if (mesh === void 0) { mesh = null; }
  42751. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  42752. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  42753. _this.radius = radius;
  42754. _this.tube = tube;
  42755. _this.radialSegments = radialSegments;
  42756. _this.tubularSegments = tubularSegments;
  42757. _this.p = p;
  42758. _this.q = q;
  42759. _this.side = side;
  42760. return _this;
  42761. }
  42762. /** @hidden */
  42763. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  42764. 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 });
  42765. };
  42766. TorusKnotGeometry.prototype.copy = function (id) {
  42767. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  42768. };
  42769. TorusKnotGeometry.prototype.serialize = function () {
  42770. var serializationObject = _super.prototype.serialize.call(this);
  42771. serializationObject.radius = this.radius;
  42772. serializationObject.tube = this.tube;
  42773. serializationObject.radialSegments = this.radialSegments;
  42774. serializationObject.tubularSegments = this.tubularSegments;
  42775. serializationObject.p = this.p;
  42776. serializationObject.q = this.q;
  42777. return serializationObject;
  42778. };
  42779. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  42780. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  42781. return null; // null since geometry could be something else than a ground...
  42782. }
  42783. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  42784. if (BABYLON.Tags) {
  42785. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  42786. }
  42787. scene.pushGeometry(torusKnot, true);
  42788. return torusKnot;
  42789. };
  42790. return TorusKnotGeometry;
  42791. }(_PrimitiveGeometry));
  42792. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  42793. //}
  42794. })(BABYLON || (BABYLON = {}));
  42795. //# sourceMappingURL=babylon.geometry.js.map
  42796. var BABYLON;
  42797. (function (BABYLON) {
  42798. /**
  42799. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  42800. */
  42801. var PerformanceMonitor = /** @class */ (function () {
  42802. /**
  42803. * constructor
  42804. * @param frameSampleSize The number of samples required to saturate the sliding window
  42805. */
  42806. function PerformanceMonitor(frameSampleSize) {
  42807. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  42808. this._enabled = true;
  42809. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  42810. }
  42811. /**
  42812. * Samples current frame
  42813. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  42814. */
  42815. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  42816. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  42817. if (!this._enabled) {
  42818. return;
  42819. }
  42820. if (this._lastFrameTimeMs != null) {
  42821. var dt = timeMs - this._lastFrameTimeMs;
  42822. this._rollingFrameTime.add(dt);
  42823. }
  42824. this._lastFrameTimeMs = timeMs;
  42825. };
  42826. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  42827. /**
  42828. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  42829. */
  42830. get: function () {
  42831. return this._rollingFrameTime.average;
  42832. },
  42833. enumerable: true,
  42834. configurable: true
  42835. });
  42836. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  42837. /**
  42838. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  42839. */
  42840. get: function () {
  42841. return this._rollingFrameTime.variance;
  42842. },
  42843. enumerable: true,
  42844. configurable: true
  42845. });
  42846. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  42847. /**
  42848. * Returns the frame time of the most recent frame
  42849. */
  42850. get: function () {
  42851. return this._rollingFrameTime.history(0);
  42852. },
  42853. enumerable: true,
  42854. configurable: true
  42855. });
  42856. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  42857. /**
  42858. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  42859. */
  42860. get: function () {
  42861. return 1000.0 / this._rollingFrameTime.average;
  42862. },
  42863. enumerable: true,
  42864. configurable: true
  42865. });
  42866. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  42867. /**
  42868. * Returns the average framerate in frames per second using the most recent frame time
  42869. */
  42870. get: function () {
  42871. var history = this._rollingFrameTime.history(0);
  42872. if (history === 0) {
  42873. return 0;
  42874. }
  42875. return 1000.0 / history;
  42876. },
  42877. enumerable: true,
  42878. configurable: true
  42879. });
  42880. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  42881. /**
  42882. * Returns true if enough samples have been taken to completely fill the sliding window
  42883. */
  42884. get: function () {
  42885. return this._rollingFrameTime.isSaturated();
  42886. },
  42887. enumerable: true,
  42888. configurable: true
  42889. });
  42890. /**
  42891. * Enables contributions to the sliding window sample set
  42892. */
  42893. PerformanceMonitor.prototype.enable = function () {
  42894. this._enabled = true;
  42895. };
  42896. /**
  42897. * Disables contributions to the sliding window sample set
  42898. * Samples will not be interpolated over the disabled period
  42899. */
  42900. PerformanceMonitor.prototype.disable = function () {
  42901. this._enabled = false;
  42902. //clear last sample to avoid interpolating over the disabled period when next enabled
  42903. this._lastFrameTimeMs = null;
  42904. };
  42905. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  42906. /**
  42907. * Returns true if sampling is enabled
  42908. */
  42909. get: function () {
  42910. return this._enabled;
  42911. },
  42912. enumerable: true,
  42913. configurable: true
  42914. });
  42915. /**
  42916. * Resets performance monitor
  42917. */
  42918. PerformanceMonitor.prototype.reset = function () {
  42919. //clear last sample to avoid interpolating over the disabled period when next enabled
  42920. this._lastFrameTimeMs = null;
  42921. //wipe record
  42922. this._rollingFrameTime.reset();
  42923. };
  42924. return PerformanceMonitor;
  42925. }());
  42926. BABYLON.PerformanceMonitor = PerformanceMonitor;
  42927. /**
  42928. * RollingAverage
  42929. *
  42930. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  42931. */
  42932. var RollingAverage = /** @class */ (function () {
  42933. /**
  42934. * constructor
  42935. * @param length The number of samples required to saturate the sliding window
  42936. */
  42937. function RollingAverage(length) {
  42938. this._samples = new Array(length);
  42939. this.reset();
  42940. }
  42941. /**
  42942. * Adds a sample to the sample set
  42943. * @param v The sample value
  42944. */
  42945. RollingAverage.prototype.add = function (v) {
  42946. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  42947. var delta;
  42948. //we need to check if we've already wrapped round
  42949. if (this.isSaturated()) {
  42950. //remove bottom of stack from mean
  42951. var bottomValue = this._samples[this._pos];
  42952. delta = bottomValue - this.average;
  42953. this.average -= delta / (this._sampleCount - 1);
  42954. this._m2 -= delta * (bottomValue - this.average);
  42955. }
  42956. else {
  42957. this._sampleCount++;
  42958. }
  42959. //add new value to mean
  42960. delta = v - this.average;
  42961. this.average += delta / (this._sampleCount);
  42962. this._m2 += delta * (v - this.average);
  42963. //set the new variance
  42964. this.variance = this._m2 / (this._sampleCount - 1);
  42965. this._samples[this._pos] = v;
  42966. this._pos++;
  42967. this._pos %= this._samples.length; //positive wrap around
  42968. };
  42969. /**
  42970. * Returns previously added values or null if outside of history or outside the sliding window domain
  42971. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  42972. * @return Value previously recorded with add() or null if outside of range
  42973. */
  42974. RollingAverage.prototype.history = function (i) {
  42975. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  42976. return 0;
  42977. }
  42978. var i0 = this._wrapPosition(this._pos - 1.0);
  42979. return this._samples[this._wrapPosition(i0 - i)];
  42980. };
  42981. /**
  42982. * Returns true if enough samples have been taken to completely fill the sliding window
  42983. * @return true if sample-set saturated
  42984. */
  42985. RollingAverage.prototype.isSaturated = function () {
  42986. return this._sampleCount >= this._samples.length;
  42987. };
  42988. /**
  42989. * Resets the rolling average (equivalent to 0 samples taken so far)
  42990. */
  42991. RollingAverage.prototype.reset = function () {
  42992. this.average = 0;
  42993. this.variance = 0;
  42994. this._sampleCount = 0;
  42995. this._pos = 0;
  42996. this._m2 = 0;
  42997. };
  42998. /**
  42999. * Wraps a value around the sample range boundaries
  43000. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  43001. * @return Wrapped position in sample range
  43002. */
  43003. RollingAverage.prototype._wrapPosition = function (i) {
  43004. var max = this._samples.length;
  43005. return ((i % max) + max) % max;
  43006. };
  43007. return RollingAverage;
  43008. }());
  43009. BABYLON.RollingAverage = RollingAverage;
  43010. })(BABYLON || (BABYLON = {}));
  43011. //# sourceMappingURL=babylon.performanceMonitor.js.map
  43012. var BABYLON;
  43013. (function (BABYLON) {
  43014. /**
  43015. * "Static Class" containing the most commonly used helper while dealing with material for
  43016. * rendering purpose.
  43017. *
  43018. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  43019. *
  43020. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  43021. */
  43022. var MaterialHelper = /** @class */ (function () {
  43023. function MaterialHelper() {
  43024. }
  43025. /**
  43026. * Bind the current view position to an effect.
  43027. * @param effect The effect to be bound
  43028. * @param scene The scene the eyes position is used from
  43029. */
  43030. MaterialHelper.BindEyePosition = function (effect, scene) {
  43031. if (scene._forcedViewPosition) {
  43032. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  43033. return;
  43034. }
  43035. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  43036. };
  43037. /**
  43038. * Helps preparing the defines values about the UVs in used in the effect.
  43039. * UVs are shared as much as we can accross channels in the shaders.
  43040. * @param texture The texture we are preparing the UVs for
  43041. * @param defines The defines to update
  43042. * @param key The channel key "diffuse", "specular"... used in the shader
  43043. */
  43044. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  43045. defines._needUVs = true;
  43046. defines[key] = true;
  43047. if (texture.getTextureMatrix().isIdentityAs3x2()) {
  43048. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  43049. if (texture.coordinatesIndex === 0) {
  43050. defines["MAINUV1"] = true;
  43051. }
  43052. else {
  43053. defines["MAINUV2"] = true;
  43054. }
  43055. }
  43056. else {
  43057. defines[key + "DIRECTUV"] = 0;
  43058. }
  43059. };
  43060. /**
  43061. * Binds a texture matrix value to its corrsponding uniform
  43062. * @param texture The texture to bind the matrix for
  43063. * @param uniformBuffer The uniform buffer receivin the data
  43064. * @param key The channel key "diffuse", "specular"... used in the shader
  43065. */
  43066. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  43067. var matrix = texture.getTextureMatrix();
  43068. if (!matrix.isIdentityAs3x2()) {
  43069. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  43070. }
  43071. };
  43072. /**
  43073. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  43074. * @param mesh defines the current mesh
  43075. * @param scene defines the current scene
  43076. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  43077. * @param pointsCloud defines if point cloud rendering has to be turned on
  43078. * @param fogEnabled defines if fog has to be turned on
  43079. * @param alphaTest defines if alpha testing has to be turned on
  43080. * @param defines defines the current list of defines
  43081. */
  43082. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  43083. if (defines._areMiscDirty) {
  43084. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  43085. defines["POINTSIZE"] = pointsCloud;
  43086. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  43087. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  43088. defines["ALPHATEST"] = alphaTest;
  43089. }
  43090. };
  43091. /**
  43092. * Helper used to prepare the list of defines associated with frame values for shader compilation
  43093. * @param scene defines the current scene
  43094. * @param engine defines the current engine
  43095. * @param defines specifies the list of active defines
  43096. * @param useInstances defines if instances have to be turned on
  43097. * @param useClipPlane defines if clip plane have to be turned on
  43098. */
  43099. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  43100. if (useClipPlane === void 0) { useClipPlane = null; }
  43101. var changed = false;
  43102. var useClipPlane1 = false;
  43103. var useClipPlane2 = false;
  43104. var useClipPlane3 = false;
  43105. var useClipPlane4 = false;
  43106. useClipPlane1 = useClipPlane == null ? (scene.clipPlane !== undefined && scene.clipPlane !== null) : useClipPlane;
  43107. useClipPlane2 = useClipPlane == null ? (scene.clipPlane2 !== undefined && scene.clipPlane2 !== null) : useClipPlane;
  43108. useClipPlane3 = useClipPlane == null ? (scene.clipPlane3 !== undefined && scene.clipPlane3 !== null) : useClipPlane;
  43109. useClipPlane4 = useClipPlane == null ? (scene.clipPlane4 !== undefined && scene.clipPlane4 !== null) : useClipPlane;
  43110. if (defines["CLIPPLANE"] !== useClipPlane1) {
  43111. defines["CLIPPLANE"] = useClipPlane1;
  43112. changed = true;
  43113. }
  43114. if (defines["CLIPPLANE2"] !== useClipPlane2) {
  43115. defines["CLIPPLANE2"] = useClipPlane2;
  43116. changed = true;
  43117. }
  43118. if (defines["CLIPPLANE3"] !== useClipPlane3) {
  43119. defines["CLIPPLANE3"] = useClipPlane3;
  43120. changed = true;
  43121. }
  43122. if (defines["CLIPPLANE4"] !== useClipPlane4) {
  43123. defines["CLIPPLANE4"] = useClipPlane4;
  43124. changed = true;
  43125. }
  43126. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  43127. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  43128. changed = true;
  43129. }
  43130. if (defines["INSTANCES"] !== useInstances) {
  43131. defines["INSTANCES"] = useInstances;
  43132. changed = true;
  43133. }
  43134. if (changed) {
  43135. defines.markAsUnprocessed();
  43136. }
  43137. };
  43138. /**
  43139. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  43140. * @param mesh The mesh containing the geometry data we will draw
  43141. * @param defines The defines to update
  43142. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  43143. * @param useBones Precise whether bones should be used or not (override mesh info)
  43144. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  43145. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  43146. * @returns false if defines are considered not dirty and have not been checked
  43147. */
  43148. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  43149. if (useMorphTargets === void 0) { useMorphTargets = false; }
  43150. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  43151. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  43152. return false;
  43153. }
  43154. defines._normals = defines._needNormals;
  43155. defines._uvs = defines._needUVs;
  43156. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  43157. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  43158. defines["TANGENT"] = true;
  43159. }
  43160. if (defines._needUVs) {
  43161. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  43162. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  43163. }
  43164. else {
  43165. defines["UV1"] = false;
  43166. defines["UV2"] = false;
  43167. }
  43168. if (useVertexColor) {
  43169. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  43170. defines["VERTEXCOLOR"] = hasVertexColors;
  43171. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  43172. }
  43173. if (useBones) {
  43174. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  43175. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  43176. var materialSupportsBoneTexture = defines["BONETEXTURE"] !== undefined;
  43177. if (mesh.skeleton.isUsingTextureForMatrices && materialSupportsBoneTexture) {
  43178. defines["BONETEXTURE"] = true;
  43179. }
  43180. else {
  43181. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  43182. defines["BONETEXTURE"] = materialSupportsBoneTexture ? false : undefined;
  43183. }
  43184. }
  43185. else {
  43186. defines["NUM_BONE_INFLUENCERS"] = 0;
  43187. defines["BonesPerMesh"] = 0;
  43188. }
  43189. }
  43190. if (useMorphTargets) {
  43191. var manager = mesh.morphTargetManager;
  43192. if (manager) {
  43193. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  43194. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  43195. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  43196. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  43197. }
  43198. else {
  43199. defines["MORPHTARGETS_TANGENT"] = false;
  43200. defines["MORPHTARGETS_NORMAL"] = false;
  43201. defines["MORPHTARGETS"] = false;
  43202. defines["NUM_MORPH_INFLUENCERS"] = 0;
  43203. }
  43204. }
  43205. return true;
  43206. };
  43207. /**
  43208. * Prepares the defines related to the light information passed in parameter
  43209. * @param scene The scene we are intending to draw
  43210. * @param mesh The mesh the effect is compiling for
  43211. * @param defines The defines to update
  43212. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  43213. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  43214. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  43215. * @returns true if normals will be required for the rest of the effect
  43216. */
  43217. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  43218. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  43219. if (disableLighting === void 0) { disableLighting = false; }
  43220. if (!defines._areLightsDirty) {
  43221. return defines._needNormals;
  43222. }
  43223. var lightIndex = 0;
  43224. var needNormals = false;
  43225. var needRebuild = false;
  43226. var lightmapMode = false;
  43227. var shadowEnabled = false;
  43228. var specularEnabled = false;
  43229. if (scene.lightsEnabled && !disableLighting) {
  43230. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  43231. var light = _a[_i];
  43232. needNormals = true;
  43233. if (defines["LIGHT" + lightIndex] === undefined) {
  43234. needRebuild = true;
  43235. }
  43236. defines["LIGHT" + lightIndex] = true;
  43237. defines["SPOTLIGHT" + lightIndex] = false;
  43238. defines["HEMILIGHT" + lightIndex] = false;
  43239. defines["POINTLIGHT" + lightIndex] = false;
  43240. defines["DIRLIGHT" + lightIndex] = false;
  43241. light.prepareLightSpecificDefines(defines, lightIndex);
  43242. // FallOff.
  43243. defines["LIGHT_FALLOFF_PHYSICAL" + lightIndex] = false;
  43244. defines["LIGHT_FALLOFF_GLTF" + lightIndex] = false;
  43245. defines["LIGHT_FALLOFF_STANDARD" + lightIndex] = false;
  43246. switch (light.falloffType) {
  43247. case BABYLON.Light.FALLOFF_GLTF:
  43248. defines["LIGHT_FALLOFF_GLTF" + lightIndex] = true;
  43249. break;
  43250. case BABYLON.Light.FALLOFF_PHYSICAL:
  43251. defines["LIGHT_FALLOFF_PHYSICAL" + lightIndex] = true;
  43252. break;
  43253. case BABYLON.Light.FALLOFF_STANDARD:
  43254. defines["LIGHT_FALLOFF_STANDARD" + lightIndex] = true;
  43255. break;
  43256. }
  43257. // Specular
  43258. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  43259. specularEnabled = true;
  43260. }
  43261. // Shadows
  43262. defines["SHADOW" + lightIndex] = false;
  43263. defines["SHADOWPCF" + lightIndex] = false;
  43264. defines["SHADOWPCSS" + lightIndex] = false;
  43265. defines["SHADOWPOISSON" + lightIndex] = false;
  43266. defines["SHADOWESM" + lightIndex] = false;
  43267. defines["SHADOWCUBE" + lightIndex] = false;
  43268. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  43269. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  43270. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  43271. var shadowGenerator = light.getShadowGenerator();
  43272. if (shadowGenerator) {
  43273. var shadowMap = shadowGenerator.getShadowMap();
  43274. if (shadowMap) {
  43275. if (shadowMap.renderList && shadowMap.renderList.length > 0) {
  43276. shadowEnabled = true;
  43277. shadowGenerator.prepareDefines(defines, lightIndex);
  43278. }
  43279. }
  43280. }
  43281. }
  43282. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  43283. lightmapMode = true;
  43284. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  43285. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  43286. }
  43287. else {
  43288. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  43289. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  43290. }
  43291. lightIndex++;
  43292. if (lightIndex === maxSimultaneousLights) {
  43293. break;
  43294. }
  43295. }
  43296. }
  43297. defines["SPECULARTERM"] = specularEnabled;
  43298. defines["SHADOWS"] = shadowEnabled;
  43299. // Resetting all other lights if any
  43300. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  43301. if (defines["LIGHT" + index] !== undefined) {
  43302. defines["LIGHT" + index] = false;
  43303. defines["HEMILIGHT" + lightIndex] = false;
  43304. defines["POINTLIGHT" + lightIndex] = false;
  43305. defines["DIRLIGHT" + lightIndex] = false;
  43306. defines["SPOTLIGHT" + lightIndex] = false;
  43307. defines["SHADOW" + lightIndex] = false;
  43308. }
  43309. }
  43310. var caps = scene.getEngine().getCaps();
  43311. if (defines["SHADOWFLOAT"] === undefined) {
  43312. needRebuild = true;
  43313. }
  43314. defines["SHADOWFLOAT"] = shadowEnabled &&
  43315. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  43316. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  43317. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  43318. if (needRebuild) {
  43319. defines.rebuild();
  43320. }
  43321. return needNormals;
  43322. };
  43323. /**
  43324. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  43325. * that won t be acctive due to defines being turned off.
  43326. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  43327. * @param samplersList The samplers list
  43328. * @param defines The defines helping in the list generation
  43329. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  43330. */
  43331. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  43332. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  43333. var uniformsList;
  43334. var uniformBuffersList = null;
  43335. if (uniformsListOrOptions.uniformsNames) {
  43336. var options = uniformsListOrOptions;
  43337. uniformsList = options.uniformsNames;
  43338. uniformBuffersList = options.uniformBuffersNames;
  43339. samplersList = options.samplers;
  43340. defines = options.defines;
  43341. maxSimultaneousLights = options.maxSimultaneousLights;
  43342. }
  43343. else {
  43344. uniformsList = uniformsListOrOptions;
  43345. if (!samplersList) {
  43346. samplersList = [];
  43347. }
  43348. }
  43349. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  43350. if (!defines["LIGHT" + lightIndex]) {
  43351. break;
  43352. }
  43353. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightFalloff" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  43354. if (uniformBuffersList) {
  43355. uniformBuffersList.push("Light" + lightIndex);
  43356. }
  43357. samplersList.push("shadowSampler" + lightIndex);
  43358. samplersList.push("depthSampler" + lightIndex);
  43359. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  43360. samplersList.push("projectionLightSampler" + lightIndex);
  43361. uniformsList.push("textureProjectionMatrix" + lightIndex);
  43362. }
  43363. }
  43364. if (defines["NUM_MORPH_INFLUENCERS"]) {
  43365. uniformsList.push("morphTargetInfluences");
  43366. }
  43367. };
  43368. /**
  43369. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  43370. * @param defines The defines to update while falling back
  43371. * @param fallbacks The authorized effect fallbacks
  43372. * @param maxSimultaneousLights The maximum number of lights allowed
  43373. * @param rank the current rank of the Effect
  43374. * @returns The newly affected rank
  43375. */
  43376. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  43377. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  43378. if (rank === void 0) { rank = 0; }
  43379. var lightFallbackRank = 0;
  43380. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  43381. if (!defines["LIGHT" + lightIndex]) {
  43382. break;
  43383. }
  43384. if (lightIndex > 0) {
  43385. lightFallbackRank = rank + lightIndex;
  43386. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  43387. }
  43388. if (!defines["SHADOWS"]) {
  43389. if (defines["SHADOW" + lightIndex]) {
  43390. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  43391. }
  43392. if (defines["SHADOWPCF" + lightIndex]) {
  43393. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  43394. }
  43395. if (defines["SHADOWPCSS" + lightIndex]) {
  43396. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  43397. }
  43398. if (defines["SHADOWPOISSON" + lightIndex]) {
  43399. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  43400. }
  43401. if (defines["SHADOWESM" + lightIndex]) {
  43402. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  43403. }
  43404. }
  43405. }
  43406. return lightFallbackRank++;
  43407. };
  43408. /**
  43409. * Prepares the list of attributes required for morph targets according to the effect defines.
  43410. * @param attribs The current list of supported attribs
  43411. * @param mesh The mesh to prepare the morph targets attributes for
  43412. * @param defines The current Defines of the effect
  43413. */
  43414. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  43415. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  43416. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  43417. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  43418. var manager = mesh.morphTargetManager;
  43419. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  43420. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  43421. for (var index = 0; index < influencers; index++) {
  43422. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  43423. if (normal) {
  43424. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  43425. }
  43426. if (tangent) {
  43427. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  43428. }
  43429. if (attribs.length > maxAttributesCount) {
  43430. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  43431. }
  43432. }
  43433. }
  43434. };
  43435. /**
  43436. * Prepares the list of attributes required for bones according to the effect defines.
  43437. * @param attribs The current list of supported attribs
  43438. * @param mesh The mesh to prepare the bones attributes for
  43439. * @param defines The current Defines of the effect
  43440. * @param fallbacks The current efffect fallback strategy
  43441. */
  43442. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  43443. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  43444. fallbacks.addCPUSkinningFallback(0, mesh);
  43445. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  43446. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  43447. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  43448. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  43449. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  43450. }
  43451. }
  43452. };
  43453. /**
  43454. * Prepares the list of attributes required for instances according to the effect defines.
  43455. * @param attribs The current list of supported attribs
  43456. * @param defines The current Defines of the effect
  43457. */
  43458. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  43459. if (defines["INSTANCES"]) {
  43460. attribs.push("world0");
  43461. attribs.push("world1");
  43462. attribs.push("world2");
  43463. attribs.push("world3");
  43464. }
  43465. };
  43466. /**
  43467. * Binds the light shadow information to the effect for the given mesh.
  43468. * @param light The light containing the generator
  43469. * @param scene The scene the lights belongs to
  43470. * @param mesh The mesh we are binding the information to render
  43471. * @param lightIndex The light index in the effect used to render the mesh
  43472. * @param effect The effect we are binding the data to
  43473. */
  43474. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  43475. if (light.shadowEnabled && mesh.receiveShadows) {
  43476. var shadowGenerator = light.getShadowGenerator();
  43477. if (shadowGenerator) {
  43478. shadowGenerator.bindShadowLight(lightIndex, effect);
  43479. }
  43480. }
  43481. };
  43482. /**
  43483. * Binds the light information to the effect.
  43484. * @param light The light containing the generator
  43485. * @param effect The effect we are binding the data to
  43486. * @param lightIndex The light index in the effect used to render
  43487. */
  43488. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  43489. light.transferToEffect(effect, lightIndex + "");
  43490. };
  43491. /**
  43492. * Binds the lights information from the scene to the effect for the given mesh.
  43493. * @param scene The scene the lights belongs to
  43494. * @param mesh The mesh we are binding the information to render
  43495. * @param effect The effect we are binding the data to
  43496. * @param defines The generated defines for the effect
  43497. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  43498. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  43499. */
  43500. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  43501. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  43502. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  43503. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  43504. for (var i = 0; i < len; i++) {
  43505. var light = mesh._lightSources[i];
  43506. var iAsString = i.toString();
  43507. var scaledIntensity = light.getScaledIntensity();
  43508. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  43509. MaterialHelper.BindLightProperties(light, effect, i);
  43510. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  43511. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  43512. if (defines["SPECULARTERM"]) {
  43513. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  43514. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  43515. }
  43516. // Shadows
  43517. if (scene.shadowsEnabled) {
  43518. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  43519. }
  43520. light._uniformBuffer.update();
  43521. }
  43522. };
  43523. /**
  43524. * Binds the fog information from the scene to the effect for the given mesh.
  43525. * @param scene The scene the lights belongs to
  43526. * @param mesh The mesh we are binding the information to render
  43527. * @param effect The effect we are binding the data to
  43528. * @param linearSpace Defines if the fog effect is applied in linear space
  43529. */
  43530. MaterialHelper.BindFogParameters = function (scene, mesh, effect, linearSpace) {
  43531. if (linearSpace === void 0) { linearSpace = false; }
  43532. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  43533. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  43534. // Convert fog color to linear space if used in a linear space computed shader.
  43535. if (linearSpace) {
  43536. scene.fogColor.toLinearSpaceToRef(this._tempFogColor);
  43537. effect.setColor3("vFogColor", this._tempFogColor);
  43538. }
  43539. else {
  43540. effect.setColor3("vFogColor", scene.fogColor);
  43541. }
  43542. }
  43543. };
  43544. /**
  43545. * Binds the bones information from the mesh to the effect.
  43546. * @param mesh The mesh we are binding the information to render
  43547. * @param effect The effect we are binding the data to
  43548. */
  43549. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  43550. if (!effect || !mesh) {
  43551. return;
  43552. }
  43553. if (mesh.computeBonesUsingShaders && effect._bonesComputationForcedToCPU) {
  43554. mesh.computeBonesUsingShaders = false;
  43555. }
  43556. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  43557. var skeleton = mesh.skeleton;
  43558. if (skeleton.isUsingTextureForMatrices && effect.getUniformIndex("boneTextureWidth") > -1) {
  43559. var boneTexture = skeleton.getTransformMatrixTexture();
  43560. effect.setTexture("boneSampler", boneTexture);
  43561. effect.setFloat("boneTextureWidth", 4.0 * (skeleton.bones.length + 1));
  43562. }
  43563. else {
  43564. var matrices = skeleton.getTransformMatrices(mesh);
  43565. if (matrices) {
  43566. effect.setMatrices("mBones", matrices);
  43567. }
  43568. }
  43569. }
  43570. };
  43571. /**
  43572. * Binds the morph targets information from the mesh to the effect.
  43573. * @param abstractMesh The mesh we are binding the information to render
  43574. * @param effect The effect we are binding the data to
  43575. */
  43576. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  43577. var manager = abstractMesh.morphTargetManager;
  43578. if (!abstractMesh || !manager) {
  43579. return;
  43580. }
  43581. effect.setFloatArray("morphTargetInfluences", manager.influences);
  43582. };
  43583. /**
  43584. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  43585. * @param defines The generated defines used in the effect
  43586. * @param effect The effect we are binding the data to
  43587. * @param scene The scene we are willing to render with logarithmic scale for
  43588. */
  43589. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  43590. if (defines["LOGARITHMICDEPTH"]) {
  43591. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  43592. }
  43593. };
  43594. /**
  43595. * Binds the clip plane information from the scene to the effect.
  43596. * @param scene The scene the clip plane information are extracted from
  43597. * @param effect The effect we are binding the data to
  43598. */
  43599. MaterialHelper.BindClipPlane = function (effect, scene) {
  43600. if (scene.clipPlane) {
  43601. var clipPlane = scene.clipPlane;
  43602. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  43603. }
  43604. if (scene.clipPlane2) {
  43605. var clipPlane = scene.clipPlane2;
  43606. effect.setFloat4("vClipPlane2", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  43607. }
  43608. if (scene.clipPlane3) {
  43609. var clipPlane = scene.clipPlane3;
  43610. effect.setFloat4("vClipPlane3", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  43611. }
  43612. if (scene.clipPlane4) {
  43613. var clipPlane = scene.clipPlane4;
  43614. effect.setFloat4("vClipPlane4", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  43615. }
  43616. };
  43617. MaterialHelper._tempFogColor = BABYLON.Color3.Black();
  43618. return MaterialHelper;
  43619. }());
  43620. BABYLON.MaterialHelper = MaterialHelper;
  43621. })(BABYLON || (BABYLON = {}));
  43622. //# sourceMappingURL=babylon.materialHelper.js.map
  43623. var BABYLON;
  43624. (function (BABYLON) {
  43625. /**
  43626. * Base class of materials working in push mode in babylon JS
  43627. * @hidden
  43628. */
  43629. var PushMaterial = /** @class */ (function (_super) {
  43630. __extends(PushMaterial, _super);
  43631. function PushMaterial(name, scene) {
  43632. var _this = _super.call(this, name, scene) || this;
  43633. _this._normalMatrix = new BABYLON.Matrix();
  43634. /**
  43635. * Gets or sets a boolean indicating that the material is allowed to do shader hot swapping.
  43636. * This means that the material can keep using a previous shader while a new one is being compiled.
  43637. * This is mostly used when shader parallel compilation is supported (true by default)
  43638. */
  43639. _this.allowShaderHotSwapping = true;
  43640. _this._storeEffectOnSubMeshes = true;
  43641. return _this;
  43642. }
  43643. PushMaterial.prototype.getEffect = function () {
  43644. return this._activeEffect;
  43645. };
  43646. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  43647. if (!mesh) {
  43648. return false;
  43649. }
  43650. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  43651. return true;
  43652. }
  43653. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  43654. };
  43655. /**
  43656. * Binds the given world matrix to the active effect
  43657. *
  43658. * @param world the matrix to bind
  43659. */
  43660. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  43661. this._activeEffect.setMatrix("world", world);
  43662. };
  43663. /**
  43664. * Binds the given normal matrix to the active effect
  43665. *
  43666. * @param normalMatrix the matrix to bind
  43667. */
  43668. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  43669. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  43670. };
  43671. PushMaterial.prototype.bind = function (world, mesh) {
  43672. if (!mesh) {
  43673. return;
  43674. }
  43675. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  43676. };
  43677. PushMaterial.prototype._afterBind = function (mesh, effect) {
  43678. if (effect === void 0) { effect = null; }
  43679. _super.prototype._afterBind.call(this, mesh);
  43680. this.getScene()._cachedEffect = effect;
  43681. };
  43682. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  43683. if (visibility === void 0) { visibility = 1; }
  43684. return scene.isCachedMaterialInvalid(this, effect, visibility);
  43685. };
  43686. return PushMaterial;
  43687. }(BABYLON.Material));
  43688. BABYLON.PushMaterial = PushMaterial;
  43689. })(BABYLON || (BABYLON = {}));
  43690. //# sourceMappingURL=babylon.pushMaterial.js.map
  43691. var BABYLON;
  43692. (function (BABYLON) {
  43693. /** @hidden */
  43694. var StandardMaterialDefines = /** @class */ (function (_super) {
  43695. __extends(StandardMaterialDefines, _super);
  43696. function StandardMaterialDefines() {
  43697. var _this = _super.call(this) || this;
  43698. _this.MAINUV1 = false;
  43699. _this.MAINUV2 = false;
  43700. _this.DIFFUSE = false;
  43701. _this.DIFFUSEDIRECTUV = 0;
  43702. _this.AMBIENT = false;
  43703. _this.AMBIENTDIRECTUV = 0;
  43704. _this.OPACITY = false;
  43705. _this.OPACITYDIRECTUV = 0;
  43706. _this.OPACITYRGB = false;
  43707. _this.REFLECTION = false;
  43708. _this.EMISSIVE = false;
  43709. _this.EMISSIVEDIRECTUV = 0;
  43710. _this.SPECULAR = false;
  43711. _this.SPECULARDIRECTUV = 0;
  43712. _this.BUMP = false;
  43713. _this.BUMPDIRECTUV = 0;
  43714. _this.PARALLAX = false;
  43715. _this.PARALLAXOCCLUSION = false;
  43716. _this.SPECULAROVERALPHA = false;
  43717. _this.CLIPPLANE = false;
  43718. _this.CLIPPLANE2 = false;
  43719. _this.CLIPPLANE3 = false;
  43720. _this.CLIPPLANE4 = false;
  43721. _this.ALPHATEST = false;
  43722. _this.DEPTHPREPASS = false;
  43723. _this.ALPHAFROMDIFFUSE = false;
  43724. _this.POINTSIZE = false;
  43725. _this.FOG = false;
  43726. _this.SPECULARTERM = false;
  43727. _this.DIFFUSEFRESNEL = false;
  43728. _this.OPACITYFRESNEL = false;
  43729. _this.REFLECTIONFRESNEL = false;
  43730. _this.REFRACTIONFRESNEL = false;
  43731. _this.EMISSIVEFRESNEL = false;
  43732. _this.FRESNEL = false;
  43733. _this.NORMAL = false;
  43734. _this.UV1 = false;
  43735. _this.UV2 = false;
  43736. _this.VERTEXCOLOR = false;
  43737. _this.VERTEXALPHA = false;
  43738. _this.NUM_BONE_INFLUENCERS = 0;
  43739. _this.BonesPerMesh = 0;
  43740. _this.BONETEXTURE = false;
  43741. _this.INSTANCES = false;
  43742. _this.GLOSSINESS = false;
  43743. _this.ROUGHNESS = false;
  43744. _this.EMISSIVEASILLUMINATION = false;
  43745. _this.LINKEMISSIVEWITHDIFFUSE = false;
  43746. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  43747. _this.LIGHTMAP = false;
  43748. _this.LIGHTMAPDIRECTUV = 0;
  43749. _this.OBJECTSPACE_NORMALMAP = false;
  43750. _this.USELIGHTMAPASSHADOWMAP = false;
  43751. _this.REFLECTIONMAP_3D = false;
  43752. _this.REFLECTIONMAP_SPHERICAL = false;
  43753. _this.REFLECTIONMAP_PLANAR = false;
  43754. _this.REFLECTIONMAP_CUBIC = false;
  43755. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  43756. _this.REFLECTIONMAP_PROJECTION = false;
  43757. _this.REFLECTIONMAP_SKYBOX = false;
  43758. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  43759. _this.REFLECTIONMAP_EXPLICIT = false;
  43760. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  43761. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  43762. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  43763. _this.INVERTCUBICMAP = false;
  43764. _this.LOGARITHMICDEPTH = false;
  43765. _this.REFRACTION = false;
  43766. _this.REFRACTIONMAP_3D = false;
  43767. _this.REFLECTIONOVERALPHA = false;
  43768. _this.TWOSIDEDLIGHTING = false;
  43769. _this.SHADOWFLOAT = false;
  43770. _this.MORPHTARGETS = false;
  43771. _this.MORPHTARGETS_NORMAL = false;
  43772. _this.MORPHTARGETS_TANGENT = false;
  43773. _this.NUM_MORPH_INFLUENCERS = 0;
  43774. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  43775. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  43776. _this.IMAGEPROCESSING = false;
  43777. _this.VIGNETTE = false;
  43778. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  43779. _this.VIGNETTEBLENDMODEOPAQUE = false;
  43780. _this.TONEMAPPING = false;
  43781. _this.TONEMAPPING_ACES = false;
  43782. _this.CONTRAST = false;
  43783. _this.COLORCURVES = false;
  43784. _this.COLORGRADING = false;
  43785. _this.COLORGRADING3D = false;
  43786. _this.SAMPLER3DGREENDEPTH = false;
  43787. _this.SAMPLER3DBGRMAP = false;
  43788. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  43789. /**
  43790. * If the reflection texture on this material is in linear color space
  43791. * @hidden
  43792. */
  43793. _this.IS_REFLECTION_LINEAR = false;
  43794. /**
  43795. * If the refraction texture on this material is in linear color space
  43796. * @hidden
  43797. */
  43798. _this.IS_REFRACTION_LINEAR = false;
  43799. _this.EXPOSURE = false;
  43800. _this.rebuild();
  43801. return _this;
  43802. }
  43803. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  43804. var modes = [
  43805. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  43806. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  43807. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  43808. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  43809. ];
  43810. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  43811. var mode = modes_1[_i];
  43812. this[mode] = (mode === modeToEnable);
  43813. }
  43814. };
  43815. return StandardMaterialDefines;
  43816. }(BABYLON.MaterialDefines));
  43817. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  43818. /**
  43819. * This is the default material used in Babylon. It is the best trade off between quality
  43820. * and performances.
  43821. * @see http://doc.babylonjs.com/babylon101/materials
  43822. */
  43823. var StandardMaterial = /** @class */ (function (_super) {
  43824. __extends(StandardMaterial, _super);
  43825. /**
  43826. * Instantiates a new standard material.
  43827. * This is the default material used in Babylon. It is the best trade off between quality
  43828. * and performances.
  43829. * @see http://doc.babylonjs.com/babylon101/materials
  43830. * @param name Define the name of the material in the scene
  43831. * @param scene Define the scene the material belong to
  43832. */
  43833. function StandardMaterial(name, scene) {
  43834. var _this = _super.call(this, name, scene) || this;
  43835. /**
  43836. * The color of the material lit by the environmental background lighting.
  43837. * @see http://doc.babylonjs.com/babylon101/materials#ambient-color-example
  43838. */
  43839. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  43840. /**
  43841. * The basic color of the material as viewed under a light.
  43842. */
  43843. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  43844. /**
  43845. * Define how the color and intensity of the highlight given by the light in the material.
  43846. */
  43847. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  43848. /**
  43849. * Define the color of the material as if self lit.
  43850. * This will be mixed in the final result even in the absence of light.
  43851. */
  43852. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  43853. /**
  43854. * Defines how sharp are the highlights in the material.
  43855. * The bigger the value the sharper giving a more glossy feeling to the result.
  43856. * Reversely, the smaller the value the blurrier giving a more rough feeling to the result.
  43857. */
  43858. _this.specularPower = 64;
  43859. _this._useAlphaFromDiffuseTexture = false;
  43860. _this._useEmissiveAsIllumination = false;
  43861. _this._linkEmissiveWithDiffuse = false;
  43862. _this._useSpecularOverAlpha = false;
  43863. _this._useReflectionOverAlpha = false;
  43864. _this._disableLighting = false;
  43865. _this._useObjectSpaceNormalMap = false;
  43866. _this._useParallax = false;
  43867. _this._useParallaxOcclusion = false;
  43868. /**
  43869. * Apply a scaling factor that determine which "depth" the height map should reprensent. A value between 0.05 and 0.1 is reasonnable in Parallax, you can reach 0.2 using Parallax Occlusion.
  43870. */
  43871. _this.parallaxScaleBias = 0.05;
  43872. _this._roughness = 0;
  43873. /**
  43874. * In case of refraction, define the value of the indice of refraction.
  43875. * @see http://doc.babylonjs.com/how_to/reflect#how-to-obtain-reflections-and-refractions
  43876. */
  43877. _this.indexOfRefraction = 0.98;
  43878. /**
  43879. * Invert the refraction texture alongside the y axis.
  43880. * It can be usefull with procedural textures or probe for instance.
  43881. * @see http://doc.babylonjs.com/how_to/reflect#how-to-obtain-reflections-and-refractions
  43882. */
  43883. _this.invertRefractionY = true;
  43884. /**
  43885. * Defines the alpha limits in alpha test mode.
  43886. */
  43887. _this.alphaCutOff = 0.4;
  43888. _this._useLightmapAsShadowmap = false;
  43889. _this._useReflectionFresnelFromSpecular = false;
  43890. _this._useGlossinessFromSpecularMapAlpha = false;
  43891. _this._maxSimultaneousLights = 4;
  43892. _this._invertNormalMapX = false;
  43893. _this._invertNormalMapY = false;
  43894. _this._twoSidedLighting = false;
  43895. _this._renderTargets = new BABYLON.SmartArray(16);
  43896. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  43897. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  43898. // Setup the default processing configuration to the scene.
  43899. _this._attachImageProcessingConfiguration(null);
  43900. _this.getRenderTargetTextures = function () {
  43901. _this._renderTargets.reset();
  43902. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  43903. _this._renderTargets.push(_this._reflectionTexture);
  43904. }
  43905. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  43906. _this._renderTargets.push(_this._refractionTexture);
  43907. }
  43908. return _this._renderTargets;
  43909. };
  43910. return _this;
  43911. }
  43912. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  43913. /**
  43914. * Gets the image processing configuration used either in this material.
  43915. */
  43916. get: function () {
  43917. return this._imageProcessingConfiguration;
  43918. },
  43919. /**
  43920. * Sets the Default image processing configuration used either in the this material.
  43921. *
  43922. * If sets to null, the scene one is in use.
  43923. */
  43924. set: function (value) {
  43925. this._attachImageProcessingConfiguration(value);
  43926. // Ensure the effect will be rebuilt.
  43927. this._markAllSubMeshesAsTexturesDirty();
  43928. },
  43929. enumerable: true,
  43930. configurable: true
  43931. });
  43932. /**
  43933. * Attaches a new image processing configuration to the Standard Material.
  43934. * @param configuration
  43935. */
  43936. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  43937. var _this = this;
  43938. if (configuration === this._imageProcessingConfiguration) {
  43939. return;
  43940. }
  43941. // Detaches observer.
  43942. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43943. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43944. }
  43945. // Pick the scene configuration if needed.
  43946. if (!configuration) {
  43947. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  43948. }
  43949. else {
  43950. this._imageProcessingConfiguration = configuration;
  43951. }
  43952. // Attaches observer.
  43953. if (this._imageProcessingConfiguration) {
  43954. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  43955. _this._markAllSubMeshesAsImageProcessingDirty();
  43956. });
  43957. }
  43958. };
  43959. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  43960. /**
  43961. * Gets wether the color curves effect is enabled.
  43962. */
  43963. get: function () {
  43964. return this.imageProcessingConfiguration.colorCurvesEnabled;
  43965. },
  43966. /**
  43967. * Sets wether the color curves effect is enabled.
  43968. */
  43969. set: function (value) {
  43970. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  43971. },
  43972. enumerable: true,
  43973. configurable: true
  43974. });
  43975. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  43976. /**
  43977. * Gets wether the color grading effect is enabled.
  43978. */
  43979. get: function () {
  43980. return this.imageProcessingConfiguration.colorGradingEnabled;
  43981. },
  43982. /**
  43983. * Gets wether the color grading effect is enabled.
  43984. */
  43985. set: function (value) {
  43986. this.imageProcessingConfiguration.colorGradingEnabled = value;
  43987. },
  43988. enumerable: true,
  43989. configurable: true
  43990. });
  43991. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  43992. /**
  43993. * Gets wether tonemapping is enabled or not.
  43994. */
  43995. get: function () {
  43996. return this._imageProcessingConfiguration.toneMappingEnabled;
  43997. },
  43998. /**
  43999. * Sets wether tonemapping is enabled or not
  44000. */
  44001. set: function (value) {
  44002. this._imageProcessingConfiguration.toneMappingEnabled = value;
  44003. },
  44004. enumerable: true,
  44005. configurable: true
  44006. });
  44007. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  44008. /**
  44009. * The camera exposure used on this material.
  44010. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  44011. * This corresponds to a photographic exposure.
  44012. */
  44013. get: function () {
  44014. return this._imageProcessingConfiguration.exposure;
  44015. },
  44016. /**
  44017. * The camera exposure used on this material.
  44018. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  44019. * This corresponds to a photographic exposure.
  44020. */
  44021. set: function (value) {
  44022. this._imageProcessingConfiguration.exposure = value;
  44023. },
  44024. enumerable: true,
  44025. configurable: true
  44026. });
  44027. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  44028. /**
  44029. * Gets The camera contrast used on this material.
  44030. */
  44031. get: function () {
  44032. return this._imageProcessingConfiguration.contrast;
  44033. },
  44034. /**
  44035. * Sets The camera contrast used on this material.
  44036. */
  44037. set: function (value) {
  44038. this._imageProcessingConfiguration.contrast = value;
  44039. },
  44040. enumerable: true,
  44041. configurable: true
  44042. });
  44043. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  44044. /**
  44045. * Gets the Color Grading 2D Lookup Texture.
  44046. */
  44047. get: function () {
  44048. return this._imageProcessingConfiguration.colorGradingTexture;
  44049. },
  44050. /**
  44051. * Sets the Color Grading 2D Lookup Texture.
  44052. */
  44053. set: function (value) {
  44054. this._imageProcessingConfiguration.colorGradingTexture = value;
  44055. },
  44056. enumerable: true,
  44057. configurable: true
  44058. });
  44059. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  44060. /**
  44061. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  44062. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  44063. * 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;
  44064. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  44065. */
  44066. get: function () {
  44067. return this._imageProcessingConfiguration.colorCurves;
  44068. },
  44069. /**
  44070. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  44071. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  44072. * 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;
  44073. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  44074. */
  44075. set: function (value) {
  44076. this._imageProcessingConfiguration.colorCurves = value;
  44077. },
  44078. enumerable: true,
  44079. configurable: true
  44080. });
  44081. Object.defineProperty(StandardMaterial.prototype, "hasRenderTargetTextures", {
  44082. /**
  44083. * Gets a boolean indicating that current material needs to register RTT
  44084. */
  44085. get: function () {
  44086. if (StandardMaterial.ReflectionTextureEnabled && this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  44087. return true;
  44088. }
  44089. if (StandardMaterial.RefractionTextureEnabled && this._refractionTexture && this._refractionTexture.isRenderTarget) {
  44090. return true;
  44091. }
  44092. return false;
  44093. },
  44094. enumerable: true,
  44095. configurable: true
  44096. });
  44097. /**
  44098. * Gets the current class name of the material e.g. "StandardMaterial"
  44099. * Mainly use in serialization.
  44100. * @returns the class name
  44101. */
  44102. StandardMaterial.prototype.getClassName = function () {
  44103. return "StandardMaterial";
  44104. };
  44105. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  44106. /**
  44107. * In case the depth buffer does not allow enough depth precision for your scene (might be the case in large scenes)
  44108. * You can try switching to logarithmic depth.
  44109. * @see http://doc.babylonjs.com/how_to/using_logarithmic_depth_buffer
  44110. */
  44111. get: function () {
  44112. return this._useLogarithmicDepth;
  44113. },
  44114. set: function (value) {
  44115. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  44116. this._markAllSubMeshesAsMiscDirty();
  44117. },
  44118. enumerable: true,
  44119. configurable: true
  44120. });
  44121. /**
  44122. * Specifies if the material will require alpha blending
  44123. * @returns a boolean specifying if alpha blending is needed
  44124. */
  44125. StandardMaterial.prototype.needAlphaBlending = function () {
  44126. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  44127. };
  44128. /**
  44129. * Specifies if this material should be rendered in alpha test mode
  44130. * @returns a boolean specifying if an alpha test is needed.
  44131. */
  44132. StandardMaterial.prototype.needAlphaTesting = function () {
  44133. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  44134. };
  44135. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  44136. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  44137. };
  44138. /**
  44139. * Get the texture used for alpha test purpose.
  44140. * @returns the diffuse texture in case of the standard material.
  44141. */
  44142. StandardMaterial.prototype.getAlphaTestTexture = function () {
  44143. return this._diffuseTexture;
  44144. };
  44145. /**
  44146. * Get if the submesh is ready to be used and all its information available.
  44147. * Child classes can use it to update shaders
  44148. * @param mesh defines the mesh to check
  44149. * @param subMesh defines which submesh to check
  44150. * @param useInstances specifies that instances should be used
  44151. * @returns a boolean indicating that the submesh is ready or not
  44152. */
  44153. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  44154. if (useInstances === void 0) { useInstances = false; }
  44155. if (subMesh.effect && this.isFrozen) {
  44156. if (this._wasPreviouslyReady) {
  44157. return true;
  44158. }
  44159. }
  44160. if (!subMesh._materialDefines) {
  44161. subMesh._materialDefines = new StandardMaterialDefines();
  44162. }
  44163. var scene = this.getScene();
  44164. var defines = subMesh._materialDefines;
  44165. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  44166. if (defines._renderId === scene.getRenderId()) {
  44167. return true;
  44168. }
  44169. }
  44170. var engine = scene.getEngine();
  44171. // Lights
  44172. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  44173. // Textures
  44174. if (defines._areTexturesDirty) {
  44175. defines._needUVs = false;
  44176. defines.MAINUV1 = false;
  44177. defines.MAINUV2 = false;
  44178. if (scene.texturesEnabled) {
  44179. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  44180. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  44181. return false;
  44182. }
  44183. else {
  44184. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  44185. }
  44186. }
  44187. else {
  44188. defines.DIFFUSE = false;
  44189. }
  44190. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  44191. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  44192. return false;
  44193. }
  44194. else {
  44195. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  44196. }
  44197. }
  44198. else {
  44199. defines.AMBIENT = false;
  44200. }
  44201. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  44202. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  44203. return false;
  44204. }
  44205. else {
  44206. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  44207. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  44208. }
  44209. }
  44210. else {
  44211. defines.OPACITY = false;
  44212. }
  44213. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  44214. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  44215. return false;
  44216. }
  44217. else {
  44218. defines._needNormals = true;
  44219. defines.REFLECTION = true;
  44220. defines.ROUGHNESS = (this._roughness > 0);
  44221. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  44222. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  44223. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  44224. switch (this._reflectionTexture.coordinatesMode) {
  44225. case BABYLON.Texture.EXPLICIT_MODE:
  44226. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  44227. break;
  44228. case BABYLON.Texture.PLANAR_MODE:
  44229. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  44230. break;
  44231. case BABYLON.Texture.PROJECTION_MODE:
  44232. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  44233. break;
  44234. case BABYLON.Texture.SKYBOX_MODE:
  44235. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  44236. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !this._reflectionTexture.getReflectionTextureMatrix().isIdentity();
  44237. break;
  44238. case BABYLON.Texture.SPHERICAL_MODE:
  44239. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  44240. break;
  44241. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  44242. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  44243. break;
  44244. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  44245. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  44246. break;
  44247. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  44248. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  44249. break;
  44250. case BABYLON.Texture.CUBIC_MODE:
  44251. case BABYLON.Texture.INVCUBIC_MODE:
  44252. default:
  44253. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  44254. break;
  44255. }
  44256. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  44257. }
  44258. }
  44259. else {
  44260. defines.REFLECTION = false;
  44261. }
  44262. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  44263. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  44264. return false;
  44265. }
  44266. else {
  44267. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  44268. }
  44269. }
  44270. else {
  44271. defines.EMISSIVE = false;
  44272. }
  44273. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  44274. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  44275. return false;
  44276. }
  44277. else {
  44278. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  44279. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  44280. }
  44281. }
  44282. else {
  44283. defines.LIGHTMAP = false;
  44284. }
  44285. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  44286. if (!this._specularTexture.isReadyOrNotBlocking()) {
  44287. return false;
  44288. }
  44289. else {
  44290. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  44291. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  44292. }
  44293. }
  44294. else {
  44295. defines.SPECULAR = false;
  44296. }
  44297. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  44298. // Bump texure can not be not blocking.
  44299. if (!this._bumpTexture.isReady()) {
  44300. return false;
  44301. }
  44302. else {
  44303. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  44304. defines.PARALLAX = this._useParallax;
  44305. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  44306. }
  44307. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  44308. }
  44309. else {
  44310. defines.BUMP = false;
  44311. }
  44312. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  44313. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  44314. return false;
  44315. }
  44316. else {
  44317. defines._needUVs = true;
  44318. defines.REFRACTION = true;
  44319. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  44320. }
  44321. }
  44322. else {
  44323. defines.REFRACTION = false;
  44324. }
  44325. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  44326. }
  44327. else {
  44328. defines.DIFFUSE = false;
  44329. defines.AMBIENT = false;
  44330. defines.OPACITY = false;
  44331. defines.REFLECTION = false;
  44332. defines.EMISSIVE = false;
  44333. defines.LIGHTMAP = false;
  44334. defines.BUMP = false;
  44335. defines.REFRACTION = false;
  44336. }
  44337. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  44338. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  44339. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  44340. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  44341. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  44342. }
  44343. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  44344. if (!this._imageProcessingConfiguration.isReady()) {
  44345. return false;
  44346. }
  44347. this._imageProcessingConfiguration.prepareDefines(defines);
  44348. defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);
  44349. defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);
  44350. }
  44351. if (defines._areFresnelDirty) {
  44352. if (StandardMaterial.FresnelEnabled) {
  44353. // Fresnel
  44354. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  44355. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  44356. this._reflectionFresnelParameters) {
  44357. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  44358. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  44359. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  44360. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  44361. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  44362. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  44363. defines._needNormals = true;
  44364. defines.FRESNEL = true;
  44365. }
  44366. }
  44367. else {
  44368. defines.FRESNEL = false;
  44369. }
  44370. }
  44371. // Misc.
  44372. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  44373. // Attribs
  44374. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  44375. // Values that need to be evaluated on every frame
  44376. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  44377. // Get correct effect
  44378. if (defines.isDirty) {
  44379. defines.markAsProcessed();
  44380. // Fallbacks
  44381. var fallbacks = new BABYLON.EffectFallbacks();
  44382. if (defines.REFLECTION) {
  44383. fallbacks.addFallback(0, "REFLECTION");
  44384. }
  44385. if (defines.SPECULAR) {
  44386. fallbacks.addFallback(0, "SPECULAR");
  44387. }
  44388. if (defines.BUMP) {
  44389. fallbacks.addFallback(0, "BUMP");
  44390. }
  44391. if (defines.PARALLAX) {
  44392. fallbacks.addFallback(1, "PARALLAX");
  44393. }
  44394. if (defines.PARALLAXOCCLUSION) {
  44395. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  44396. }
  44397. if (defines.SPECULAROVERALPHA) {
  44398. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  44399. }
  44400. if (defines.FOG) {
  44401. fallbacks.addFallback(1, "FOG");
  44402. }
  44403. if (defines.POINTSIZE) {
  44404. fallbacks.addFallback(0, "POINTSIZE");
  44405. }
  44406. if (defines.LOGARITHMICDEPTH) {
  44407. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  44408. }
  44409. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  44410. if (defines.SPECULARTERM) {
  44411. fallbacks.addFallback(0, "SPECULARTERM");
  44412. }
  44413. if (defines.DIFFUSEFRESNEL) {
  44414. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  44415. }
  44416. if (defines.OPACITYFRESNEL) {
  44417. fallbacks.addFallback(2, "OPACITYFRESNEL");
  44418. }
  44419. if (defines.REFLECTIONFRESNEL) {
  44420. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  44421. }
  44422. if (defines.EMISSIVEFRESNEL) {
  44423. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  44424. }
  44425. if (defines.FRESNEL) {
  44426. fallbacks.addFallback(4, "FRESNEL");
  44427. }
  44428. //Attributes
  44429. var attribs = [BABYLON.VertexBuffer.PositionKind];
  44430. if (defines.NORMAL) {
  44431. attribs.push(BABYLON.VertexBuffer.NormalKind);
  44432. }
  44433. if (defines.UV1) {
  44434. attribs.push(BABYLON.VertexBuffer.UVKind);
  44435. }
  44436. if (defines.UV2) {
  44437. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  44438. }
  44439. if (defines.VERTEXCOLOR) {
  44440. attribs.push(BABYLON.VertexBuffer.ColorKind);
  44441. }
  44442. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  44443. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  44444. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  44445. var shaderName = "default";
  44446. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  44447. "vFogInfos", "vFogColor", "pointSize",
  44448. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  44449. "mBones",
  44450. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  44451. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  44452. "vReflectionPosition", "vReflectionSize",
  44453. "logarithmicDepthConstant", "vTangentSpaceParams", "alphaCutOff", "boneTextureWidth"
  44454. ];
  44455. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler",
  44456. "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler",
  44457. "refractionCubeSampler", "refraction2DSampler", "boneSampler"];
  44458. var uniformBuffers = ["Material", "Scene"];
  44459. if (BABYLON.ImageProcessingConfiguration) {
  44460. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  44461. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  44462. }
  44463. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  44464. uniformsNames: uniforms,
  44465. uniformBuffersNames: uniformBuffers,
  44466. samplers: samplers,
  44467. defines: defines,
  44468. maxSimultaneousLights: this._maxSimultaneousLights
  44469. });
  44470. if (this.customShaderNameResolve) {
  44471. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  44472. }
  44473. var join = defines.toString();
  44474. var previousEffect = subMesh.effect;
  44475. var effect = scene.getEngine().createEffect(shaderName, {
  44476. attributes: attribs,
  44477. uniformsNames: uniforms,
  44478. uniformBuffersNames: uniformBuffers,
  44479. samplers: samplers,
  44480. defines: join,
  44481. fallbacks: fallbacks,
  44482. onCompiled: this.onCompiled,
  44483. onError: this.onError,
  44484. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  44485. }, engine);
  44486. if (effect) {
  44487. // Use previous effect while new one is compiling
  44488. if (this.allowShaderHotSwapping && previousEffect && !effect.isReady()) {
  44489. effect = previousEffect;
  44490. defines.markAsUnprocessed();
  44491. }
  44492. else {
  44493. scene.resetCachedMaterial();
  44494. subMesh.setEffect(effect, defines);
  44495. this.buildUniformLayout();
  44496. }
  44497. }
  44498. }
  44499. if (!subMesh.effect || !subMesh.effect.isReady()) {
  44500. return false;
  44501. }
  44502. defines._renderId = scene.getRenderId();
  44503. this._wasPreviouslyReady = true;
  44504. return true;
  44505. };
  44506. /**
  44507. * Builds the material UBO layouts.
  44508. * Used internally during the effect preparation.
  44509. */
  44510. StandardMaterial.prototype.buildUniformLayout = function () {
  44511. // Order is important !
  44512. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  44513. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  44514. this._uniformBuffer.addUniform("opacityParts", 4);
  44515. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  44516. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  44517. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  44518. this._uniformBuffer.addUniform("refractionRightColor", 4);
  44519. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  44520. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  44521. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  44522. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  44523. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  44524. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  44525. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  44526. this._uniformBuffer.addUniform("vReflectionSize", 3);
  44527. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  44528. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  44529. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  44530. this._uniformBuffer.addUniform("vBumpInfos", 3);
  44531. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  44532. this._uniformBuffer.addUniform("ambientMatrix", 16);
  44533. this._uniformBuffer.addUniform("opacityMatrix", 16);
  44534. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  44535. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  44536. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  44537. this._uniformBuffer.addUniform("specularMatrix", 16);
  44538. this._uniformBuffer.addUniform("bumpMatrix", 16);
  44539. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  44540. this._uniformBuffer.addUniform("refractionMatrix", 16);
  44541. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  44542. this._uniformBuffer.addUniform("vSpecularColor", 4);
  44543. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  44544. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  44545. this._uniformBuffer.addUniform("pointSize", 1);
  44546. this._uniformBuffer.create();
  44547. };
  44548. /**
  44549. * Unbinds the material from the mesh
  44550. */
  44551. StandardMaterial.prototype.unbind = function () {
  44552. if (this._activeEffect) {
  44553. var needFlag = false;
  44554. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  44555. this._activeEffect.setTexture("reflection2DSampler", null);
  44556. needFlag = true;
  44557. }
  44558. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  44559. this._activeEffect.setTexture("refraction2DSampler", null);
  44560. needFlag = true;
  44561. }
  44562. if (needFlag) {
  44563. this._markAllSubMeshesAsTexturesDirty();
  44564. }
  44565. }
  44566. _super.prototype.unbind.call(this);
  44567. };
  44568. /**
  44569. * Binds the submesh to this material by preparing the effect and shader to draw
  44570. * @param world defines the world transformation matrix
  44571. * @param mesh defines the mesh containing the submesh
  44572. * @param subMesh defines the submesh to bind the material to
  44573. */
  44574. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  44575. var scene = this.getScene();
  44576. var defines = subMesh._materialDefines;
  44577. if (!defines) {
  44578. return;
  44579. }
  44580. var effect = subMesh.effect;
  44581. if (!effect) {
  44582. return;
  44583. }
  44584. this._activeEffect = effect;
  44585. // Matrices
  44586. this.bindOnlyWorldMatrix(world);
  44587. // Normal Matrix
  44588. if (defines.OBJECTSPACE_NORMALMAP) {
  44589. world.toNormalMatrix(this._normalMatrix);
  44590. this.bindOnlyNormalMatrix(this._normalMatrix);
  44591. }
  44592. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  44593. // Bones
  44594. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  44595. if (mustRebind) {
  44596. this._uniformBuffer.bindToEffect(effect, "Material");
  44597. this.bindViewProjection(effect);
  44598. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  44599. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  44600. // Fresnel
  44601. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  44602. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  44603. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  44604. }
  44605. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  44606. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  44607. }
  44608. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  44609. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  44610. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  44611. }
  44612. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  44613. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  44614. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  44615. }
  44616. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  44617. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  44618. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  44619. }
  44620. }
  44621. // Textures
  44622. if (scene.texturesEnabled) {
  44623. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  44624. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  44625. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  44626. if (this._diffuseTexture.hasAlpha) {
  44627. effect.setFloat("alphaCutOff", this.alphaCutOff);
  44628. }
  44629. }
  44630. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  44631. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  44632. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  44633. }
  44634. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  44635. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  44636. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  44637. }
  44638. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  44639. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  44640. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  44641. if (this._reflectionTexture.boundingBoxSize) {
  44642. var cubeTexture = this._reflectionTexture;
  44643. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  44644. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  44645. }
  44646. }
  44647. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  44648. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  44649. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  44650. }
  44651. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  44652. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  44653. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  44654. }
  44655. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  44656. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  44657. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  44658. }
  44659. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  44660. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  44661. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  44662. if (scene._mirroredCameraPosition) {
  44663. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  44664. }
  44665. else {
  44666. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  44667. }
  44668. }
  44669. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  44670. var depth = 1.0;
  44671. if (!this._refractionTexture.isCube) {
  44672. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  44673. if (this._refractionTexture.depth) {
  44674. depth = this._refractionTexture.depth;
  44675. }
  44676. }
  44677. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  44678. }
  44679. }
  44680. // Point size
  44681. if (this.pointsCloud) {
  44682. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  44683. }
  44684. if (defines.SPECULARTERM) {
  44685. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  44686. }
  44687. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  44688. // Diffuse
  44689. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  44690. }
  44691. // Textures
  44692. if (scene.texturesEnabled) {
  44693. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  44694. effect.setTexture("diffuseSampler", this._diffuseTexture);
  44695. }
  44696. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  44697. effect.setTexture("ambientSampler", this._ambientTexture);
  44698. }
  44699. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  44700. effect.setTexture("opacitySampler", this._opacityTexture);
  44701. }
  44702. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  44703. if (this._reflectionTexture.isCube) {
  44704. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  44705. }
  44706. else {
  44707. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  44708. }
  44709. }
  44710. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  44711. effect.setTexture("emissiveSampler", this._emissiveTexture);
  44712. }
  44713. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  44714. effect.setTexture("lightmapSampler", this._lightmapTexture);
  44715. }
  44716. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  44717. effect.setTexture("specularSampler", this._specularTexture);
  44718. }
  44719. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  44720. effect.setTexture("bumpSampler", this._bumpTexture);
  44721. }
  44722. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  44723. var depth = 1.0;
  44724. if (this._refractionTexture.isCube) {
  44725. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  44726. }
  44727. else {
  44728. effect.setTexture("refraction2DSampler", this._refractionTexture);
  44729. }
  44730. }
  44731. }
  44732. // Clip plane
  44733. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  44734. // Colors
  44735. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  44736. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  44737. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  44738. }
  44739. if (mustRebind || !this.isFrozen) {
  44740. // Lights
  44741. if (scene.lightsEnabled && !this._disableLighting) {
  44742. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  44743. }
  44744. // View
  44745. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  44746. this.bindView(effect);
  44747. }
  44748. // Fog
  44749. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  44750. // Morph targets
  44751. if (defines.NUM_MORPH_INFLUENCERS) {
  44752. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  44753. }
  44754. // Log. depth
  44755. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  44756. // image processing
  44757. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  44758. this._imageProcessingConfiguration.bind(this._activeEffect);
  44759. }
  44760. }
  44761. this._uniformBuffer.update();
  44762. this._afterBind(mesh, this._activeEffect);
  44763. };
  44764. /**
  44765. * Get the list of animatables in the material.
  44766. * @returns the list of animatables object used in the material
  44767. */
  44768. StandardMaterial.prototype.getAnimatables = function () {
  44769. var results = [];
  44770. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  44771. results.push(this._diffuseTexture);
  44772. }
  44773. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  44774. results.push(this._ambientTexture);
  44775. }
  44776. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  44777. results.push(this._opacityTexture);
  44778. }
  44779. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  44780. results.push(this._reflectionTexture);
  44781. }
  44782. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  44783. results.push(this._emissiveTexture);
  44784. }
  44785. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  44786. results.push(this._specularTexture);
  44787. }
  44788. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  44789. results.push(this._bumpTexture);
  44790. }
  44791. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  44792. results.push(this._lightmapTexture);
  44793. }
  44794. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  44795. results.push(this._refractionTexture);
  44796. }
  44797. return results;
  44798. };
  44799. /**
  44800. * Gets the active textures from the material
  44801. * @returns an array of textures
  44802. */
  44803. StandardMaterial.prototype.getActiveTextures = function () {
  44804. var activeTextures = _super.prototype.getActiveTextures.call(this);
  44805. if (this._diffuseTexture) {
  44806. activeTextures.push(this._diffuseTexture);
  44807. }
  44808. if (this._ambientTexture) {
  44809. activeTextures.push(this._ambientTexture);
  44810. }
  44811. if (this._opacityTexture) {
  44812. activeTextures.push(this._opacityTexture);
  44813. }
  44814. if (this._reflectionTexture) {
  44815. activeTextures.push(this._reflectionTexture);
  44816. }
  44817. if (this._emissiveTexture) {
  44818. activeTextures.push(this._emissiveTexture);
  44819. }
  44820. if (this._specularTexture) {
  44821. activeTextures.push(this._specularTexture);
  44822. }
  44823. if (this._bumpTexture) {
  44824. activeTextures.push(this._bumpTexture);
  44825. }
  44826. if (this._lightmapTexture) {
  44827. activeTextures.push(this._lightmapTexture);
  44828. }
  44829. if (this._refractionTexture) {
  44830. activeTextures.push(this._refractionTexture);
  44831. }
  44832. return activeTextures;
  44833. };
  44834. /**
  44835. * Specifies if the material uses a texture
  44836. * @param texture defines the texture to check against the material
  44837. * @returns a boolean specifying if the material uses the texture
  44838. */
  44839. StandardMaterial.prototype.hasTexture = function (texture) {
  44840. if (_super.prototype.hasTexture.call(this, texture)) {
  44841. return true;
  44842. }
  44843. if (this._diffuseTexture === texture) {
  44844. return true;
  44845. }
  44846. if (this._ambientTexture === texture) {
  44847. return true;
  44848. }
  44849. if (this._opacityTexture === texture) {
  44850. return true;
  44851. }
  44852. if (this._reflectionTexture === texture) {
  44853. return true;
  44854. }
  44855. if (this._emissiveTexture === texture) {
  44856. return true;
  44857. }
  44858. if (this._specularTexture === texture) {
  44859. return true;
  44860. }
  44861. if (this._bumpTexture === texture) {
  44862. return true;
  44863. }
  44864. if (this._lightmapTexture === texture) {
  44865. return true;
  44866. }
  44867. if (this._refractionTexture === texture) {
  44868. return true;
  44869. }
  44870. return false;
  44871. };
  44872. /**
  44873. * Disposes the material
  44874. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  44875. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  44876. */
  44877. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  44878. if (forceDisposeTextures) {
  44879. if (this._diffuseTexture) {
  44880. this._diffuseTexture.dispose();
  44881. }
  44882. if (this._ambientTexture) {
  44883. this._ambientTexture.dispose();
  44884. }
  44885. if (this._opacityTexture) {
  44886. this._opacityTexture.dispose();
  44887. }
  44888. if (this._reflectionTexture) {
  44889. this._reflectionTexture.dispose();
  44890. }
  44891. if (this._emissiveTexture) {
  44892. this._emissiveTexture.dispose();
  44893. }
  44894. if (this._specularTexture) {
  44895. this._specularTexture.dispose();
  44896. }
  44897. if (this._bumpTexture) {
  44898. this._bumpTexture.dispose();
  44899. }
  44900. if (this._lightmapTexture) {
  44901. this._lightmapTexture.dispose();
  44902. }
  44903. if (this._refractionTexture) {
  44904. this._refractionTexture.dispose();
  44905. }
  44906. }
  44907. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44908. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44909. }
  44910. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  44911. };
  44912. /**
  44913. * Makes a duplicate of the material, and gives it a new name
  44914. * @param name defines the new name for the duplicated material
  44915. * @returns the cloned material
  44916. */
  44917. StandardMaterial.prototype.clone = function (name) {
  44918. var _this = this;
  44919. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  44920. result.name = name;
  44921. result.id = name;
  44922. return result;
  44923. };
  44924. /**
  44925. * Serializes this material in a JSON representation
  44926. * @returns the serialized material object
  44927. */
  44928. StandardMaterial.prototype.serialize = function () {
  44929. return BABYLON.SerializationHelper.Serialize(this);
  44930. };
  44931. /**
  44932. * Creates a standard material from parsed material data
  44933. * @param source defines the JSON represnetation of the material
  44934. * @param scene defines the hosting scene
  44935. * @param rootUrl defines the root URL to use to load textures and relative dependencies
  44936. * @returns a new material
  44937. */
  44938. StandardMaterial.Parse = function (source, scene, rootUrl) {
  44939. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  44940. };
  44941. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  44942. /**
  44943. * Are diffuse textures enabled in the application.
  44944. */
  44945. get: function () {
  44946. return StandardMaterial._DiffuseTextureEnabled;
  44947. },
  44948. set: function (value) {
  44949. if (StandardMaterial._DiffuseTextureEnabled === value) {
  44950. return;
  44951. }
  44952. StandardMaterial._DiffuseTextureEnabled = value;
  44953. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44954. },
  44955. enumerable: true,
  44956. configurable: true
  44957. });
  44958. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  44959. /**
  44960. * Are ambient textures enabled in the application.
  44961. */
  44962. get: function () {
  44963. return StandardMaterial._AmbientTextureEnabled;
  44964. },
  44965. set: function (value) {
  44966. if (StandardMaterial._AmbientTextureEnabled === value) {
  44967. return;
  44968. }
  44969. StandardMaterial._AmbientTextureEnabled = value;
  44970. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44971. },
  44972. enumerable: true,
  44973. configurable: true
  44974. });
  44975. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  44976. /**
  44977. * Are opacity textures enabled in the application.
  44978. */
  44979. get: function () {
  44980. return StandardMaterial._OpacityTextureEnabled;
  44981. },
  44982. set: function (value) {
  44983. if (StandardMaterial._OpacityTextureEnabled === value) {
  44984. return;
  44985. }
  44986. StandardMaterial._OpacityTextureEnabled = value;
  44987. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44988. },
  44989. enumerable: true,
  44990. configurable: true
  44991. });
  44992. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  44993. /**
  44994. * Are reflection textures enabled in the application.
  44995. */
  44996. get: function () {
  44997. return StandardMaterial._ReflectionTextureEnabled;
  44998. },
  44999. set: function (value) {
  45000. if (StandardMaterial._ReflectionTextureEnabled === value) {
  45001. return;
  45002. }
  45003. StandardMaterial._ReflectionTextureEnabled = value;
  45004. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  45005. },
  45006. enumerable: true,
  45007. configurable: true
  45008. });
  45009. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  45010. /**
  45011. * Are emissive textures enabled in the application.
  45012. */
  45013. get: function () {
  45014. return StandardMaterial._EmissiveTextureEnabled;
  45015. },
  45016. set: function (value) {
  45017. if (StandardMaterial._EmissiveTextureEnabled === value) {
  45018. return;
  45019. }
  45020. StandardMaterial._EmissiveTextureEnabled = value;
  45021. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  45022. },
  45023. enumerable: true,
  45024. configurable: true
  45025. });
  45026. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  45027. /**
  45028. * Are specular textures enabled in the application.
  45029. */
  45030. get: function () {
  45031. return StandardMaterial._SpecularTextureEnabled;
  45032. },
  45033. set: function (value) {
  45034. if (StandardMaterial._SpecularTextureEnabled === value) {
  45035. return;
  45036. }
  45037. StandardMaterial._SpecularTextureEnabled = value;
  45038. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  45039. },
  45040. enumerable: true,
  45041. configurable: true
  45042. });
  45043. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  45044. /**
  45045. * Are bump textures enabled in the application.
  45046. */
  45047. get: function () {
  45048. return StandardMaterial._BumpTextureEnabled;
  45049. },
  45050. set: function (value) {
  45051. if (StandardMaterial._BumpTextureEnabled === value) {
  45052. return;
  45053. }
  45054. StandardMaterial._BumpTextureEnabled = value;
  45055. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  45056. },
  45057. enumerable: true,
  45058. configurable: true
  45059. });
  45060. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  45061. /**
  45062. * Are lightmap textures enabled in the application.
  45063. */
  45064. get: function () {
  45065. return StandardMaterial._LightmapTextureEnabled;
  45066. },
  45067. set: function (value) {
  45068. if (StandardMaterial._LightmapTextureEnabled === value) {
  45069. return;
  45070. }
  45071. StandardMaterial._LightmapTextureEnabled = value;
  45072. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  45073. },
  45074. enumerable: true,
  45075. configurable: true
  45076. });
  45077. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  45078. /**
  45079. * Are refraction textures enabled in the application.
  45080. */
  45081. get: function () {
  45082. return StandardMaterial._RefractionTextureEnabled;
  45083. },
  45084. set: function (value) {
  45085. if (StandardMaterial._RefractionTextureEnabled === value) {
  45086. return;
  45087. }
  45088. StandardMaterial._RefractionTextureEnabled = value;
  45089. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  45090. },
  45091. enumerable: true,
  45092. configurable: true
  45093. });
  45094. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  45095. /**
  45096. * Are color grading textures enabled in the application.
  45097. */
  45098. get: function () {
  45099. return StandardMaterial._ColorGradingTextureEnabled;
  45100. },
  45101. set: function (value) {
  45102. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  45103. return;
  45104. }
  45105. StandardMaterial._ColorGradingTextureEnabled = value;
  45106. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  45107. },
  45108. enumerable: true,
  45109. configurable: true
  45110. });
  45111. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  45112. /**
  45113. * Are fresnels enabled in the application.
  45114. */
  45115. get: function () {
  45116. return StandardMaterial._FresnelEnabled;
  45117. },
  45118. set: function (value) {
  45119. if (StandardMaterial._FresnelEnabled === value) {
  45120. return;
  45121. }
  45122. StandardMaterial._FresnelEnabled = value;
  45123. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  45124. },
  45125. enumerable: true,
  45126. configurable: true
  45127. });
  45128. // Flags used to enable or disable a type of texture for all Standard Materials
  45129. StandardMaterial._DiffuseTextureEnabled = true;
  45130. StandardMaterial._AmbientTextureEnabled = true;
  45131. StandardMaterial._OpacityTextureEnabled = true;
  45132. StandardMaterial._ReflectionTextureEnabled = true;
  45133. StandardMaterial._EmissiveTextureEnabled = true;
  45134. StandardMaterial._SpecularTextureEnabled = true;
  45135. StandardMaterial._BumpTextureEnabled = true;
  45136. StandardMaterial._LightmapTextureEnabled = true;
  45137. StandardMaterial._RefractionTextureEnabled = true;
  45138. StandardMaterial._ColorGradingTextureEnabled = true;
  45139. StandardMaterial._FresnelEnabled = true;
  45140. __decorate([
  45141. BABYLON.serializeAsTexture("diffuseTexture")
  45142. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  45143. __decorate([
  45144. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45145. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  45146. __decorate([
  45147. BABYLON.serializeAsTexture("ambientTexture")
  45148. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  45149. __decorate([
  45150. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45151. ], StandardMaterial.prototype, "ambientTexture", void 0);
  45152. __decorate([
  45153. BABYLON.serializeAsTexture("opacityTexture")
  45154. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  45155. __decorate([
  45156. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45157. ], StandardMaterial.prototype, "opacityTexture", void 0);
  45158. __decorate([
  45159. BABYLON.serializeAsTexture("reflectionTexture")
  45160. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  45161. __decorate([
  45162. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45163. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  45164. __decorate([
  45165. BABYLON.serializeAsTexture("emissiveTexture")
  45166. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  45167. __decorate([
  45168. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45169. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  45170. __decorate([
  45171. BABYLON.serializeAsTexture("specularTexture")
  45172. ], StandardMaterial.prototype, "_specularTexture", void 0);
  45173. __decorate([
  45174. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45175. ], StandardMaterial.prototype, "specularTexture", void 0);
  45176. __decorate([
  45177. BABYLON.serializeAsTexture("bumpTexture")
  45178. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  45179. __decorate([
  45180. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45181. ], StandardMaterial.prototype, "bumpTexture", void 0);
  45182. __decorate([
  45183. BABYLON.serializeAsTexture("lightmapTexture")
  45184. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  45185. __decorate([
  45186. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45187. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  45188. __decorate([
  45189. BABYLON.serializeAsTexture("refractionTexture")
  45190. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  45191. __decorate([
  45192. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45193. ], StandardMaterial.prototype, "refractionTexture", void 0);
  45194. __decorate([
  45195. BABYLON.serializeAsColor3("ambient")
  45196. ], StandardMaterial.prototype, "ambientColor", void 0);
  45197. __decorate([
  45198. BABYLON.serializeAsColor3("diffuse")
  45199. ], StandardMaterial.prototype, "diffuseColor", void 0);
  45200. __decorate([
  45201. BABYLON.serializeAsColor3("specular")
  45202. ], StandardMaterial.prototype, "specularColor", void 0);
  45203. __decorate([
  45204. BABYLON.serializeAsColor3("emissive")
  45205. ], StandardMaterial.prototype, "emissiveColor", void 0);
  45206. __decorate([
  45207. BABYLON.serialize()
  45208. ], StandardMaterial.prototype, "specularPower", void 0);
  45209. __decorate([
  45210. BABYLON.serialize("useAlphaFromDiffuseTexture")
  45211. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  45212. __decorate([
  45213. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45214. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  45215. __decorate([
  45216. BABYLON.serialize("useEmissiveAsIllumination")
  45217. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  45218. __decorate([
  45219. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45220. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  45221. __decorate([
  45222. BABYLON.serialize("linkEmissiveWithDiffuse")
  45223. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  45224. __decorate([
  45225. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45226. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  45227. __decorate([
  45228. BABYLON.serialize("useSpecularOverAlpha")
  45229. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  45230. __decorate([
  45231. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45232. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  45233. __decorate([
  45234. BABYLON.serialize("useReflectionOverAlpha")
  45235. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  45236. __decorate([
  45237. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45238. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  45239. __decorate([
  45240. BABYLON.serialize("disableLighting")
  45241. ], StandardMaterial.prototype, "_disableLighting", void 0);
  45242. __decorate([
  45243. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45244. ], StandardMaterial.prototype, "disableLighting", void 0);
  45245. __decorate([
  45246. BABYLON.serialize("useObjectSpaceNormalMap")
  45247. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  45248. __decorate([
  45249. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45250. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  45251. __decorate([
  45252. BABYLON.serialize("useParallax")
  45253. ], StandardMaterial.prototype, "_useParallax", void 0);
  45254. __decorate([
  45255. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45256. ], StandardMaterial.prototype, "useParallax", void 0);
  45257. __decorate([
  45258. BABYLON.serialize("useParallaxOcclusion")
  45259. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  45260. __decorate([
  45261. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45262. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  45263. __decorate([
  45264. BABYLON.serialize()
  45265. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  45266. __decorate([
  45267. BABYLON.serialize("roughness")
  45268. ], StandardMaterial.prototype, "_roughness", void 0);
  45269. __decorate([
  45270. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45271. ], StandardMaterial.prototype, "roughness", void 0);
  45272. __decorate([
  45273. BABYLON.serialize()
  45274. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  45275. __decorate([
  45276. BABYLON.serialize()
  45277. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  45278. __decorate([
  45279. BABYLON.serialize()
  45280. ], StandardMaterial.prototype, "alphaCutOff", void 0);
  45281. __decorate([
  45282. BABYLON.serialize("useLightmapAsShadowmap")
  45283. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  45284. __decorate([
  45285. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45286. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45287. __decorate([
  45288. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  45289. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  45290. __decorate([
  45291. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  45292. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  45293. __decorate([
  45294. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  45295. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  45296. __decorate([
  45297. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  45298. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  45299. __decorate([
  45300. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  45301. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  45302. __decorate([
  45303. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  45304. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  45305. __decorate([
  45306. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  45307. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  45308. __decorate([
  45309. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  45310. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  45311. __decorate([
  45312. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  45313. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  45314. __decorate([
  45315. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  45316. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  45317. __decorate([
  45318. BABYLON.serialize("useReflectionFresnelFromSpecular")
  45319. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  45320. __decorate([
  45321. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  45322. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  45323. __decorate([
  45324. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  45325. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  45326. __decorate([
  45327. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45328. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  45329. __decorate([
  45330. BABYLON.serialize("maxSimultaneousLights")
  45331. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  45332. __decorate([
  45333. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45334. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  45335. __decorate([
  45336. BABYLON.serialize("invertNormalMapX")
  45337. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  45338. __decorate([
  45339. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45340. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  45341. __decorate([
  45342. BABYLON.serialize("invertNormalMapY")
  45343. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  45344. __decorate([
  45345. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45346. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  45347. __decorate([
  45348. BABYLON.serialize("twoSidedLighting")
  45349. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  45350. __decorate([
  45351. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45352. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  45353. __decorate([
  45354. BABYLON.serialize()
  45355. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  45356. return StandardMaterial;
  45357. }(BABYLON.PushMaterial));
  45358. BABYLON.StandardMaterial = StandardMaterial;
  45359. })(BABYLON || (BABYLON = {}));
  45360. //# sourceMappingURL=babylon.standardMaterial.js.map
  45361. var BABYLON;
  45362. (function (BABYLON) {
  45363. /**
  45364. * Class representing spherical polynomial coefficients to the 3rd degree
  45365. */
  45366. var SphericalPolynomial = /** @class */ (function () {
  45367. function SphericalPolynomial() {
  45368. /**
  45369. * The x coefficients of the spherical polynomial
  45370. */
  45371. this.x = BABYLON.Vector3.Zero();
  45372. /**
  45373. * The y coefficients of the spherical polynomial
  45374. */
  45375. this.y = BABYLON.Vector3.Zero();
  45376. /**
  45377. * The z coefficients of the spherical polynomial
  45378. */
  45379. this.z = BABYLON.Vector3.Zero();
  45380. /**
  45381. * The xx coefficients of the spherical polynomial
  45382. */
  45383. this.xx = BABYLON.Vector3.Zero();
  45384. /**
  45385. * The yy coefficients of the spherical polynomial
  45386. */
  45387. this.yy = BABYLON.Vector3.Zero();
  45388. /**
  45389. * The zz coefficients of the spherical polynomial
  45390. */
  45391. this.zz = BABYLON.Vector3.Zero();
  45392. /**
  45393. * The xy coefficients of the spherical polynomial
  45394. */
  45395. this.xy = BABYLON.Vector3.Zero();
  45396. /**
  45397. * The yz coefficients of the spherical polynomial
  45398. */
  45399. this.yz = BABYLON.Vector3.Zero();
  45400. /**
  45401. * The zx coefficients of the spherical polynomial
  45402. */
  45403. this.zx = BABYLON.Vector3.Zero();
  45404. }
  45405. /**
  45406. * Adds an ambient color to the spherical polynomial
  45407. * @param color the color to add
  45408. */
  45409. SphericalPolynomial.prototype.addAmbient = function (color) {
  45410. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  45411. this.xx = this.xx.add(colorVector);
  45412. this.yy = this.yy.add(colorVector);
  45413. this.zz = this.zz.add(colorVector);
  45414. };
  45415. /**
  45416. * Scales the spherical polynomial by the given amount
  45417. * @param scale the amount to scale
  45418. */
  45419. SphericalPolynomial.prototype.scale = function (scale) {
  45420. this.x = this.x.scale(scale);
  45421. this.y = this.y.scale(scale);
  45422. this.z = this.z.scale(scale);
  45423. this.xx = this.xx.scale(scale);
  45424. this.yy = this.yy.scale(scale);
  45425. this.zz = this.zz.scale(scale);
  45426. this.yz = this.yz.scale(scale);
  45427. this.zx = this.zx.scale(scale);
  45428. this.xy = this.xy.scale(scale);
  45429. };
  45430. /**
  45431. * Gets the spherical polynomial from harmonics
  45432. * @param harmonics the spherical harmonics
  45433. * @returns the spherical polynomial
  45434. */
  45435. SphericalPolynomial.FromHarmonics = function (harmonics) {
  45436. var result = new SphericalPolynomial();
  45437. result.x = harmonics.l11.scale(1.02333);
  45438. result.y = harmonics.l1_1.scale(1.02333);
  45439. result.z = harmonics.l10.scale(1.02333);
  45440. result.xx = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).add(harmonics.lL22.scale(0.429043));
  45441. result.yy = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).subtract(harmonics.lL22.scale(0.429043));
  45442. result.zz = harmonics.l00.scale(0.886277).add(harmonics.l20.scale(0.495417));
  45443. result.yz = harmonics.l2_1.scale(0.858086);
  45444. result.zx = harmonics.l21.scale(0.858086);
  45445. result.xy = harmonics.l2_2.scale(0.858086);
  45446. result.scale(1.0 / Math.PI);
  45447. return result;
  45448. };
  45449. /**
  45450. * Constructs a spherical polynomial from an array.
  45451. * @param data defines the 9x3 coefficients (x, y, z, xx, yy, zz, yz, zx, xy)
  45452. * @returns the spherical polynomial
  45453. */
  45454. SphericalPolynomial.FromArray = function (data) {
  45455. var sp = new SphericalPolynomial();
  45456. BABYLON.Vector3.FromArrayToRef(data[0], 0, sp.x);
  45457. BABYLON.Vector3.FromArrayToRef(data[1], 0, sp.y);
  45458. BABYLON.Vector3.FromArrayToRef(data[2], 0, sp.z);
  45459. BABYLON.Vector3.FromArrayToRef(data[3], 0, sp.xx);
  45460. BABYLON.Vector3.FromArrayToRef(data[4], 0, sp.yy);
  45461. BABYLON.Vector3.FromArrayToRef(data[5], 0, sp.zz);
  45462. BABYLON.Vector3.FromArrayToRef(data[6], 0, sp.yz);
  45463. BABYLON.Vector3.FromArrayToRef(data[7], 0, sp.zx);
  45464. BABYLON.Vector3.FromArrayToRef(data[8], 0, sp.xy);
  45465. return sp;
  45466. };
  45467. return SphericalPolynomial;
  45468. }());
  45469. BABYLON.SphericalPolynomial = SphericalPolynomial;
  45470. /**
  45471. * Class representing spherical harmonics coefficients to the 3rd degree
  45472. */
  45473. var SphericalHarmonics = /** @class */ (function () {
  45474. function SphericalHarmonics() {
  45475. /**
  45476. * The l0,0 coefficients of the spherical harmonics
  45477. */
  45478. this.l00 = BABYLON.Vector3.Zero();
  45479. /**
  45480. * The l1,-1 coefficients of the spherical harmonics
  45481. */
  45482. this.l1_1 = BABYLON.Vector3.Zero();
  45483. /**
  45484. * The l1,0 coefficients of the spherical harmonics
  45485. */
  45486. this.l10 = BABYLON.Vector3.Zero();
  45487. /**
  45488. * The l1,1 coefficients of the spherical harmonics
  45489. */
  45490. this.l11 = BABYLON.Vector3.Zero();
  45491. /**
  45492. * The l2,-2 coefficients of the spherical harmonics
  45493. */
  45494. this.l2_2 = BABYLON.Vector3.Zero();
  45495. /**
  45496. * The l2,-1 coefficients of the spherical harmonics
  45497. */
  45498. this.l2_1 = BABYLON.Vector3.Zero();
  45499. /**
  45500. * The l2,0 coefficients of the spherical harmonics
  45501. */
  45502. this.l20 = BABYLON.Vector3.Zero();
  45503. /**
  45504. * The l2,1 coefficients of the spherical harmonics
  45505. */
  45506. this.l21 = BABYLON.Vector3.Zero();
  45507. /**
  45508. * The l2,2 coefficients of the spherical harmonics
  45509. */
  45510. this.lL22 = BABYLON.Vector3.Zero();
  45511. }
  45512. /**
  45513. * Adds a light to the spherical harmonics
  45514. * @param direction the direction of the light
  45515. * @param color the color of the light
  45516. * @param deltaSolidAngle the delta solid angle of the light
  45517. */
  45518. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  45519. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  45520. var c = colorVector.scale(deltaSolidAngle);
  45521. this.l00 = this.l00.add(c.scale(0.282095));
  45522. this.l1_1 = this.l1_1.add(c.scale(0.488603 * direction.y));
  45523. this.l10 = this.l10.add(c.scale(0.488603 * direction.z));
  45524. this.l11 = this.l11.add(c.scale(0.488603 * direction.x));
  45525. this.l2_2 = this.l2_2.add(c.scale(1.092548 * direction.x * direction.y));
  45526. this.l2_1 = this.l2_1.add(c.scale(1.092548 * direction.y * direction.z));
  45527. this.l21 = this.l21.add(c.scale(1.092548 * direction.x * direction.z));
  45528. this.l20 = this.l20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  45529. this.lL22 = this.lL22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  45530. };
  45531. /**
  45532. * Scales the spherical harmonics by the given amount
  45533. * @param scale the amount to scale
  45534. */
  45535. SphericalHarmonics.prototype.scale = function (scale) {
  45536. this.l00 = this.l00.scale(scale);
  45537. this.l1_1 = this.l1_1.scale(scale);
  45538. this.l10 = this.l10.scale(scale);
  45539. this.l11 = this.l11.scale(scale);
  45540. this.l2_2 = this.l2_2.scale(scale);
  45541. this.l2_1 = this.l2_1.scale(scale);
  45542. this.l20 = this.l20.scale(scale);
  45543. this.l21 = this.l21.scale(scale);
  45544. this.lL22 = this.lL22.scale(scale);
  45545. };
  45546. /**
  45547. * Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  45548. *
  45549. * ```
  45550. * E_lm = A_l * L_lm
  45551. * ```
  45552. *
  45553. * In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  45554. * This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  45555. * the scaling factors are given in equation 9.
  45556. */
  45557. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  45558. // Constant (Band 0)
  45559. this.l00 = this.l00.scale(3.141593);
  45560. // Linear (Band 1)
  45561. this.l1_1 = this.l1_1.scale(2.094395);
  45562. this.l10 = this.l10.scale(2.094395);
  45563. this.l11 = this.l11.scale(2.094395);
  45564. // Quadratic (Band 2)
  45565. this.l2_2 = this.l2_2.scale(0.785398);
  45566. this.l2_1 = this.l2_1.scale(0.785398);
  45567. this.l20 = this.l20.scale(0.785398);
  45568. this.l21 = this.l21.scale(0.785398);
  45569. this.lL22 = this.lL22.scale(0.785398);
  45570. };
  45571. /**
  45572. * Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  45573. *
  45574. * ```
  45575. * L = (1/pi) * E * rho
  45576. * ```
  45577. *
  45578. * This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  45579. */
  45580. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  45581. this.scale(1.0 / Math.PI);
  45582. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  45583. // (The pixel shader must apply albedo after texture fetches, etc).
  45584. };
  45585. /**
  45586. * Gets the spherical harmonics from polynomial
  45587. * @param polynomial the spherical polynomial
  45588. * @returns the spherical harmonics
  45589. */
  45590. SphericalHarmonics.FromPolynomial = function (polynomial) {
  45591. var result = new SphericalHarmonics();
  45592. result.l00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  45593. result.l1_1 = polynomial.y.scale(0.977204);
  45594. result.l10 = polynomial.z.scale(0.977204);
  45595. result.l11 = polynomial.x.scale(0.977204);
  45596. result.l2_2 = polynomial.xy.scale(1.16538);
  45597. result.l2_1 = polynomial.yz.scale(1.16538);
  45598. result.l20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  45599. result.l21 = polynomial.zx.scale(1.16538);
  45600. result.lL22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  45601. result.scale(Math.PI);
  45602. return result;
  45603. };
  45604. /**
  45605. * Constructs a spherical harmonics from an array.
  45606. * @param data defines the 9x3 coefficients (l00, l1-1, l10, l11, l2-2, l2-1, l20, l21, l22)
  45607. * @returns the spherical harmonics
  45608. */
  45609. SphericalHarmonics.FromArray = function (data) {
  45610. var sh = new SphericalHarmonics();
  45611. BABYLON.Vector3.FromArrayToRef(data[0], 0, sh.l00);
  45612. BABYLON.Vector3.FromArrayToRef(data[1], 0, sh.l1_1);
  45613. BABYLON.Vector3.FromArrayToRef(data[2], 0, sh.l10);
  45614. BABYLON.Vector3.FromArrayToRef(data[3], 0, sh.l11);
  45615. BABYLON.Vector3.FromArrayToRef(data[4], 0, sh.l2_2);
  45616. BABYLON.Vector3.FromArrayToRef(data[5], 0, sh.l2_1);
  45617. BABYLON.Vector3.FromArrayToRef(data[6], 0, sh.l20);
  45618. BABYLON.Vector3.FromArrayToRef(data[7], 0, sh.l21);
  45619. BABYLON.Vector3.FromArrayToRef(data[8], 0, sh.lL22);
  45620. return sh;
  45621. };
  45622. return SphericalHarmonics;
  45623. }());
  45624. BABYLON.SphericalHarmonics = SphericalHarmonics;
  45625. })(BABYLON || (BABYLON = {}));
  45626. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  45627. var BABYLON;
  45628. (function (BABYLON) {
  45629. var FileFaceOrientation = /** @class */ (function () {
  45630. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  45631. this.name = name;
  45632. this.worldAxisForNormal = worldAxisForNormal;
  45633. this.worldAxisForFileX = worldAxisForFileX;
  45634. this.worldAxisForFileY = worldAxisForFileY;
  45635. }
  45636. return FileFaceOrientation;
  45637. }());
  45638. /**
  45639. * Helper class dealing with the extraction of spherical polynomial dataArray
  45640. * from a cube map.
  45641. */
  45642. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  45643. function CubeMapToSphericalPolynomialTools() {
  45644. }
  45645. /**
  45646. * Converts a texture to the according Spherical Polynomial data.
  45647. * This extracts the first 3 orders only as they are the only one used in the lighting.
  45648. *
  45649. * @param texture The texture to extract the information from.
  45650. * @return The Spherical Polynomial data.
  45651. */
  45652. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  45653. if (!texture.isCube) {
  45654. // Only supports cube Textures currently.
  45655. return null;
  45656. }
  45657. var size = texture.getSize().width;
  45658. var right = texture.readPixels(0);
  45659. var left = texture.readPixels(1);
  45660. var up;
  45661. var down;
  45662. if (texture.isRenderTarget) {
  45663. up = texture.readPixels(3);
  45664. down = texture.readPixels(2);
  45665. }
  45666. else {
  45667. up = texture.readPixels(2);
  45668. down = texture.readPixels(3);
  45669. }
  45670. var front = texture.readPixels(4);
  45671. var back = texture.readPixels(5);
  45672. var gammaSpace = texture.gammaSpace;
  45673. // Always read as RGBA.
  45674. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  45675. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  45676. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  45677. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  45678. }
  45679. var cubeInfo = {
  45680. size: size,
  45681. right: right,
  45682. left: left,
  45683. up: up,
  45684. down: down,
  45685. front: front,
  45686. back: back,
  45687. format: format,
  45688. type: type,
  45689. gammaSpace: gammaSpace,
  45690. };
  45691. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  45692. };
  45693. /**
  45694. * Converts a cubemap to the according Spherical Polynomial data.
  45695. * This extracts the first 3 orders only as they are the only one used in the lighting.
  45696. *
  45697. * @param cubeInfo The Cube map to extract the information from.
  45698. * @return The Spherical Polynomial data.
  45699. */
  45700. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  45701. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  45702. var totalSolidAngle = 0.0;
  45703. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  45704. var du = 2.0 / cubeInfo.size;
  45705. var dv = du;
  45706. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  45707. var minUV = du * 0.5 - 1.0;
  45708. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  45709. var fileFace = this.FileFaces[faceIndex];
  45710. var dataArray = cubeInfo[fileFace.name];
  45711. var v = minUV;
  45712. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  45713. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  45714. // Because SP is still linear, so summation is fine in that basis.
  45715. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  45716. for (var y = 0; y < cubeInfo.size; y++) {
  45717. var u = minUV;
  45718. for (var x = 0; x < cubeInfo.size; x++) {
  45719. // World direction (not normalised)
  45720. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  45721. worldDirection.normalize();
  45722. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  45723. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  45724. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  45725. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  45726. // Handle Integer types.
  45727. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  45728. r /= 255;
  45729. g /= 255;
  45730. b /= 255;
  45731. }
  45732. // Handle Gamma space textures.
  45733. if (cubeInfo.gammaSpace) {
  45734. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  45735. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  45736. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  45737. }
  45738. var color = new BABYLON.Color3(r, g, b);
  45739. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  45740. totalSolidAngle += deltaSolidAngle;
  45741. u += du;
  45742. }
  45743. v += dv;
  45744. }
  45745. }
  45746. // Solid angle for entire sphere is 4*pi
  45747. var sphereSolidAngle = 4.0 * Math.PI;
  45748. // Adjust the solid angle to allow for how many faces we processed.
  45749. var facesProcessed = 6.0;
  45750. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  45751. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  45752. // This is needed because the numerical integration over the cube uses a
  45753. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  45754. // and also to compensate for accumulative error due to float precision in the summation.
  45755. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  45756. sphericalHarmonics.scale(correctionFactor);
  45757. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  45758. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  45759. return BABYLON.SphericalPolynomial.FromHarmonics(sphericalHarmonics);
  45760. };
  45761. CubeMapToSphericalPolynomialTools.FileFaces = [
  45762. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  45763. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  45764. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  45765. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  45766. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  45767. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  45768. ];
  45769. return CubeMapToSphericalPolynomialTools;
  45770. }());
  45771. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  45772. })(BABYLON || (BABYLON = {}));
  45773. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  45774. var BABYLON;
  45775. (function (BABYLON) {
  45776. /**
  45777. * Manages the defines for the PBR Material.
  45778. * @hiddenChildren
  45779. */
  45780. var PBRMaterialDefines = /** @class */ (function (_super) {
  45781. __extends(PBRMaterialDefines, _super);
  45782. /**
  45783. * Initializes the PBR Material defines.
  45784. */
  45785. function PBRMaterialDefines() {
  45786. var _this = _super.call(this) || this;
  45787. _this.PBR = true;
  45788. _this.MAINUV1 = false;
  45789. _this.MAINUV2 = false;
  45790. _this.UV1 = false;
  45791. _this.UV2 = false;
  45792. _this.ALBEDO = false;
  45793. _this.ALBEDODIRECTUV = 0;
  45794. _this.VERTEXCOLOR = false;
  45795. _this.AMBIENT = false;
  45796. _this.AMBIENTDIRECTUV = 0;
  45797. _this.AMBIENTINGRAYSCALE = false;
  45798. _this.OPACITY = false;
  45799. _this.VERTEXALPHA = false;
  45800. _this.OPACITYDIRECTUV = 0;
  45801. _this.OPACITYRGB = false;
  45802. _this.ALPHATEST = false;
  45803. _this.DEPTHPREPASS = false;
  45804. _this.ALPHABLEND = false;
  45805. _this.ALPHAFROMALBEDO = false;
  45806. _this.ALPHATESTVALUE = "0.5";
  45807. _this.SPECULAROVERALPHA = false;
  45808. _this.RADIANCEOVERALPHA = false;
  45809. _this.ALPHAFRESNEL = false;
  45810. _this.LINEARALPHAFRESNEL = false;
  45811. _this.PREMULTIPLYALPHA = false;
  45812. _this.EMISSIVE = false;
  45813. _this.EMISSIVEDIRECTUV = 0;
  45814. _this.REFLECTIVITY = false;
  45815. _this.REFLECTIVITYDIRECTUV = 0;
  45816. _this.SPECULARTERM = false;
  45817. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  45818. _this.MICROSURFACEAUTOMATIC = false;
  45819. _this.LODBASEDMICROSFURACE = false;
  45820. _this.MICROSURFACEMAP = false;
  45821. _this.MICROSURFACEMAPDIRECTUV = 0;
  45822. _this.METALLICWORKFLOW = false;
  45823. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  45824. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  45825. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  45826. _this.AOSTOREINMETALMAPRED = false;
  45827. _this.ENVIRONMENTBRDF = false;
  45828. _this.NORMAL = false;
  45829. _this.TANGENT = false;
  45830. _this.BUMP = false;
  45831. _this.BUMPDIRECTUV = 0;
  45832. _this.OBJECTSPACE_NORMALMAP = false;
  45833. _this.PARALLAX = false;
  45834. _this.PARALLAXOCCLUSION = false;
  45835. _this.NORMALXYSCALE = true;
  45836. _this.LIGHTMAP = false;
  45837. _this.LIGHTMAPDIRECTUV = 0;
  45838. _this.USELIGHTMAPASSHADOWMAP = false;
  45839. _this.GAMMALIGHTMAP = false;
  45840. _this.REFLECTION = false;
  45841. _this.REFLECTIONMAP_3D = false;
  45842. _this.REFLECTIONMAP_SPHERICAL = false;
  45843. _this.REFLECTIONMAP_PLANAR = false;
  45844. _this.REFLECTIONMAP_CUBIC = false;
  45845. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  45846. _this.REFLECTIONMAP_PROJECTION = false;
  45847. _this.REFLECTIONMAP_SKYBOX = false;
  45848. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  45849. _this.REFLECTIONMAP_EXPLICIT = false;
  45850. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  45851. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  45852. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  45853. _this.INVERTCUBICMAP = false;
  45854. _this.USESPHERICALFROMREFLECTIONMAP = false;
  45855. _this.USESPHERICALINVERTEX = false;
  45856. _this.REFLECTIONMAP_OPPOSITEZ = false;
  45857. _this.LODINREFLECTIONALPHA = false;
  45858. _this.GAMMAREFLECTION = false;
  45859. _this.RGBDREFLECTION = false;
  45860. _this.RADIANCEOCCLUSION = false;
  45861. _this.HORIZONOCCLUSION = false;
  45862. _this.REFRACTION = false;
  45863. _this.REFRACTIONMAP_3D = false;
  45864. _this.REFRACTIONMAP_OPPOSITEZ = false;
  45865. _this.LODINREFRACTIONALPHA = false;
  45866. _this.GAMMAREFRACTION = false;
  45867. _this.RGBDREFRACTION = false;
  45868. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  45869. _this.INSTANCES = false;
  45870. _this.NUM_BONE_INFLUENCERS = 0;
  45871. _this.BonesPerMesh = 0;
  45872. _this.BONETEXTURE = false;
  45873. _this.NONUNIFORMSCALING = false;
  45874. _this.MORPHTARGETS = false;
  45875. _this.MORPHTARGETS_NORMAL = false;
  45876. _this.MORPHTARGETS_TANGENT = false;
  45877. _this.NUM_MORPH_INFLUENCERS = 0;
  45878. _this.IMAGEPROCESSING = false;
  45879. _this.VIGNETTE = false;
  45880. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  45881. _this.VIGNETTEBLENDMODEOPAQUE = false;
  45882. _this.TONEMAPPING = false;
  45883. _this.TONEMAPPING_ACES = false;
  45884. _this.CONTRAST = false;
  45885. _this.COLORCURVES = false;
  45886. _this.COLORGRADING = false;
  45887. _this.COLORGRADING3D = false;
  45888. _this.SAMPLER3DGREENDEPTH = false;
  45889. _this.SAMPLER3DBGRMAP = false;
  45890. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  45891. _this.EXPOSURE = false;
  45892. _this.USEPHYSICALLIGHTFALLOFF = false;
  45893. _this.USEGLTFLIGHTFALLOFF = false;
  45894. _this.TWOSIDEDLIGHTING = false;
  45895. _this.SHADOWFLOAT = false;
  45896. _this.CLIPPLANE = false;
  45897. _this.CLIPPLANE2 = false;
  45898. _this.CLIPPLANE3 = false;
  45899. _this.CLIPPLANE4 = false;
  45900. _this.POINTSIZE = false;
  45901. _this.FOG = false;
  45902. _this.LOGARITHMICDEPTH = false;
  45903. _this.FORCENORMALFORWARD = false;
  45904. _this.SPECULARAA = false;
  45905. _this.UNLIT = false;
  45906. _this.rebuild();
  45907. return _this;
  45908. }
  45909. /**
  45910. * Resets the PBR Material defines.
  45911. */
  45912. PBRMaterialDefines.prototype.reset = function () {
  45913. _super.prototype.reset.call(this);
  45914. this.ALPHATESTVALUE = "0.5";
  45915. this.PBR = true;
  45916. };
  45917. return PBRMaterialDefines;
  45918. }(BABYLON.MaterialDefines));
  45919. /**
  45920. * The Physically based material base class of BJS.
  45921. *
  45922. * This offers the main features of a standard PBR material.
  45923. * For more information, please refer to the documentation :
  45924. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  45925. */
  45926. var PBRBaseMaterial = /** @class */ (function (_super) {
  45927. __extends(PBRBaseMaterial, _super);
  45928. /**
  45929. * Instantiates a new PBRMaterial instance.
  45930. *
  45931. * @param name The material name
  45932. * @param scene The scene the material will be use in.
  45933. */
  45934. function PBRBaseMaterial(name, scene) {
  45935. var _this = _super.call(this, name, scene) || this;
  45936. /**
  45937. * Intensity of the direct lights e.g. the four lights available in your scene.
  45938. * This impacts both the direct diffuse and specular highlights.
  45939. */
  45940. _this._directIntensity = 1.0;
  45941. /**
  45942. * Intensity of the emissive part of the material.
  45943. * This helps controlling the emissive effect without modifying the emissive color.
  45944. */
  45945. _this._emissiveIntensity = 1.0;
  45946. /**
  45947. * Intensity of the environment e.g. how much the environment will light the object
  45948. * either through harmonics for rough material or through the refelction for shiny ones.
  45949. */
  45950. _this._environmentIntensity = 1.0;
  45951. /**
  45952. * This is a special control allowing the reduction of the specular highlights coming from the
  45953. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  45954. */
  45955. _this._specularIntensity = 1.0;
  45956. /**
  45957. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  45958. */
  45959. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  45960. /**
  45961. * Debug Control allowing disabling the bump map on this material.
  45962. */
  45963. _this._disableBumpMap = false;
  45964. /**
  45965. * AKA Occlusion Texture Intensity in other nomenclature.
  45966. */
  45967. _this._ambientTextureStrength = 1.0;
  45968. /**
  45969. * Defines how much the AO map is occluding the analytical lights (point spot...).
  45970. * 1 means it completely occludes it
  45971. * 0 mean it has no impact
  45972. */
  45973. _this._ambientTextureImpactOnAnalyticalLights = BABYLON.PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS;
  45974. /**
  45975. * The color of a material in ambient lighting.
  45976. */
  45977. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  45978. /**
  45979. * AKA Diffuse Color in other nomenclature.
  45980. */
  45981. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  45982. /**
  45983. * AKA Specular Color in other nomenclature.
  45984. */
  45985. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  45986. /**
  45987. * The color applied when light is reflected from a material.
  45988. */
  45989. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  45990. /**
  45991. * The color applied when light is emitted from a material.
  45992. */
  45993. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  45994. /**
  45995. * AKA Glossiness in other nomenclature.
  45996. */
  45997. _this._microSurface = 0.9;
  45998. /**
  45999. * source material index of refraction (IOR)' / 'destination material IOR.
  46000. */
  46001. _this._indexOfRefraction = 0.66;
  46002. /**
  46003. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  46004. */
  46005. _this._invertRefractionY = false;
  46006. /**
  46007. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  46008. * Materials half opaque for instance using refraction could benefit from this control.
  46009. */
  46010. _this._linkRefractionWithTransparency = false;
  46011. /**
  46012. * Specifies that the material will use the light map as a show map.
  46013. */
  46014. _this._useLightmapAsShadowmap = false;
  46015. /**
  46016. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  46017. * makes the reflect vector face the model (under horizon).
  46018. */
  46019. _this._useHorizonOcclusion = true;
  46020. /**
  46021. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  46022. * too much the area relying on ambient texture to define their ambient occlusion.
  46023. */
  46024. _this._useRadianceOcclusion = true;
  46025. /**
  46026. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  46027. */
  46028. _this._useAlphaFromAlbedoTexture = false;
  46029. /**
  46030. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  46031. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  46032. */
  46033. _this._useSpecularOverAlpha = true;
  46034. /**
  46035. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  46036. */
  46037. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  46038. /**
  46039. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  46040. */
  46041. _this._useRoughnessFromMetallicTextureAlpha = true;
  46042. /**
  46043. * Specifies if the metallic texture contains the roughness information in its green channel.
  46044. */
  46045. _this._useRoughnessFromMetallicTextureGreen = false;
  46046. /**
  46047. * Specifies if the metallic texture contains the metallness information in its blue channel.
  46048. */
  46049. _this._useMetallnessFromMetallicTextureBlue = false;
  46050. /**
  46051. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  46052. */
  46053. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  46054. /**
  46055. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  46056. */
  46057. _this._useAmbientInGrayScale = false;
  46058. /**
  46059. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  46060. * The material will try to infer what glossiness each pixel should be.
  46061. */
  46062. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  46063. /**
  46064. * Defines the falloff type used in this material.
  46065. * It by default is Physical.
  46066. */
  46067. _this._lightFalloff = PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  46068. /**
  46069. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  46070. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  46071. */
  46072. _this._useRadianceOverAlpha = true;
  46073. /**
  46074. * Allows using an object space normal map (instead of tangent space).
  46075. */
  46076. _this._useObjectSpaceNormalMap = false;
  46077. /**
  46078. * Allows using the bump map in parallax mode.
  46079. */
  46080. _this._useParallax = false;
  46081. /**
  46082. * Allows using the bump map in parallax occlusion mode.
  46083. */
  46084. _this._useParallaxOcclusion = false;
  46085. /**
  46086. * Controls the scale bias of the parallax mode.
  46087. */
  46088. _this._parallaxScaleBias = 0.05;
  46089. /**
  46090. * If sets to true, disables all the lights affecting the material.
  46091. */
  46092. _this._disableLighting = false;
  46093. /**
  46094. * Number of Simultaneous lights allowed on the material.
  46095. */
  46096. _this._maxSimultaneousLights = 4;
  46097. /**
  46098. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  46099. */
  46100. _this._invertNormalMapX = false;
  46101. /**
  46102. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  46103. */
  46104. _this._invertNormalMapY = false;
  46105. /**
  46106. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  46107. */
  46108. _this._twoSidedLighting = false;
  46109. /**
  46110. * Defines the alpha limits in alpha test mode.
  46111. */
  46112. _this._alphaCutOff = 0.4;
  46113. /**
  46114. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  46115. */
  46116. _this._forceAlphaTest = false;
  46117. /**
  46118. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  46119. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  46120. */
  46121. _this._useAlphaFresnel = false;
  46122. /**
  46123. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  46124. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  46125. */
  46126. _this._useLinearAlphaFresnel = false;
  46127. /**
  46128. * The transparency mode of the material.
  46129. */
  46130. _this._transparencyMode = null;
  46131. /**
  46132. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  46133. * from cos thetav and roughness:
  46134. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  46135. */
  46136. _this._environmentBRDFTexture = null;
  46137. /**
  46138. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  46139. */
  46140. _this._forceIrradianceInFragment = false;
  46141. /**
  46142. * Force normal to face away from face.
  46143. */
  46144. _this._forceNormalForward = false;
  46145. /**
  46146. * Enables specular anti aliasing in the PBR shader.
  46147. * It will both interacts on the Geometry for analytical and IBL lighting.
  46148. * It also prefilter the roughness map based on the bump values.
  46149. */
  46150. _this._enableSpecularAntiAliasing = false;
  46151. /**
  46152. * Stores the available render targets.
  46153. */
  46154. _this._renderTargets = new BABYLON.SmartArray(16);
  46155. /**
  46156. * Sets the global ambient color for the material used in lighting calculations.
  46157. */
  46158. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  46159. /**
  46160. * If set to true, no lighting calculations will be applied.
  46161. */
  46162. _this._unlit = false;
  46163. // Setup the default processing configuration to the scene.
  46164. _this._attachImageProcessingConfiguration(null);
  46165. _this.getRenderTargetTextures = function () {
  46166. _this._renderTargets.reset();
  46167. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  46168. _this._renderTargets.push(_this._reflectionTexture);
  46169. }
  46170. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  46171. _this._renderTargets.push(_this._refractionTexture);
  46172. }
  46173. return _this._renderTargets;
  46174. };
  46175. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  46176. return _this;
  46177. }
  46178. /**
  46179. * Attaches a new image processing configuration to the PBR Material.
  46180. * @param configuration
  46181. */
  46182. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  46183. var _this = this;
  46184. if (configuration === this._imageProcessingConfiguration) {
  46185. return;
  46186. }
  46187. // Detaches observer.
  46188. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  46189. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  46190. }
  46191. // Pick the scene configuration if needed.
  46192. if (!configuration) {
  46193. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  46194. }
  46195. else {
  46196. this._imageProcessingConfiguration = configuration;
  46197. }
  46198. // Attaches observer.
  46199. if (this._imageProcessingConfiguration) {
  46200. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  46201. _this._markAllSubMeshesAsImageProcessingDirty();
  46202. });
  46203. }
  46204. };
  46205. Object.defineProperty(PBRBaseMaterial.prototype, "hasRenderTargetTextures", {
  46206. /**
  46207. * Gets a boolean indicating that current material needs to register RTT
  46208. */
  46209. get: function () {
  46210. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  46211. return true;
  46212. }
  46213. if (BABYLON.StandardMaterial.RefractionTextureEnabled && this._refractionTexture && this._refractionTexture.isRenderTarget) {
  46214. return true;
  46215. }
  46216. return false;
  46217. },
  46218. enumerable: true,
  46219. configurable: true
  46220. });
  46221. /**
  46222. * Gets the name of the material class.
  46223. */
  46224. PBRBaseMaterial.prototype.getClassName = function () {
  46225. return "PBRBaseMaterial";
  46226. };
  46227. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  46228. /**
  46229. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  46230. */
  46231. get: function () {
  46232. return this._useLogarithmicDepth;
  46233. },
  46234. /**
  46235. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  46236. */
  46237. set: function (value) {
  46238. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  46239. },
  46240. enumerable: true,
  46241. configurable: true
  46242. });
  46243. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  46244. /**
  46245. * Gets the current transparency mode.
  46246. */
  46247. get: function () {
  46248. return this._transparencyMode;
  46249. },
  46250. /**
  46251. * Sets the transparency mode of the material.
  46252. *
  46253. * | Value | Type | Description |
  46254. * | ----- | ----------------------------------- | ----------- |
  46255. * | 0 | OPAQUE | |
  46256. * | 1 | ALPHATEST | |
  46257. * | 2 | ALPHABLEND | |
  46258. * | 3 | ALPHATESTANDBLEND | |
  46259. *
  46260. */
  46261. set: function (value) {
  46262. if (this._transparencyMode === value) {
  46263. return;
  46264. }
  46265. this._transparencyMode = value;
  46266. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  46267. this._markAllSubMeshesAsTexturesAndMiscDirty();
  46268. },
  46269. enumerable: true,
  46270. configurable: true
  46271. });
  46272. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  46273. /**
  46274. * Returns true if alpha blending should be disabled.
  46275. */
  46276. get: function () {
  46277. return (this._linkRefractionWithTransparency ||
  46278. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  46279. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  46280. },
  46281. enumerable: true,
  46282. configurable: true
  46283. });
  46284. /**
  46285. * Specifies whether or not this material should be rendered in alpha blend mode.
  46286. */
  46287. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  46288. if (this._disableAlphaBlending) {
  46289. return false;
  46290. }
  46291. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  46292. };
  46293. /**
  46294. * Specifies if the mesh will require alpha blending.
  46295. * @param mesh - BJS mesh.
  46296. */
  46297. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  46298. if (this._disableAlphaBlending) {
  46299. return false;
  46300. }
  46301. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  46302. };
  46303. /**
  46304. * Specifies whether or not this material should be rendered in alpha test mode.
  46305. */
  46306. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  46307. if (this._forceAlphaTest) {
  46308. return true;
  46309. }
  46310. if (this._linkRefractionWithTransparency) {
  46311. return false;
  46312. }
  46313. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  46314. };
  46315. /**
  46316. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  46317. */
  46318. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  46319. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  46320. };
  46321. /**
  46322. * Gets the texture used for the alpha test.
  46323. */
  46324. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  46325. return this._albedoTexture;
  46326. };
  46327. /**
  46328. * Specifies that the submesh is ready to be used.
  46329. * @param mesh - BJS mesh.
  46330. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  46331. * @param useInstances - Specifies that instances should be used.
  46332. * @returns - boolean indicating that the submesh is ready or not.
  46333. */
  46334. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  46335. if (subMesh.effect && this.isFrozen) {
  46336. if (this._wasPreviouslyReady) {
  46337. return true;
  46338. }
  46339. }
  46340. if (!subMesh._materialDefines) {
  46341. subMesh._materialDefines = new PBRMaterialDefines();
  46342. }
  46343. var defines = subMesh._materialDefines;
  46344. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  46345. if (defines._renderId === this.getScene().getRenderId()) {
  46346. return true;
  46347. }
  46348. }
  46349. var scene = this.getScene();
  46350. var engine = scene.getEngine();
  46351. if (defines._areTexturesDirty) {
  46352. if (scene.texturesEnabled) {
  46353. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  46354. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  46355. return false;
  46356. }
  46357. }
  46358. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  46359. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  46360. return false;
  46361. }
  46362. }
  46363. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  46364. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  46365. return false;
  46366. }
  46367. }
  46368. var reflectionTexture = this._getReflectionTexture();
  46369. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  46370. if (!reflectionTexture.isReadyOrNotBlocking()) {
  46371. return false;
  46372. }
  46373. }
  46374. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  46375. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  46376. return false;
  46377. }
  46378. }
  46379. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  46380. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  46381. return false;
  46382. }
  46383. }
  46384. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  46385. if (this._metallicTexture) {
  46386. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  46387. return false;
  46388. }
  46389. }
  46390. else if (this._reflectivityTexture) {
  46391. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  46392. return false;
  46393. }
  46394. }
  46395. if (this._microSurfaceTexture) {
  46396. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  46397. return false;
  46398. }
  46399. }
  46400. }
  46401. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  46402. // Bump texture cannot be not blocking.
  46403. if (!this._bumpTexture.isReady()) {
  46404. return false;
  46405. }
  46406. }
  46407. var refractionTexture = this._getRefractionTexture();
  46408. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  46409. if (!refractionTexture.isReadyOrNotBlocking()) {
  46410. return false;
  46411. }
  46412. }
  46413. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  46414. // This is blocking.
  46415. if (!this._environmentBRDFTexture.isReady()) {
  46416. return false;
  46417. }
  46418. }
  46419. }
  46420. }
  46421. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  46422. if (!this._imageProcessingConfiguration.isReady()) {
  46423. return false;
  46424. }
  46425. }
  46426. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  46427. mesh.createNormals(true);
  46428. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  46429. }
  46430. var previousEffect = subMesh.effect;
  46431. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  46432. if (effect) {
  46433. // Use previous effect while new one is compiling
  46434. if (this.allowShaderHotSwapping && previousEffect && !effect.isReady()) {
  46435. effect = previousEffect;
  46436. defines.markAsUnprocessed();
  46437. }
  46438. else {
  46439. scene.resetCachedMaterial();
  46440. subMesh.setEffect(effect, defines);
  46441. this.buildUniformLayout();
  46442. }
  46443. }
  46444. if (!subMesh.effect || !subMesh.effect.isReady()) {
  46445. return false;
  46446. }
  46447. defines._renderId = scene.getRenderId();
  46448. this._wasPreviouslyReady = true;
  46449. return true;
  46450. };
  46451. /**
  46452. * Specifies if the material uses metallic roughness workflow.
  46453. * @returns boolean specifiying if the material uses metallic roughness workflow.
  46454. */
  46455. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  46456. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  46457. return true;
  46458. }
  46459. return false;
  46460. };
  46461. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  46462. if (onCompiled === void 0) { onCompiled = null; }
  46463. if (onError === void 0) { onError = null; }
  46464. if (useInstances === void 0) { useInstances = null; }
  46465. if (useClipPlane === void 0) { useClipPlane = null; }
  46466. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  46467. if (!defines.isDirty) {
  46468. return null;
  46469. }
  46470. defines.markAsProcessed();
  46471. var scene = this.getScene();
  46472. var engine = scene.getEngine();
  46473. // Fallbacks
  46474. var fallbacks = new BABYLON.EffectFallbacks();
  46475. var fallbackRank = 0;
  46476. if (defines.USESPHERICALINVERTEX) {
  46477. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  46478. }
  46479. if (defines.FOG) {
  46480. fallbacks.addFallback(fallbackRank, "FOG");
  46481. }
  46482. if (defines.SPECULARAA) {
  46483. fallbacks.addFallback(fallbackRank, "SPECULARAA");
  46484. }
  46485. if (defines.POINTSIZE) {
  46486. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  46487. }
  46488. if (defines.LOGARITHMICDEPTH) {
  46489. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  46490. }
  46491. if (defines.PARALLAX) {
  46492. fallbacks.addFallback(fallbackRank, "PARALLAX");
  46493. }
  46494. if (defines.PARALLAXOCCLUSION) {
  46495. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  46496. }
  46497. if (defines.ENVIRONMENTBRDF) {
  46498. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  46499. }
  46500. if (defines.TANGENT) {
  46501. fallbacks.addFallback(fallbackRank++, "TANGENT");
  46502. }
  46503. if (defines.BUMP) {
  46504. fallbacks.addFallback(fallbackRank++, "BUMP");
  46505. }
  46506. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  46507. if (defines.SPECULARTERM) {
  46508. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  46509. }
  46510. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  46511. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  46512. }
  46513. if (defines.LIGHTMAP) {
  46514. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  46515. }
  46516. if (defines.NORMAL) {
  46517. fallbacks.addFallback(fallbackRank++, "NORMAL");
  46518. }
  46519. if (defines.AMBIENT) {
  46520. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  46521. }
  46522. if (defines.EMISSIVE) {
  46523. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  46524. }
  46525. if (defines.VERTEXCOLOR) {
  46526. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  46527. }
  46528. if (defines.NUM_BONE_INFLUENCERS > 0) {
  46529. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  46530. }
  46531. if (defines.MORPHTARGETS) {
  46532. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  46533. }
  46534. //Attributes
  46535. var attribs = [BABYLON.VertexBuffer.PositionKind];
  46536. if (defines.NORMAL) {
  46537. attribs.push(BABYLON.VertexBuffer.NormalKind);
  46538. }
  46539. if (defines.TANGENT) {
  46540. attribs.push(BABYLON.VertexBuffer.TangentKind);
  46541. }
  46542. if (defines.UV1) {
  46543. attribs.push(BABYLON.VertexBuffer.UVKind);
  46544. }
  46545. if (defines.UV2) {
  46546. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  46547. }
  46548. if (defines.VERTEXCOLOR) {
  46549. attribs.push(BABYLON.VertexBuffer.ColorKind);
  46550. }
  46551. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  46552. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  46553. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  46554. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  46555. "vFogInfos", "vFogColor", "pointSize",
  46556. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  46557. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  46558. "mBones",
  46559. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  46560. "vLightingIntensity",
  46561. "logarithmicDepthConstant",
  46562. "vSphericalX", "vSphericalY", "vSphericalZ",
  46563. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  46564. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  46565. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  46566. "vTangentSpaceParams", "boneTextureWidth"
  46567. ];
  46568. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  46569. "bumpSampler", "lightmapSampler", "opacitySampler",
  46570. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  46571. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  46572. "microSurfaceSampler", "environmentBrdfSampler", "boneSampler"];
  46573. var uniformBuffers = ["Material", "Scene"];
  46574. if (BABYLON.ImageProcessingConfiguration) {
  46575. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  46576. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  46577. }
  46578. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  46579. uniformsNames: uniforms,
  46580. uniformBuffersNames: uniformBuffers,
  46581. samplers: samplers,
  46582. defines: defines,
  46583. maxSimultaneousLights: this._maxSimultaneousLights
  46584. });
  46585. var join = defines.toString();
  46586. return engine.createEffect("pbr", {
  46587. attributes: attribs,
  46588. uniformsNames: uniforms,
  46589. uniformBuffersNames: uniformBuffers,
  46590. samplers: samplers,
  46591. defines: join,
  46592. fallbacks: fallbacks,
  46593. onCompiled: onCompiled,
  46594. onError: onError,
  46595. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  46596. }, engine);
  46597. };
  46598. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  46599. if (useInstances === void 0) { useInstances = null; }
  46600. if (useClipPlane === void 0) { useClipPlane = null; }
  46601. var scene = this.getScene();
  46602. var engine = scene.getEngine();
  46603. // Lights
  46604. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  46605. defines._needNormals = true;
  46606. // Textures
  46607. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  46608. if (defines._areTexturesDirty) {
  46609. defines._needUVs = false;
  46610. if (scene.texturesEnabled) {
  46611. if (scene.getEngine().getCaps().textureLOD) {
  46612. defines.LODBASEDMICROSFURACE = true;
  46613. }
  46614. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  46615. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  46616. }
  46617. else {
  46618. defines.ALBEDO = false;
  46619. }
  46620. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  46621. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  46622. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  46623. }
  46624. else {
  46625. defines.AMBIENT = false;
  46626. }
  46627. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  46628. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  46629. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  46630. }
  46631. else {
  46632. defines.OPACITY = false;
  46633. }
  46634. var reflectionTexture = this._getReflectionTexture();
  46635. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  46636. defines.REFLECTION = true;
  46637. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  46638. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  46639. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  46640. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  46641. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  46642. defines.INVERTCUBICMAP = true;
  46643. }
  46644. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  46645. switch (reflectionTexture.coordinatesMode) {
  46646. case BABYLON.Texture.EXPLICIT_MODE:
  46647. defines.REFLECTIONMAP_EXPLICIT = true;
  46648. break;
  46649. case BABYLON.Texture.PLANAR_MODE:
  46650. defines.REFLECTIONMAP_PLANAR = true;
  46651. break;
  46652. case BABYLON.Texture.PROJECTION_MODE:
  46653. defines.REFLECTIONMAP_PROJECTION = true;
  46654. break;
  46655. case BABYLON.Texture.SKYBOX_MODE:
  46656. defines.REFLECTIONMAP_SKYBOX = true;
  46657. break;
  46658. case BABYLON.Texture.SPHERICAL_MODE:
  46659. defines.REFLECTIONMAP_SPHERICAL = true;
  46660. break;
  46661. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  46662. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  46663. break;
  46664. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  46665. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  46666. break;
  46667. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  46668. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  46669. break;
  46670. case BABYLON.Texture.CUBIC_MODE:
  46671. case BABYLON.Texture.INVCUBIC_MODE:
  46672. default:
  46673. defines.REFLECTIONMAP_CUBIC = true;
  46674. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  46675. break;
  46676. }
  46677. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  46678. if (reflectionTexture.sphericalPolynomial) {
  46679. defines.USESPHERICALFROMREFLECTIONMAP = true;
  46680. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  46681. defines.USESPHERICALINVERTEX = false;
  46682. }
  46683. else {
  46684. defines.USESPHERICALINVERTEX = true;
  46685. }
  46686. }
  46687. }
  46688. else {
  46689. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !reflectionTexture.getReflectionTextureMatrix().isIdentity();
  46690. }
  46691. }
  46692. else {
  46693. defines.REFLECTION = false;
  46694. defines.REFLECTIONMAP_3D = false;
  46695. defines.REFLECTIONMAP_SPHERICAL = false;
  46696. defines.REFLECTIONMAP_PLANAR = false;
  46697. defines.REFLECTIONMAP_CUBIC = false;
  46698. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  46699. defines.REFLECTIONMAP_PROJECTION = false;
  46700. defines.REFLECTIONMAP_SKYBOX = false;
  46701. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  46702. defines.REFLECTIONMAP_EXPLICIT = false;
  46703. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  46704. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  46705. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  46706. defines.INVERTCUBICMAP = false;
  46707. defines.USESPHERICALFROMREFLECTIONMAP = false;
  46708. defines.USESPHERICALINVERTEX = false;
  46709. defines.REFLECTIONMAP_OPPOSITEZ = false;
  46710. defines.LODINREFLECTIONALPHA = false;
  46711. defines.GAMMAREFLECTION = false;
  46712. defines.RGBDREFLECTION = false;
  46713. }
  46714. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  46715. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  46716. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  46717. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  46718. }
  46719. else {
  46720. defines.LIGHTMAP = false;
  46721. }
  46722. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  46723. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  46724. }
  46725. else {
  46726. defines.EMISSIVE = false;
  46727. }
  46728. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  46729. if (this._metallicTexture) {
  46730. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  46731. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  46732. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  46733. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  46734. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  46735. }
  46736. else if (this._reflectivityTexture) {
  46737. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  46738. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  46739. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  46740. }
  46741. else {
  46742. defines.REFLECTIVITY = false;
  46743. }
  46744. if (this._microSurfaceTexture) {
  46745. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  46746. }
  46747. else {
  46748. defines.MICROSURFACEMAP = false;
  46749. }
  46750. }
  46751. else {
  46752. defines.REFLECTIVITY = false;
  46753. defines.MICROSURFACEMAP = false;
  46754. }
  46755. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  46756. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  46757. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  46758. defines.PARALLAX = true;
  46759. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  46760. }
  46761. else {
  46762. defines.PARALLAX = false;
  46763. }
  46764. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  46765. }
  46766. else {
  46767. defines.BUMP = false;
  46768. }
  46769. var refractionTexture = this._getRefractionTexture();
  46770. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  46771. defines.REFRACTION = true;
  46772. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  46773. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  46774. defines.RGBDREFRACTION = refractionTexture.isRGBD;
  46775. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  46776. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  46777. if (this._linkRefractionWithTransparency) {
  46778. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  46779. }
  46780. }
  46781. else {
  46782. defines.REFRACTION = false;
  46783. }
  46784. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  46785. defines.ENVIRONMENTBRDF = true;
  46786. }
  46787. else {
  46788. defines.ENVIRONMENTBRDF = false;
  46789. }
  46790. if (this._shouldUseAlphaFromAlbedoTexture()) {
  46791. defines.ALPHAFROMALBEDO = true;
  46792. }
  46793. else {
  46794. defines.ALPHAFROMALBEDO = false;
  46795. }
  46796. }
  46797. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  46798. if (this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_STANDARD) {
  46799. defines.USEPHYSICALLIGHTFALLOFF = false;
  46800. defines.USEGLTFLIGHTFALLOFF = false;
  46801. }
  46802. else if (this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_GLTF) {
  46803. defines.USEPHYSICALLIGHTFALLOFF = false;
  46804. defines.USEGLTFLIGHTFALLOFF = true;
  46805. }
  46806. else {
  46807. defines.USEPHYSICALLIGHTFALLOFF = true;
  46808. defines.USEGLTFLIGHTFALLOFF = false;
  46809. }
  46810. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  46811. if (!this.backFaceCulling && this._twoSidedLighting) {
  46812. defines.TWOSIDEDLIGHTING = true;
  46813. }
  46814. else {
  46815. defines.TWOSIDEDLIGHTING = false;
  46816. }
  46817. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  46818. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  46819. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  46820. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  46821. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  46822. defines.SPECULARAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  46823. }
  46824. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  46825. this._imageProcessingConfiguration.prepareDefines(defines);
  46826. }
  46827. defines.FORCENORMALFORWARD = this._forceNormalForward;
  46828. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  46829. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  46830. // Misc.
  46831. if (defines._areMiscDirty) {
  46832. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  46833. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  46834. }
  46835. // Values that need to be evaluated on every frame
  46836. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  46837. // Attribs
  46838. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  46839. };
  46840. /**
  46841. * Force shader compilation
  46842. */
  46843. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  46844. var _this = this;
  46845. var localOptions = __assign({ clipPlane: false }, options);
  46846. var defines = new PBRMaterialDefines();
  46847. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  46848. if (effect.isReady()) {
  46849. if (onCompiled) {
  46850. onCompiled(this);
  46851. }
  46852. }
  46853. else {
  46854. effect.onCompileObservable.add(function () {
  46855. if (onCompiled) {
  46856. onCompiled(_this);
  46857. }
  46858. });
  46859. }
  46860. };
  46861. /**
  46862. * Initializes the uniform buffer layout for the shader.
  46863. */
  46864. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  46865. // Order is important !
  46866. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  46867. this._uniformBuffer.addUniform("vAmbientInfos", 4);
  46868. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  46869. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  46870. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  46871. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  46872. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  46873. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  46874. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  46875. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  46876. this._uniformBuffer.addUniform("vReflectionSize", 3);
  46877. this._uniformBuffer.addUniform("vBumpInfos", 3);
  46878. this._uniformBuffer.addUniform("albedoMatrix", 16);
  46879. this._uniformBuffer.addUniform("ambientMatrix", 16);
  46880. this._uniformBuffer.addUniform("opacityMatrix", 16);
  46881. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  46882. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  46883. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  46884. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  46885. this._uniformBuffer.addUniform("bumpMatrix", 16);
  46886. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  46887. this._uniformBuffer.addUniform("refractionMatrix", 16);
  46888. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  46889. this._uniformBuffer.addUniform("vReflectionColor", 3);
  46890. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  46891. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  46892. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  46893. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  46894. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  46895. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  46896. this._uniformBuffer.addUniform("pointSize", 1);
  46897. this._uniformBuffer.create();
  46898. };
  46899. /**
  46900. * Unbinds the textures.
  46901. */
  46902. PBRBaseMaterial.prototype.unbind = function () {
  46903. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  46904. this._uniformBuffer.setTexture("reflectionSampler", null);
  46905. }
  46906. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  46907. this._uniformBuffer.setTexture("refractionSampler", null);
  46908. }
  46909. _super.prototype.unbind.call(this);
  46910. };
  46911. /**
  46912. * Binds the submesh data.
  46913. * @param world - The world matrix.
  46914. * @param mesh - The BJS mesh.
  46915. * @param subMesh - A submesh of the BJS mesh.
  46916. */
  46917. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  46918. var scene = this.getScene();
  46919. var defines = subMesh._materialDefines;
  46920. if (!defines) {
  46921. return;
  46922. }
  46923. var effect = subMesh.effect;
  46924. if (!effect) {
  46925. return;
  46926. }
  46927. this._activeEffect = effect;
  46928. // Matrices
  46929. this.bindOnlyWorldMatrix(world);
  46930. // Normal Matrix
  46931. if (defines.OBJECTSPACE_NORMALMAP) {
  46932. world.toNormalMatrix(this._normalMatrix);
  46933. this.bindOnlyNormalMatrix(this._normalMatrix);
  46934. }
  46935. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  46936. // Bones
  46937. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  46938. var reflectionTexture = null;
  46939. if (mustRebind) {
  46940. this._uniformBuffer.bindToEffect(effect, "Material");
  46941. this.bindViewProjection(effect);
  46942. reflectionTexture = this._getReflectionTexture();
  46943. var refractionTexture = this._getRefractionTexture();
  46944. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  46945. // Texture uniforms
  46946. if (scene.texturesEnabled) {
  46947. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  46948. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  46949. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  46950. }
  46951. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  46952. this._uniformBuffer.updateFloat4("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength, this._ambientTextureImpactOnAnalyticalLights);
  46953. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  46954. }
  46955. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  46956. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  46957. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  46958. }
  46959. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  46960. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  46961. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  46962. if (reflectionTexture.boundingBoxSize) {
  46963. var cubeTexture = reflectionTexture;
  46964. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  46965. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  46966. }
  46967. var polynomials = reflectionTexture.sphericalPolynomial;
  46968. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  46969. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  46970. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  46971. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  46972. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  46973. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  46974. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  46975. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  46976. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  46977. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  46978. }
  46979. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  46980. }
  46981. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  46982. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  46983. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  46984. }
  46985. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  46986. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  46987. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  46988. }
  46989. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  46990. if (this._metallicTexture) {
  46991. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  46992. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  46993. }
  46994. else if (this._reflectivityTexture) {
  46995. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  46996. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  46997. }
  46998. if (this._microSurfaceTexture) {
  46999. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  47000. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  47001. }
  47002. }
  47003. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  47004. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  47005. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  47006. if (scene._mirroredCameraPosition) {
  47007. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  47008. }
  47009. else {
  47010. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  47011. }
  47012. }
  47013. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  47014. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  47015. var depth = 1.0;
  47016. if (!refractionTexture.isCube) {
  47017. if (refractionTexture.depth) {
  47018. depth = refractionTexture.depth;
  47019. }
  47020. }
  47021. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  47022. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  47023. }
  47024. }
  47025. // Point size
  47026. if (this.pointsCloud) {
  47027. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  47028. }
  47029. // Colors
  47030. if (defines.METALLICWORKFLOW) {
  47031. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  47032. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  47033. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  47034. }
  47035. else {
  47036. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  47037. }
  47038. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  47039. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  47040. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  47041. // Misc
  47042. this._lightingInfos.x = this._directIntensity;
  47043. this._lightingInfos.y = this._emissiveIntensity;
  47044. this._lightingInfos.z = this._environmentIntensity;
  47045. this._lightingInfos.w = this._specularIntensity;
  47046. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  47047. }
  47048. // Textures
  47049. if (scene.texturesEnabled) {
  47050. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  47051. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  47052. }
  47053. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  47054. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  47055. }
  47056. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  47057. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  47058. }
  47059. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  47060. if (defines.LODBASEDMICROSFURACE) {
  47061. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  47062. }
  47063. else {
  47064. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  47065. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  47066. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  47067. }
  47068. }
  47069. if (defines.ENVIRONMENTBRDF) {
  47070. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  47071. }
  47072. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  47073. if (defines.LODBASEDMICROSFURACE) {
  47074. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  47075. }
  47076. else {
  47077. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  47078. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  47079. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  47080. }
  47081. }
  47082. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  47083. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  47084. }
  47085. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  47086. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  47087. }
  47088. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  47089. if (this._metallicTexture) {
  47090. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  47091. }
  47092. else if (this._reflectivityTexture) {
  47093. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  47094. }
  47095. if (this._microSurfaceTexture) {
  47096. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  47097. }
  47098. }
  47099. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  47100. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  47101. }
  47102. }
  47103. // Clip plane
  47104. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  47105. // Colors
  47106. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  47107. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  47108. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  47109. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  47110. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  47111. }
  47112. if (mustRebind || !this.isFrozen) {
  47113. // Lights
  47114. if (scene.lightsEnabled && !this._disableLighting) {
  47115. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._lightFalloff !== PBRBaseMaterial.LIGHTFALLOFF_STANDARD);
  47116. }
  47117. // View
  47118. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  47119. this.bindView(effect);
  47120. }
  47121. // Fog
  47122. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect, true);
  47123. // Morph targets
  47124. if (defines.NUM_MORPH_INFLUENCERS) {
  47125. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  47126. }
  47127. // image processing
  47128. this._imageProcessingConfiguration.bind(this._activeEffect);
  47129. // Log. depth
  47130. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  47131. }
  47132. this._uniformBuffer.update();
  47133. this._afterBind(mesh, this._activeEffect);
  47134. };
  47135. /**
  47136. * Returns the animatable textures.
  47137. * @returns - Array of animatable textures.
  47138. */
  47139. PBRBaseMaterial.prototype.getAnimatables = function () {
  47140. var results = [];
  47141. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  47142. results.push(this._albedoTexture);
  47143. }
  47144. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  47145. results.push(this._ambientTexture);
  47146. }
  47147. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  47148. results.push(this._opacityTexture);
  47149. }
  47150. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  47151. results.push(this._reflectionTexture);
  47152. }
  47153. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  47154. results.push(this._emissiveTexture);
  47155. }
  47156. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  47157. results.push(this._metallicTexture);
  47158. }
  47159. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  47160. results.push(this._reflectivityTexture);
  47161. }
  47162. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  47163. results.push(this._bumpTexture);
  47164. }
  47165. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  47166. results.push(this._lightmapTexture);
  47167. }
  47168. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  47169. results.push(this._refractionTexture);
  47170. }
  47171. return results;
  47172. };
  47173. /**
  47174. * Returns the texture used for reflections.
  47175. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  47176. */
  47177. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  47178. if (this._reflectionTexture) {
  47179. return this._reflectionTexture;
  47180. }
  47181. return this.getScene().environmentTexture;
  47182. };
  47183. /**
  47184. * Returns the texture used for refraction or null if none is used.
  47185. * @returns - Refection texture if present. If no refraction texture and refraction
  47186. * is linked with transparency, returns environment texture. Otherwise, returns null.
  47187. */
  47188. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  47189. if (this._refractionTexture) {
  47190. return this._refractionTexture;
  47191. }
  47192. if (this._linkRefractionWithTransparency) {
  47193. return this.getScene().environmentTexture;
  47194. }
  47195. return null;
  47196. };
  47197. /**
  47198. * Disposes the resources of the material.
  47199. * @param forceDisposeEffect - Forces the disposal of effects.
  47200. * @param forceDisposeTextures - Forces the disposal of all textures.
  47201. */
  47202. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  47203. if (forceDisposeTextures) {
  47204. if (this._albedoTexture) {
  47205. this._albedoTexture.dispose();
  47206. }
  47207. if (this._ambientTexture) {
  47208. this._ambientTexture.dispose();
  47209. }
  47210. if (this._opacityTexture) {
  47211. this._opacityTexture.dispose();
  47212. }
  47213. if (this._reflectionTexture) {
  47214. this._reflectionTexture.dispose();
  47215. }
  47216. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  47217. this._environmentBRDFTexture.dispose();
  47218. }
  47219. if (this._emissiveTexture) {
  47220. this._emissiveTexture.dispose();
  47221. }
  47222. if (this._metallicTexture) {
  47223. this._metallicTexture.dispose();
  47224. }
  47225. if (this._reflectivityTexture) {
  47226. this._reflectivityTexture.dispose();
  47227. }
  47228. if (this._bumpTexture) {
  47229. this._bumpTexture.dispose();
  47230. }
  47231. if (this._lightmapTexture) {
  47232. this._lightmapTexture.dispose();
  47233. }
  47234. if (this._refractionTexture) {
  47235. this._refractionTexture.dispose();
  47236. }
  47237. }
  47238. this._renderTargets.dispose();
  47239. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  47240. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  47241. }
  47242. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  47243. };
  47244. /**
  47245. * PBRMaterialLightFalloff Physical: light is falling off following the inverse squared distance law.
  47246. */
  47247. PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL = 0;
  47248. /**
  47249. * PBRMaterialLightFalloff gltf: light is falling off as described in the gltf moving to PBR document
  47250. * to enhance interoperability with other engines.
  47251. */
  47252. PBRBaseMaterial.LIGHTFALLOFF_GLTF = 1;
  47253. /**
  47254. * PBRMaterialLightFalloff Standard: light is falling off like in the standard material
  47255. * to enhance interoperability with other materials.
  47256. */
  47257. PBRBaseMaterial.LIGHTFALLOFF_STANDARD = 2;
  47258. /**
  47259. * Stores the reflectivity values based on metallic roughness workflow.
  47260. */
  47261. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  47262. __decorate([
  47263. BABYLON.serializeAsImageProcessingConfiguration()
  47264. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  47265. __decorate([
  47266. BABYLON.serialize()
  47267. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  47268. __decorate([
  47269. BABYLON.serialize()
  47270. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  47271. return PBRBaseMaterial;
  47272. }(BABYLON.PushMaterial));
  47273. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  47274. })(BABYLON || (BABYLON = {}));
  47275. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  47276. var BABYLON;
  47277. (function (BABYLON) {
  47278. /**
  47279. * The Physically based simple base material of BJS.
  47280. *
  47281. * This enables better naming and convention enforcements on top of the pbrMaterial.
  47282. * It is used as the base class for both the specGloss and metalRough conventions.
  47283. */
  47284. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  47285. __extends(PBRBaseSimpleMaterial, _super);
  47286. /**
  47287. * Instantiates a new PBRMaterial instance.
  47288. *
  47289. * @param name The material name
  47290. * @param scene The scene the material will be use in.
  47291. */
  47292. function PBRBaseSimpleMaterial(name, scene) {
  47293. var _this = _super.call(this, name, scene) || this;
  47294. /**
  47295. * Number of Simultaneous lights allowed on the material.
  47296. */
  47297. _this.maxSimultaneousLights = 4;
  47298. /**
  47299. * If sets to true, disables all the lights affecting the material.
  47300. */
  47301. _this.disableLighting = false;
  47302. /**
  47303. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  47304. */
  47305. _this.invertNormalMapX = false;
  47306. /**
  47307. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  47308. */
  47309. _this.invertNormalMapY = false;
  47310. /**
  47311. * Emissivie color used to self-illuminate the model.
  47312. */
  47313. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  47314. /**
  47315. * Occlusion Channel Strenght.
  47316. */
  47317. _this.occlusionStrength = 1.0;
  47318. /**
  47319. * If true, the light map contains occlusion information instead of lighting info.
  47320. */
  47321. _this.useLightmapAsShadowmap = false;
  47322. _this._useAlphaFromAlbedoTexture = true;
  47323. _this._useAmbientInGrayScale = true;
  47324. return _this;
  47325. }
  47326. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  47327. /**
  47328. * Gets the current double sided mode.
  47329. */
  47330. get: function () {
  47331. return this._twoSidedLighting;
  47332. },
  47333. /**
  47334. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  47335. */
  47336. set: function (value) {
  47337. if (this._twoSidedLighting === value) {
  47338. return;
  47339. }
  47340. this._twoSidedLighting = value;
  47341. this.backFaceCulling = !value;
  47342. this._markAllSubMeshesAsTexturesDirty();
  47343. },
  47344. enumerable: true,
  47345. configurable: true
  47346. });
  47347. /**
  47348. * Return the active textures of the material.
  47349. */
  47350. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  47351. var activeTextures = _super.prototype.getActiveTextures.call(this);
  47352. if (this.environmentTexture) {
  47353. activeTextures.push(this.environmentTexture);
  47354. }
  47355. if (this.normalTexture) {
  47356. activeTextures.push(this.normalTexture);
  47357. }
  47358. if (this.emissiveTexture) {
  47359. activeTextures.push(this.emissiveTexture);
  47360. }
  47361. if (this.occlusionTexture) {
  47362. activeTextures.push(this.occlusionTexture);
  47363. }
  47364. if (this.lightmapTexture) {
  47365. activeTextures.push(this.lightmapTexture);
  47366. }
  47367. return activeTextures;
  47368. };
  47369. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  47370. if (_super.prototype.hasTexture.call(this, texture)) {
  47371. return true;
  47372. }
  47373. if (this.lightmapTexture === texture) {
  47374. return true;
  47375. }
  47376. return false;
  47377. };
  47378. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  47379. return "PBRBaseSimpleMaterial";
  47380. };
  47381. __decorate([
  47382. BABYLON.serialize(),
  47383. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  47384. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  47385. __decorate([
  47386. BABYLON.serialize(),
  47387. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  47388. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  47389. __decorate([
  47390. BABYLON.serializeAsTexture(),
  47391. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  47392. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  47393. __decorate([
  47394. BABYLON.serialize(),
  47395. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47396. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  47397. __decorate([
  47398. BABYLON.serialize(),
  47399. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47400. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  47401. __decorate([
  47402. BABYLON.serializeAsTexture(),
  47403. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  47404. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  47405. __decorate([
  47406. BABYLON.serializeAsColor3("emissive"),
  47407. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47408. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  47409. __decorate([
  47410. BABYLON.serializeAsTexture(),
  47411. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47412. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  47413. __decorate([
  47414. BABYLON.serialize(),
  47415. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  47416. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  47417. __decorate([
  47418. BABYLON.serializeAsTexture(),
  47419. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  47420. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  47421. __decorate([
  47422. BABYLON.serialize(),
  47423. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  47424. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  47425. __decorate([
  47426. BABYLON.serialize()
  47427. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  47428. __decorate([
  47429. BABYLON.serializeAsTexture(),
  47430. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  47431. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  47432. __decorate([
  47433. BABYLON.serialize(),
  47434. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47435. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  47436. return PBRBaseSimpleMaterial;
  47437. }(BABYLON.PBRBaseMaterial));
  47438. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  47439. })(BABYLON || (BABYLON = {}));
  47440. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  47441. var BABYLON;
  47442. (function (BABYLON) {
  47443. /**
  47444. * The Physically based material of BJS.
  47445. *
  47446. * This offers the main features of a standard PBR material.
  47447. * For more information, please refer to the documentation :
  47448. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  47449. */
  47450. var PBRMaterial = /** @class */ (function (_super) {
  47451. __extends(PBRMaterial, _super);
  47452. /**
  47453. * Instantiates a new PBRMaterial instance.
  47454. *
  47455. * @param name The material name
  47456. * @param scene The scene the material will be use in.
  47457. */
  47458. function PBRMaterial(name, scene) {
  47459. var _this = _super.call(this, name, scene) || this;
  47460. /**
  47461. * Intensity of the direct lights e.g. the four lights available in your scene.
  47462. * This impacts both the direct diffuse and specular highlights.
  47463. */
  47464. _this.directIntensity = 1.0;
  47465. /**
  47466. * Intensity of the emissive part of the material.
  47467. * This helps controlling the emissive effect without modifying the emissive color.
  47468. */
  47469. _this.emissiveIntensity = 1.0;
  47470. /**
  47471. * Intensity of the environment e.g. how much the environment will light the object
  47472. * either through harmonics for rough material or through the refelction for shiny ones.
  47473. */
  47474. _this.environmentIntensity = 1.0;
  47475. /**
  47476. * This is a special control allowing the reduction of the specular highlights coming from the
  47477. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  47478. */
  47479. _this.specularIntensity = 1.0;
  47480. /**
  47481. * Debug Control allowing disabling the bump map on this material.
  47482. */
  47483. _this.disableBumpMap = false;
  47484. /**
  47485. * AKA Occlusion Texture Intensity in other nomenclature.
  47486. */
  47487. _this.ambientTextureStrength = 1.0;
  47488. /**
  47489. * Defines how much the AO map is occluding the analytical lights (point spot...).
  47490. * 1 means it completely occludes it
  47491. * 0 mean it has no impact
  47492. */
  47493. _this.ambientTextureImpactOnAnalyticalLights = PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS;
  47494. /**
  47495. * The color of a material in ambient lighting.
  47496. */
  47497. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  47498. /**
  47499. * AKA Diffuse Color in other nomenclature.
  47500. */
  47501. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  47502. /**
  47503. * AKA Specular Color in other nomenclature.
  47504. */
  47505. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  47506. /**
  47507. * The color reflected from the material.
  47508. */
  47509. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  47510. /**
  47511. * The color emitted from the material.
  47512. */
  47513. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  47514. /**
  47515. * AKA Glossiness in other nomenclature.
  47516. */
  47517. _this.microSurface = 1.0;
  47518. /**
  47519. * source material index of refraction (IOR)' / 'destination material IOR.
  47520. */
  47521. _this.indexOfRefraction = 0.66;
  47522. /**
  47523. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  47524. */
  47525. _this.invertRefractionY = false;
  47526. /**
  47527. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  47528. * Materials half opaque for instance using refraction could benefit from this control.
  47529. */
  47530. _this.linkRefractionWithTransparency = false;
  47531. /**
  47532. * If true, the light map contains occlusion information instead of lighting info.
  47533. */
  47534. _this.useLightmapAsShadowmap = false;
  47535. /**
  47536. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  47537. */
  47538. _this.useAlphaFromAlbedoTexture = false;
  47539. /**
  47540. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  47541. */
  47542. _this.forceAlphaTest = false;
  47543. /**
  47544. * Defines the alpha limits in alpha test mode.
  47545. */
  47546. _this.alphaCutOff = 0.4;
  47547. /**
  47548. * Specifies that the material will keep the specular highlights over a transparent surface (only the most limunous ones).
  47549. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  47550. */
  47551. _this.useSpecularOverAlpha = true;
  47552. /**
  47553. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  47554. */
  47555. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  47556. /**
  47557. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  47558. */
  47559. _this.useRoughnessFromMetallicTextureAlpha = true;
  47560. /**
  47561. * Specifies if the metallic texture contains the roughness information in its green channel.
  47562. */
  47563. _this.useRoughnessFromMetallicTextureGreen = false;
  47564. /**
  47565. * Specifies if the metallic texture contains the metallness information in its blue channel.
  47566. */
  47567. _this.useMetallnessFromMetallicTextureBlue = false;
  47568. /**
  47569. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  47570. */
  47571. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  47572. /**
  47573. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  47574. */
  47575. _this.useAmbientInGrayScale = false;
  47576. /**
  47577. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  47578. * The material will try to infer what glossiness each pixel should be.
  47579. */
  47580. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  47581. /**
  47582. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  47583. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  47584. */
  47585. _this.useRadianceOverAlpha = true;
  47586. /**
  47587. * Allows using an object space normal map (instead of tangent space).
  47588. */
  47589. _this.useObjectSpaceNormalMap = false;
  47590. /**
  47591. * Allows using the bump map in parallax mode.
  47592. */
  47593. _this.useParallax = false;
  47594. /**
  47595. * Allows using the bump map in parallax occlusion mode.
  47596. */
  47597. _this.useParallaxOcclusion = false;
  47598. /**
  47599. * Controls the scale bias of the parallax mode.
  47600. */
  47601. _this.parallaxScaleBias = 0.05;
  47602. /**
  47603. * If sets to true, disables all the lights affecting the material.
  47604. */
  47605. _this.disableLighting = false;
  47606. /**
  47607. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  47608. */
  47609. _this.forceIrradianceInFragment = false;
  47610. /**
  47611. * Number of Simultaneous lights allowed on the material.
  47612. */
  47613. _this.maxSimultaneousLights = 4;
  47614. /**
  47615. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  47616. */
  47617. _this.invertNormalMapX = false;
  47618. /**
  47619. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  47620. */
  47621. _this.invertNormalMapY = false;
  47622. /**
  47623. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  47624. */
  47625. _this.twoSidedLighting = false;
  47626. /**
  47627. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  47628. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  47629. */
  47630. _this.useAlphaFresnel = false;
  47631. /**
  47632. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  47633. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  47634. */
  47635. _this.useLinearAlphaFresnel = false;
  47636. /**
  47637. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  47638. * And/Or occlude the blended part.
  47639. */
  47640. _this.environmentBRDFTexture = null;
  47641. /**
  47642. * Force normal to face away from face.
  47643. */
  47644. _this.forceNormalForward = false;
  47645. /**
  47646. * Enables specular anti aliasing in the PBR shader.
  47647. * It will both interacts on the Geometry for analytical and IBL lighting.
  47648. * It also prefilter the roughness map based on the bump values.
  47649. */
  47650. _this.enableSpecularAntiAliasing = false;
  47651. /**
  47652. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  47653. * makes the reflect vector face the model (under horizon).
  47654. */
  47655. _this.useHorizonOcclusion = true;
  47656. /**
  47657. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  47658. * too much the area relying on ambient texture to define their ambient occlusion.
  47659. */
  47660. _this.useRadianceOcclusion = true;
  47661. /**
  47662. * If set to true, no lighting calculations will be applied.
  47663. */
  47664. _this.unlit = false;
  47665. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  47666. return _this;
  47667. }
  47668. Object.defineProperty(PBRMaterial.prototype, "usePhysicalLightFalloff", {
  47669. /**
  47670. * BJS is using an harcoded light falloff based on a manually sets up range.
  47671. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  47672. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  47673. */
  47674. get: function () {
  47675. return this._lightFalloff === BABYLON.PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  47676. },
  47677. /**
  47678. * BJS is using an harcoded light falloff based on a manually sets up range.
  47679. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  47680. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  47681. */
  47682. set: function (value) {
  47683. if (value !== this.usePhysicalLightFalloff) {
  47684. // Ensure the effect will be rebuilt.
  47685. this._markAllSubMeshesAsTexturesDirty();
  47686. if (value) {
  47687. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  47688. }
  47689. else {
  47690. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_STANDARD;
  47691. }
  47692. }
  47693. },
  47694. enumerable: true,
  47695. configurable: true
  47696. });
  47697. Object.defineProperty(PBRMaterial.prototype, "useGLTFLightFalloff", {
  47698. /**
  47699. * In order to support the falloff compatibility with gltf, a special mode has been added
  47700. * to reproduce the gltf light falloff.
  47701. */
  47702. get: function () {
  47703. return this._lightFalloff === BABYLON.PBRBaseMaterial.LIGHTFALLOFF_GLTF;
  47704. },
  47705. /**
  47706. * In order to support the falloff compatibility with gltf, a special mode has been added
  47707. * to reproduce the gltf light falloff.
  47708. */
  47709. set: function (value) {
  47710. if (value !== this.useGLTFLightFalloff) {
  47711. // Ensure the effect will be rebuilt.
  47712. this._markAllSubMeshesAsTexturesDirty();
  47713. if (value) {
  47714. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_GLTF;
  47715. }
  47716. else {
  47717. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_STANDARD;
  47718. }
  47719. }
  47720. },
  47721. enumerable: true,
  47722. configurable: true
  47723. });
  47724. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  47725. /**
  47726. * Gets the image processing configuration used either in this material.
  47727. */
  47728. get: function () {
  47729. return this._imageProcessingConfiguration;
  47730. },
  47731. /**
  47732. * Sets the Default image processing configuration used either in the this material.
  47733. *
  47734. * If sets to null, the scene one is in use.
  47735. */
  47736. set: function (value) {
  47737. this._attachImageProcessingConfiguration(value);
  47738. // Ensure the effect will be rebuilt.
  47739. this._markAllSubMeshesAsTexturesDirty();
  47740. },
  47741. enumerable: true,
  47742. configurable: true
  47743. });
  47744. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  47745. /**
  47746. * Gets wether the color curves effect is enabled.
  47747. */
  47748. get: function () {
  47749. return this.imageProcessingConfiguration.colorCurvesEnabled;
  47750. },
  47751. /**
  47752. * Sets wether the color curves effect is enabled.
  47753. */
  47754. set: function (value) {
  47755. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  47756. },
  47757. enumerable: true,
  47758. configurable: true
  47759. });
  47760. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  47761. /**
  47762. * Gets wether the color grading effect is enabled.
  47763. */
  47764. get: function () {
  47765. return this.imageProcessingConfiguration.colorGradingEnabled;
  47766. },
  47767. /**
  47768. * Gets wether the color grading effect is enabled.
  47769. */
  47770. set: function (value) {
  47771. this.imageProcessingConfiguration.colorGradingEnabled = value;
  47772. },
  47773. enumerable: true,
  47774. configurable: true
  47775. });
  47776. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  47777. /**
  47778. * Gets wether tonemapping is enabled or not.
  47779. */
  47780. get: function () {
  47781. return this._imageProcessingConfiguration.toneMappingEnabled;
  47782. },
  47783. /**
  47784. * Sets wether tonemapping is enabled or not
  47785. */
  47786. set: function (value) {
  47787. this._imageProcessingConfiguration.toneMappingEnabled = value;
  47788. },
  47789. enumerable: true,
  47790. configurable: true
  47791. });
  47792. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  47793. /**
  47794. * The camera exposure used on this material.
  47795. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  47796. * This corresponds to a photographic exposure.
  47797. */
  47798. get: function () {
  47799. return this._imageProcessingConfiguration.exposure;
  47800. },
  47801. /**
  47802. * The camera exposure used on this material.
  47803. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  47804. * This corresponds to a photographic exposure.
  47805. */
  47806. set: function (value) {
  47807. this._imageProcessingConfiguration.exposure = value;
  47808. },
  47809. enumerable: true,
  47810. configurable: true
  47811. });
  47812. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  47813. /**
  47814. * Gets The camera contrast used on this material.
  47815. */
  47816. get: function () {
  47817. return this._imageProcessingConfiguration.contrast;
  47818. },
  47819. /**
  47820. * Sets The camera contrast used on this material.
  47821. */
  47822. set: function (value) {
  47823. this._imageProcessingConfiguration.contrast = value;
  47824. },
  47825. enumerable: true,
  47826. configurable: true
  47827. });
  47828. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  47829. /**
  47830. * Gets the Color Grading 2D Lookup Texture.
  47831. */
  47832. get: function () {
  47833. return this._imageProcessingConfiguration.colorGradingTexture;
  47834. },
  47835. /**
  47836. * Sets the Color Grading 2D Lookup Texture.
  47837. */
  47838. set: function (value) {
  47839. this._imageProcessingConfiguration.colorGradingTexture = value;
  47840. },
  47841. enumerable: true,
  47842. configurable: true
  47843. });
  47844. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  47845. /**
  47846. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  47847. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  47848. * 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;
  47849. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  47850. */
  47851. get: function () {
  47852. return this._imageProcessingConfiguration.colorCurves;
  47853. },
  47854. /**
  47855. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  47856. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  47857. * 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;
  47858. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  47859. */
  47860. set: function (value) {
  47861. this._imageProcessingConfiguration.colorCurves = value;
  47862. },
  47863. enumerable: true,
  47864. configurable: true
  47865. });
  47866. /**
  47867. * Returns the name of this material class.
  47868. */
  47869. PBRMaterial.prototype.getClassName = function () {
  47870. return "PBRMaterial";
  47871. };
  47872. /**
  47873. * Returns an array of the actively used textures.
  47874. * @returns - Array of BaseTextures
  47875. */
  47876. PBRMaterial.prototype.getActiveTextures = function () {
  47877. var activeTextures = _super.prototype.getActiveTextures.call(this);
  47878. if (this._albedoTexture) {
  47879. activeTextures.push(this._albedoTexture);
  47880. }
  47881. if (this._ambientTexture) {
  47882. activeTextures.push(this._ambientTexture);
  47883. }
  47884. if (this._opacityTexture) {
  47885. activeTextures.push(this._opacityTexture);
  47886. }
  47887. if (this._reflectionTexture) {
  47888. activeTextures.push(this._reflectionTexture);
  47889. }
  47890. if (this._emissiveTexture) {
  47891. activeTextures.push(this._emissiveTexture);
  47892. }
  47893. if (this._reflectivityTexture) {
  47894. activeTextures.push(this._reflectivityTexture);
  47895. }
  47896. if (this._metallicTexture) {
  47897. activeTextures.push(this._metallicTexture);
  47898. }
  47899. if (this._microSurfaceTexture) {
  47900. activeTextures.push(this._microSurfaceTexture);
  47901. }
  47902. if (this._bumpTexture) {
  47903. activeTextures.push(this._bumpTexture);
  47904. }
  47905. if (this._lightmapTexture) {
  47906. activeTextures.push(this._lightmapTexture);
  47907. }
  47908. if (this._refractionTexture) {
  47909. activeTextures.push(this._refractionTexture);
  47910. }
  47911. return activeTextures;
  47912. };
  47913. /**
  47914. * Checks to see if a texture is used in the material.
  47915. * @param texture - Base texture to use.
  47916. * @returns - Boolean specifying if a texture is used in the material.
  47917. */
  47918. PBRMaterial.prototype.hasTexture = function (texture) {
  47919. if (_super.prototype.hasTexture.call(this, texture)) {
  47920. return true;
  47921. }
  47922. if (this._albedoTexture === texture) {
  47923. return true;
  47924. }
  47925. if (this._ambientTexture === texture) {
  47926. return true;
  47927. }
  47928. if (this._opacityTexture === texture) {
  47929. return true;
  47930. }
  47931. if (this._reflectionTexture === texture) {
  47932. return true;
  47933. }
  47934. if (this._reflectivityTexture === texture) {
  47935. return true;
  47936. }
  47937. if (this._metallicTexture === texture) {
  47938. return true;
  47939. }
  47940. if (this._microSurfaceTexture === texture) {
  47941. return true;
  47942. }
  47943. if (this._bumpTexture === texture) {
  47944. return true;
  47945. }
  47946. if (this._lightmapTexture === texture) {
  47947. return true;
  47948. }
  47949. if (this._refractionTexture === texture) {
  47950. return true;
  47951. }
  47952. return false;
  47953. };
  47954. /**
  47955. * Makes a duplicate of the current material.
  47956. * @param name - name to use for the new material.
  47957. */
  47958. PBRMaterial.prototype.clone = function (name) {
  47959. var _this = this;
  47960. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  47961. clone.id = name;
  47962. clone.name = name;
  47963. return clone;
  47964. };
  47965. /**
  47966. * Serializes this PBR Material.
  47967. * @returns - An object with the serialized material.
  47968. */
  47969. PBRMaterial.prototype.serialize = function () {
  47970. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  47971. serializationObject.customType = "BABYLON.PBRMaterial";
  47972. return serializationObject;
  47973. };
  47974. // Statics
  47975. /**
  47976. * Parses a PBR Material from a serialized object.
  47977. * @param source - Serialized object.
  47978. * @param scene - BJS scene instance.
  47979. * @param rootUrl - url for the scene object
  47980. * @returns - PBRMaterial
  47981. */
  47982. PBRMaterial.Parse = function (source, scene, rootUrl) {
  47983. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  47984. };
  47985. /**
  47986. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  47987. */
  47988. PBRMaterial.PBRMATERIAL_OPAQUE = 0;
  47989. /**
  47990. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  47991. */
  47992. PBRMaterial.PBRMATERIAL_ALPHATEST = 1;
  47993. /**
  47994. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  47995. */
  47996. PBRMaterial.PBRMATERIAL_ALPHABLEND = 2;
  47997. /**
  47998. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  47999. * They are also discarded below the alpha cutoff threshold to improve performances.
  48000. */
  48001. PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND = 3;
  48002. /**
  48003. * Defines the default value of how much AO map is occluding the analytical lights
  48004. * (point spot...).
  48005. */
  48006. PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS = 1;
  48007. __decorate([
  48008. BABYLON.serialize(),
  48009. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  48010. ], PBRMaterial.prototype, "directIntensity", void 0);
  48011. __decorate([
  48012. BABYLON.serialize(),
  48013. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  48014. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  48015. __decorate([
  48016. BABYLON.serialize(),
  48017. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  48018. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  48019. __decorate([
  48020. BABYLON.serialize(),
  48021. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  48022. ], PBRMaterial.prototype, "specularIntensity", void 0);
  48023. __decorate([
  48024. BABYLON.serialize(),
  48025. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  48026. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  48027. __decorate([
  48028. BABYLON.serializeAsTexture(),
  48029. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  48030. ], PBRMaterial.prototype, "albedoTexture", void 0);
  48031. __decorate([
  48032. BABYLON.serializeAsTexture(),
  48033. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  48034. ], PBRMaterial.prototype, "ambientTexture", void 0);
  48035. __decorate([
  48036. BABYLON.serialize(),
  48037. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  48038. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  48039. __decorate([
  48040. BABYLON.serialize(),
  48041. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  48042. ], PBRMaterial.prototype, "ambientTextureImpactOnAnalyticalLights", void 0);
  48043. __decorate([
  48044. BABYLON.serializeAsTexture(),
  48045. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  48046. ], PBRMaterial.prototype, "opacityTexture", void 0);
  48047. __decorate([
  48048. BABYLON.serializeAsTexture(),
  48049. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  48050. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  48051. __decorate([
  48052. BABYLON.serializeAsTexture(),
  48053. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  48054. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  48055. __decorate([
  48056. BABYLON.serializeAsTexture(),
  48057. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  48058. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  48059. __decorate([
  48060. BABYLON.serializeAsTexture(),
  48061. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  48062. ], PBRMaterial.prototype, "metallicTexture", void 0);
  48063. __decorate([
  48064. BABYLON.serialize(),
  48065. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  48066. ], PBRMaterial.prototype, "metallic", void 0);
  48067. __decorate([
  48068. BABYLON.serialize(),
  48069. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  48070. ], PBRMaterial.prototype, "roughness", void 0);
  48071. __decorate([
  48072. BABYLON.serializeAsTexture(),
  48073. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  48074. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  48075. __decorate([
  48076. BABYLON.serializeAsTexture(),
  48077. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  48078. ], PBRMaterial.prototype, "bumpTexture", void 0);
  48079. __decorate([
  48080. BABYLON.serializeAsTexture(),
  48081. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  48082. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  48083. __decorate([
  48084. BABYLON.serializeAsTexture(),
  48085. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  48086. ], PBRMaterial.prototype, "refractionTexture", void 0);
  48087. __decorate([
  48088. BABYLON.serializeAsColor3("ambient"),
  48089. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  48090. ], PBRMaterial.prototype, "ambientColor", void 0);
  48091. __decorate([
  48092. BABYLON.serializeAsColor3("albedo"),
  48093. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  48094. ], PBRMaterial.prototype, "albedoColor", void 0);
  48095. __decorate([
  48096. BABYLON.serializeAsColor3("reflectivity"),
  48097. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  48098. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  48099. __decorate([
  48100. BABYLON.serializeAsColor3("reflection"),
  48101. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  48102. ], PBRMaterial.prototype, "reflectionColor", void 0);
  48103. __decorate([
  48104. BABYLON.serializeAsColor3("emissive"),
  48105. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  48106. ], PBRMaterial.prototype, "emissiveColor", void 0);
  48107. __decorate([
  48108. BABYLON.serialize(),
  48109. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  48110. ], PBRMaterial.prototype, "microSurface", void 0);
  48111. __decorate([
  48112. BABYLON.serialize(),
  48113. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  48114. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  48115. __decorate([
  48116. BABYLON.serialize(),
  48117. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  48118. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  48119. __decorate([
  48120. BABYLON.serialize(),
  48121. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  48122. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  48123. __decorate([
  48124. BABYLON.serialize(),
  48125. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  48126. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  48127. __decorate([
  48128. BABYLON.serialize(),
  48129. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  48130. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  48131. __decorate([
  48132. BABYLON.serialize(),
  48133. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  48134. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  48135. __decorate([
  48136. BABYLON.serialize(),
  48137. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  48138. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  48139. __decorate([
  48140. BABYLON.serialize(),
  48141. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  48142. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  48143. __decorate([
  48144. BABYLON.serialize(),
  48145. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  48146. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  48147. __decorate([
  48148. BABYLON.serialize(),
  48149. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  48150. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  48151. __decorate([
  48152. BABYLON.serialize(),
  48153. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  48154. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  48155. __decorate([
  48156. BABYLON.serialize(),
  48157. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  48158. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  48159. __decorate([
  48160. BABYLON.serialize(),
  48161. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  48162. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  48163. __decorate([
  48164. BABYLON.serialize(),
  48165. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  48166. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  48167. __decorate([
  48168. BABYLON.serialize(),
  48169. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  48170. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  48171. __decorate([
  48172. BABYLON.serialize()
  48173. ], PBRMaterial.prototype, "usePhysicalLightFalloff", null);
  48174. __decorate([
  48175. BABYLON.serialize()
  48176. ], PBRMaterial.prototype, "useGLTFLightFalloff", null);
  48177. __decorate([
  48178. BABYLON.serialize(),
  48179. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  48180. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  48181. __decorate([
  48182. BABYLON.serialize(),
  48183. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  48184. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  48185. __decorate([
  48186. BABYLON.serialize(),
  48187. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  48188. ], PBRMaterial.prototype, "useParallax", void 0);
  48189. __decorate([
  48190. BABYLON.serialize(),
  48191. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  48192. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  48193. __decorate([
  48194. BABYLON.serialize(),
  48195. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  48196. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  48197. __decorate([
  48198. BABYLON.serialize(),
  48199. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  48200. ], PBRMaterial.prototype, "disableLighting", void 0);
  48201. __decorate([
  48202. BABYLON.serialize(),
  48203. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  48204. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  48205. __decorate([
  48206. BABYLON.serialize(),
  48207. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  48208. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  48209. __decorate([
  48210. BABYLON.serialize(),
  48211. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  48212. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  48213. __decorate([
  48214. BABYLON.serialize(),
  48215. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  48216. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  48217. __decorate([
  48218. BABYLON.serialize(),
  48219. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  48220. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  48221. __decorate([
  48222. BABYLON.serialize(),
  48223. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  48224. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  48225. __decorate([
  48226. BABYLON.serialize(),
  48227. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  48228. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  48229. __decorate([
  48230. BABYLON.serializeAsTexture(),
  48231. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  48232. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  48233. __decorate([
  48234. BABYLON.serialize(),
  48235. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  48236. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  48237. __decorate([
  48238. BABYLON.serialize(),
  48239. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  48240. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  48241. __decorate([
  48242. BABYLON.serialize(),
  48243. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  48244. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  48245. __decorate([
  48246. BABYLON.serialize(),
  48247. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  48248. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  48249. __decorate([
  48250. BABYLON.serialize(),
  48251. BABYLON.expandToProperty("_markAllSubMeshesAsMiscDirty")
  48252. ], PBRMaterial.prototype, "unlit", void 0);
  48253. return PBRMaterial;
  48254. }(BABYLON.PBRBaseMaterial));
  48255. BABYLON.PBRMaterial = PBRMaterial;
  48256. })(BABYLON || (BABYLON = {}));
  48257. //# sourceMappingURL=babylon.pbrMaterial.js.map
  48258. var BABYLON;
  48259. (function (BABYLON) {
  48260. /**
  48261. * The PBR material of BJS following the metal roughness convention.
  48262. *
  48263. * This fits to the PBR convention in the GLTF definition:
  48264. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  48265. */
  48266. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  48267. __extends(PBRMetallicRoughnessMaterial, _super);
  48268. /**
  48269. * Instantiates a new PBRMetalRoughnessMaterial instance.
  48270. *
  48271. * @param name The material name
  48272. * @param scene The scene the material will be use in.
  48273. */
  48274. function PBRMetallicRoughnessMaterial(name, scene) {
  48275. var _this = _super.call(this, name, scene) || this;
  48276. _this._useRoughnessFromMetallicTextureAlpha = false;
  48277. _this._useRoughnessFromMetallicTextureGreen = true;
  48278. _this._useMetallnessFromMetallicTextureBlue = true;
  48279. _this.metallic = 1.0;
  48280. _this.roughness = 1.0;
  48281. return _this;
  48282. }
  48283. /**
  48284. * Return the currrent class name of the material.
  48285. */
  48286. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  48287. return "PBRMetallicRoughnessMaterial";
  48288. };
  48289. /**
  48290. * Return the active textures of the material.
  48291. */
  48292. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  48293. var activeTextures = _super.prototype.getActiveTextures.call(this);
  48294. if (this.baseTexture) {
  48295. activeTextures.push(this.baseTexture);
  48296. }
  48297. if (this.metallicRoughnessTexture) {
  48298. activeTextures.push(this.metallicRoughnessTexture);
  48299. }
  48300. return activeTextures;
  48301. };
  48302. /**
  48303. * Checks to see if a texture is used in the material.
  48304. * @param texture - Base texture to use.
  48305. * @returns - Boolean specifying if a texture is used in the material.
  48306. */
  48307. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  48308. if (_super.prototype.hasTexture.call(this, texture)) {
  48309. return true;
  48310. }
  48311. if (this.baseTexture === texture) {
  48312. return true;
  48313. }
  48314. if (this.metallicRoughnessTexture === texture) {
  48315. return true;
  48316. }
  48317. return false;
  48318. };
  48319. /**
  48320. * Makes a duplicate of the current material.
  48321. * @param name - name to use for the new material.
  48322. */
  48323. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  48324. var _this = this;
  48325. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  48326. clone.id = name;
  48327. clone.name = name;
  48328. return clone;
  48329. };
  48330. /**
  48331. * Serialize the material to a parsable JSON object.
  48332. */
  48333. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  48334. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  48335. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  48336. return serializationObject;
  48337. };
  48338. /**
  48339. * Parses a JSON object correponding to the serialize function.
  48340. */
  48341. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  48342. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  48343. };
  48344. __decorate([
  48345. BABYLON.serializeAsColor3(),
  48346. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  48347. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  48348. __decorate([
  48349. BABYLON.serializeAsTexture(),
  48350. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  48351. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  48352. __decorate([
  48353. BABYLON.serialize(),
  48354. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  48355. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  48356. __decorate([
  48357. BABYLON.serialize(),
  48358. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  48359. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  48360. __decorate([
  48361. BABYLON.serializeAsTexture(),
  48362. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  48363. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  48364. return PBRMetallicRoughnessMaterial;
  48365. }(BABYLON.PBRBaseSimpleMaterial));
  48366. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  48367. })(BABYLON || (BABYLON = {}));
  48368. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  48369. var BABYLON;
  48370. (function (BABYLON) {
  48371. /**
  48372. * The PBR material of BJS following the specular glossiness convention.
  48373. *
  48374. * This fits to the PBR convention in the GLTF definition:
  48375. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  48376. */
  48377. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  48378. __extends(PBRSpecularGlossinessMaterial, _super);
  48379. /**
  48380. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  48381. *
  48382. * @param name The material name
  48383. * @param scene The scene the material will be use in.
  48384. */
  48385. function PBRSpecularGlossinessMaterial(name, scene) {
  48386. var _this = _super.call(this, name, scene) || this;
  48387. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  48388. return _this;
  48389. }
  48390. /**
  48391. * Return the currrent class name of the material.
  48392. */
  48393. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  48394. return "PBRSpecularGlossinessMaterial";
  48395. };
  48396. /**
  48397. * Return the active textures of the material.
  48398. */
  48399. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  48400. var activeTextures = _super.prototype.getActiveTextures.call(this);
  48401. if (this.diffuseTexture) {
  48402. activeTextures.push(this.diffuseTexture);
  48403. }
  48404. if (this.specularGlossinessTexture) {
  48405. activeTextures.push(this.specularGlossinessTexture);
  48406. }
  48407. return activeTextures;
  48408. };
  48409. /**
  48410. * Checks to see if a texture is used in the material.
  48411. * @param texture - Base texture to use.
  48412. * @returns - Boolean specifying if a texture is used in the material.
  48413. */
  48414. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  48415. if (_super.prototype.hasTexture.call(this, texture)) {
  48416. return true;
  48417. }
  48418. if (this.diffuseTexture === texture) {
  48419. return true;
  48420. }
  48421. if (this.specularGlossinessTexture === texture) {
  48422. return true;
  48423. }
  48424. return false;
  48425. };
  48426. /**
  48427. * Makes a duplicate of the current material.
  48428. * @param name - name to use for the new material.
  48429. */
  48430. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  48431. var _this = this;
  48432. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  48433. clone.id = name;
  48434. clone.name = name;
  48435. return clone;
  48436. };
  48437. /**
  48438. * Serialize the material to a parsable JSON object.
  48439. */
  48440. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  48441. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  48442. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  48443. return serializationObject;
  48444. };
  48445. /**
  48446. * Parses a JSON object correponding to the serialize function.
  48447. */
  48448. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  48449. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  48450. };
  48451. __decorate([
  48452. BABYLON.serializeAsColor3("diffuse"),
  48453. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  48454. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  48455. __decorate([
  48456. BABYLON.serializeAsTexture(),
  48457. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  48458. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  48459. __decorate([
  48460. BABYLON.serializeAsColor3("specular"),
  48461. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  48462. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  48463. __decorate([
  48464. BABYLON.serialize(),
  48465. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  48466. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  48467. __decorate([
  48468. BABYLON.serializeAsTexture(),
  48469. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  48470. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  48471. return PBRSpecularGlossinessMaterial;
  48472. }(BABYLON.PBRBaseSimpleMaterial));
  48473. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  48474. })(BABYLON || (BABYLON = {}));
  48475. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  48476. var BABYLON;
  48477. (function (BABYLON) {
  48478. /**
  48479. * @ignore
  48480. * This is a list of all the different input types that are available in the application.
  48481. * Fo instance: ArcRotateCameraGamepadInput...
  48482. */
  48483. BABYLON.CameraInputTypes = {};
  48484. /**
  48485. * This represents the input manager used within a camera.
  48486. * It helps dealing with all the different kind of input attached to a camera.
  48487. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  48488. */
  48489. var CameraInputsManager = /** @class */ (function () {
  48490. /**
  48491. * Instantiate a new Camera Input Manager.
  48492. * @param camera Defines the camera the input manager blongs to
  48493. */
  48494. function CameraInputsManager(camera) {
  48495. this.attached = {};
  48496. this.camera = camera;
  48497. this.checkInputs = function () { };
  48498. }
  48499. /**
  48500. * Add an input method to a camera
  48501. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  48502. * @param input camera input method
  48503. */
  48504. CameraInputsManager.prototype.add = function (input) {
  48505. var type = input.getSimpleName();
  48506. if (this.attached[type]) {
  48507. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  48508. return;
  48509. }
  48510. this.attached[type] = input;
  48511. input.camera = this.camera;
  48512. //for checkInputs, we are dynamically creating a function
  48513. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  48514. if (input.checkInputs) {
  48515. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  48516. }
  48517. if (this.attachedElement) {
  48518. input.attachControl(this.attachedElement);
  48519. }
  48520. };
  48521. /**
  48522. * Remove a specific input method from a camera
  48523. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  48524. * @param inputToRemove camera input method
  48525. */
  48526. CameraInputsManager.prototype.remove = function (inputToRemove) {
  48527. for (var cam in this.attached) {
  48528. var input = this.attached[cam];
  48529. if (input === inputToRemove) {
  48530. input.detachControl(this.attachedElement);
  48531. input.camera = null;
  48532. delete this.attached[cam];
  48533. this.rebuildInputCheck();
  48534. }
  48535. }
  48536. };
  48537. /**
  48538. * Remove a specific input type from a camera
  48539. * example: camera.inputs.remove("ArcRotateCameraGamepadInput");
  48540. * @param inputType the type of the input to remove
  48541. */
  48542. CameraInputsManager.prototype.removeByType = function (inputType) {
  48543. for (var cam in this.attached) {
  48544. var input = this.attached[cam];
  48545. if (input.getClassName() === inputType) {
  48546. input.detachControl(this.attachedElement);
  48547. input.camera = null;
  48548. delete this.attached[cam];
  48549. this.rebuildInputCheck();
  48550. }
  48551. }
  48552. };
  48553. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  48554. var current = this.checkInputs;
  48555. return function () {
  48556. current();
  48557. fn();
  48558. };
  48559. };
  48560. /**
  48561. * Attach the input controls to the currently attached dom element to listen the events from.
  48562. * @param input Defines the input to attach
  48563. */
  48564. CameraInputsManager.prototype.attachInput = function (input) {
  48565. if (this.attachedElement) {
  48566. input.attachControl(this.attachedElement, this.noPreventDefault);
  48567. }
  48568. };
  48569. /**
  48570. * Attach the current manager inputs controls to a specific dom element to listen the events from.
  48571. * @param element Defines the dom element to collect the events from
  48572. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  48573. */
  48574. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  48575. if (noPreventDefault === void 0) { noPreventDefault = false; }
  48576. if (this.attachedElement) {
  48577. return;
  48578. }
  48579. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  48580. this.attachedElement = element;
  48581. this.noPreventDefault = noPreventDefault;
  48582. for (var cam in this.attached) {
  48583. this.attached[cam].attachControl(element, noPreventDefault);
  48584. }
  48585. };
  48586. /**
  48587. * Detach the current manager inputs controls from a specific dom element.
  48588. * @param element Defines the dom element to collect the events from
  48589. * @param disconnect Defines whether the input should be removed from the current list of attached inputs
  48590. */
  48591. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  48592. if (disconnect === void 0) { disconnect = false; }
  48593. if (this.attachedElement !== element) {
  48594. return;
  48595. }
  48596. for (var cam in this.attached) {
  48597. this.attached[cam].detachControl(element);
  48598. if (disconnect) {
  48599. this.attached[cam].camera = null;
  48600. }
  48601. }
  48602. this.attachedElement = null;
  48603. };
  48604. /**
  48605. * Rebuild the dynamic inputCheck function from the current list of
  48606. * defined inputs in the manager.
  48607. */
  48608. CameraInputsManager.prototype.rebuildInputCheck = function () {
  48609. this.checkInputs = function () { };
  48610. for (var cam in this.attached) {
  48611. var input = this.attached[cam];
  48612. if (input.checkInputs) {
  48613. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  48614. }
  48615. }
  48616. };
  48617. /**
  48618. * Remove all attached input methods from a camera
  48619. */
  48620. CameraInputsManager.prototype.clear = function () {
  48621. if (this.attachedElement) {
  48622. this.detachElement(this.attachedElement, true);
  48623. }
  48624. this.attached = {};
  48625. this.attachedElement = null;
  48626. this.checkInputs = function () { };
  48627. };
  48628. /**
  48629. * Serialize the current input manager attached to a camera.
  48630. * This ensures than once parsed,
  48631. * the input associated to the camera will be identical to the current ones
  48632. * @param serializedCamera Defines the camera serialization JSON the input serialization should write to
  48633. */
  48634. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  48635. var inputs = {};
  48636. for (var cam in this.attached) {
  48637. var input = this.attached[cam];
  48638. var res = BABYLON.SerializationHelper.Serialize(input);
  48639. inputs[input.getClassName()] = res;
  48640. }
  48641. serializedCamera.inputsmgr = inputs;
  48642. };
  48643. /**
  48644. * Parses an input manager serialized JSON to restore the previous list of inputs
  48645. * and states associated to a camera.
  48646. * @param parsedCamera Defines the JSON to parse
  48647. */
  48648. CameraInputsManager.prototype.parse = function (parsedCamera) {
  48649. var parsedInputs = parsedCamera.inputsmgr;
  48650. if (parsedInputs) {
  48651. this.clear();
  48652. for (var n in parsedInputs) {
  48653. var construct = BABYLON.CameraInputTypes[n];
  48654. if (construct) {
  48655. var parsedinput = parsedInputs[n];
  48656. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  48657. this.add(input);
  48658. }
  48659. }
  48660. }
  48661. else {
  48662. //2016-03-08 this part is for managing backward compatibility
  48663. for (var n in this.attached) {
  48664. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  48665. if (construct) {
  48666. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  48667. this.remove(this.attached[n]);
  48668. this.add(input);
  48669. }
  48670. }
  48671. }
  48672. };
  48673. return CameraInputsManager;
  48674. }());
  48675. BABYLON.CameraInputsManager = CameraInputsManager;
  48676. })(BABYLON || (BABYLON = {}));
  48677. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  48678. var BABYLON;
  48679. (function (BABYLON) {
  48680. /**
  48681. * A target camera takes a mesh or position as a target and continues to look at it while it moves.
  48682. * This is the base of the follow, arc rotate cameras and Free camera
  48683. * @see http://doc.babylonjs.com/features/cameras
  48684. */
  48685. var TargetCamera = /** @class */ (function (_super) {
  48686. __extends(TargetCamera, _super);
  48687. /**
  48688. * Instantiates a target camera that takes a meshor position as a target and continues to look at it while it moves.
  48689. * This is the base of the follow, arc rotate cameras and Free camera
  48690. * @see http://doc.babylonjs.com/features/cameras
  48691. * @param name Defines the name of the camera in the scene
  48692. * @param position Defines the start position of the camera in the scene
  48693. * @param scene Defines the scene the camera belongs to
  48694. * @param setActiveOnSceneIfNoneActive Defines wheter the camera should be marked as active if not other active cameras have been defined
  48695. */
  48696. function TargetCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  48697. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  48698. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  48699. /**
  48700. * Define the current direction the camera is moving to
  48701. */
  48702. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  48703. /**
  48704. * Define the current rotation the camera is rotating to
  48705. */
  48706. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  48707. /**
  48708. * When set, the up vector of the camera will be updated by the rotation of the camera
  48709. */
  48710. _this.updateUpVectorFromRotation = false;
  48711. _this._tmpQuaternion = new BABYLON.Quaternion();
  48712. /**
  48713. * Define the current rotation of the camera
  48714. */
  48715. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  48716. /**
  48717. * Define the current speed of the camera
  48718. */
  48719. _this.speed = 2.0;
  48720. /**
  48721. * Add cconstraint to the camera to prevent it to move freely in all directions and
  48722. * around all axis.
  48723. */
  48724. _this.noRotationConstraint = false;
  48725. /**
  48726. * Define the current target of the camera as an object or a position.
  48727. */
  48728. _this.lockedTarget = null;
  48729. /** @hidden */
  48730. _this._currentTarget = BABYLON.Vector3.Zero();
  48731. /** @hidden */
  48732. _this._viewMatrix = BABYLON.Matrix.Zero();
  48733. /** @hidden */
  48734. _this._camMatrix = BABYLON.Matrix.Zero();
  48735. /** @hidden */
  48736. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  48737. /** @hidden */
  48738. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  48739. /** @hidden */
  48740. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  48741. /** @hidden */
  48742. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  48743. _this._globalCurrentTarget = BABYLON.Vector3.Zero();
  48744. _this._globalCurrentUpVector = BABYLON.Vector3.Zero();
  48745. _this._defaultUp = BABYLON.Vector3.Up();
  48746. _this._cachedRotationZ = 0;
  48747. _this._cachedQuaternionRotationZ = 0;
  48748. return _this;
  48749. }
  48750. /**
  48751. * Gets the position in front of the camera at a given distance.
  48752. * @param distance The distance from the camera we want the position to be
  48753. * @returns the position
  48754. */
  48755. TargetCamera.prototype.getFrontPosition = function (distance) {
  48756. this.getWorldMatrix();
  48757. var direction = this.getTarget().subtract(this.position);
  48758. direction.normalize();
  48759. direction.scaleInPlace(distance);
  48760. return this.globalPosition.add(direction);
  48761. };
  48762. /** @hidden */
  48763. TargetCamera.prototype._getLockedTargetPosition = function () {
  48764. if (!this.lockedTarget) {
  48765. return null;
  48766. }
  48767. if (this.lockedTarget.absolutePosition) {
  48768. this.lockedTarget.computeWorldMatrix();
  48769. }
  48770. return this.lockedTarget.absolutePosition || this.lockedTarget;
  48771. };
  48772. /**
  48773. * Store current camera state of the camera (fov, position, rotation, etc..)
  48774. * @returns the camera
  48775. */
  48776. TargetCamera.prototype.storeState = function () {
  48777. this._storedPosition = this.position.clone();
  48778. this._storedRotation = this.rotation.clone();
  48779. if (this.rotationQuaternion) {
  48780. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  48781. }
  48782. return _super.prototype.storeState.call(this);
  48783. };
  48784. /**
  48785. * Restored camera state. You must call storeState() first
  48786. * @returns whether it was successful or not
  48787. * @hidden
  48788. */
  48789. TargetCamera.prototype._restoreStateValues = function () {
  48790. if (!_super.prototype._restoreStateValues.call(this)) {
  48791. return false;
  48792. }
  48793. this.position = this._storedPosition.clone();
  48794. this.rotation = this._storedRotation.clone();
  48795. if (this.rotationQuaternion) {
  48796. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  48797. }
  48798. this.cameraDirection.copyFromFloats(0, 0, 0);
  48799. this.cameraRotation.copyFromFloats(0, 0);
  48800. return true;
  48801. };
  48802. /** @hidden */
  48803. TargetCamera.prototype._initCache = function () {
  48804. _super.prototype._initCache.call(this);
  48805. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  48806. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  48807. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  48808. };
  48809. /** @hidden */
  48810. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  48811. if (!ignoreParentClass) {
  48812. _super.prototype._updateCache.call(this);
  48813. }
  48814. var lockedTargetPosition = this._getLockedTargetPosition();
  48815. if (!lockedTargetPosition) {
  48816. this._cache.lockedTarget = null;
  48817. }
  48818. else {
  48819. if (!this._cache.lockedTarget) {
  48820. this._cache.lockedTarget = lockedTargetPosition.clone();
  48821. }
  48822. else {
  48823. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  48824. }
  48825. }
  48826. this._cache.rotation.copyFrom(this.rotation);
  48827. if (this.rotationQuaternion) {
  48828. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  48829. }
  48830. };
  48831. // Synchronized
  48832. /** @hidden */
  48833. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  48834. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  48835. return false;
  48836. }
  48837. var lockedTargetPosition = this._getLockedTargetPosition();
  48838. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  48839. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  48840. };
  48841. // Methods
  48842. /** @hidden */
  48843. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  48844. var engine = this.getEngine();
  48845. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  48846. };
  48847. // Target
  48848. /** @hidden */
  48849. TargetCamera.prototype.setTarget = function (target) {
  48850. this.upVector.normalize();
  48851. if (this.position.z === target.z) {
  48852. this.position.z += BABYLON.Epsilon;
  48853. }
  48854. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUp, this._camMatrix);
  48855. this._camMatrix.invert();
  48856. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  48857. var vDir = target.subtract(this.position);
  48858. if (vDir.x >= 0.0) {
  48859. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  48860. }
  48861. else {
  48862. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  48863. }
  48864. this.rotation.z = 0;
  48865. if (isNaN(this.rotation.x)) {
  48866. this.rotation.x = 0;
  48867. }
  48868. if (isNaN(this.rotation.y)) {
  48869. this.rotation.y = 0;
  48870. }
  48871. if (isNaN(this.rotation.z)) {
  48872. this.rotation.z = 0;
  48873. }
  48874. if (this.rotationQuaternion) {
  48875. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  48876. }
  48877. };
  48878. /**
  48879. * Return the current target position of the camera. This value is expressed in local space.
  48880. * @returns the target position
  48881. */
  48882. TargetCamera.prototype.getTarget = function () {
  48883. return this._currentTarget;
  48884. };
  48885. /** @hidden */
  48886. TargetCamera.prototype._decideIfNeedsToMove = function () {
  48887. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  48888. };
  48889. /** @hidden */
  48890. TargetCamera.prototype._updatePosition = function () {
  48891. if (this.parent) {
  48892. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  48893. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  48894. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  48895. return;
  48896. }
  48897. this.position.addInPlace(this.cameraDirection);
  48898. };
  48899. /** @hidden */
  48900. TargetCamera.prototype._checkInputs = function () {
  48901. var needToMove = this._decideIfNeedsToMove();
  48902. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  48903. // Move
  48904. if (needToMove) {
  48905. this._updatePosition();
  48906. }
  48907. // Rotate
  48908. if (needToRotate) {
  48909. this.rotation.x += this.cameraRotation.x;
  48910. this.rotation.y += this.cameraRotation.y;
  48911. //rotate, if quaternion is set and rotation was used
  48912. if (this.rotationQuaternion) {
  48913. var len = this.rotation.lengthSquared();
  48914. if (len) {
  48915. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  48916. }
  48917. }
  48918. if (!this.noRotationConstraint) {
  48919. var limit = (Math.PI / 2) * 0.95;
  48920. if (this.rotation.x > limit) {
  48921. this.rotation.x = limit;
  48922. }
  48923. if (this.rotation.x < -limit) {
  48924. this.rotation.x = -limit;
  48925. }
  48926. }
  48927. }
  48928. // Inertia
  48929. if (needToMove) {
  48930. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  48931. this.cameraDirection.x = 0;
  48932. }
  48933. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  48934. this.cameraDirection.y = 0;
  48935. }
  48936. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  48937. this.cameraDirection.z = 0;
  48938. }
  48939. this.cameraDirection.scaleInPlace(this.inertia);
  48940. }
  48941. if (needToRotate) {
  48942. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  48943. this.cameraRotation.x = 0;
  48944. }
  48945. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  48946. this.cameraRotation.y = 0;
  48947. }
  48948. this.cameraRotation.scaleInPlace(this.inertia);
  48949. }
  48950. _super.prototype._checkInputs.call(this);
  48951. };
  48952. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  48953. if (this.rotationQuaternion) {
  48954. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  48955. }
  48956. else {
  48957. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  48958. }
  48959. };
  48960. /**
  48961. * 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)
  48962. * @returns the current camera
  48963. */
  48964. TargetCamera.prototype._rotateUpVectorWithCameraRotationMatrix = function () {
  48965. BABYLON.Vector3.TransformNormalToRef(this._defaultUp, this._cameraRotationMatrix, this.upVector);
  48966. return this;
  48967. };
  48968. /** @hidden */
  48969. TargetCamera.prototype._getViewMatrix = function () {
  48970. if (this.lockedTarget) {
  48971. this.setTarget(this._getLockedTargetPosition());
  48972. }
  48973. // Compute
  48974. this._updateCameraRotationMatrix();
  48975. // Apply the changed rotation to the upVector
  48976. if (this.rotationQuaternion && this._cachedQuaternionRotationZ != this.rotationQuaternion.z) {
  48977. this._rotateUpVectorWithCameraRotationMatrix();
  48978. this._cachedQuaternionRotationZ = this.rotationQuaternion.z;
  48979. }
  48980. else if (this._cachedRotationZ != this.rotation.z) {
  48981. this._rotateUpVectorWithCameraRotationMatrix();
  48982. this._cachedRotationZ = this.rotation.z;
  48983. }
  48984. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  48985. // Computing target and final matrix
  48986. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  48987. if (this.updateUpVectorFromRotation) {
  48988. if (this.rotationQuaternion) {
  48989. BABYLON.Axis.Y.rotateByQuaternionToRef(this.rotationQuaternion, this.upVector);
  48990. }
  48991. else {
  48992. BABYLON.Quaternion.FromEulerVectorToRef(this.rotation, this._tmpQuaternion);
  48993. BABYLON.Axis.Y.rotateByQuaternionToRef(this._tmpQuaternion, this.upVector);
  48994. }
  48995. }
  48996. this._computeViewMatrix(this.position, this._currentTarget, this.upVector);
  48997. return this._viewMatrix;
  48998. };
  48999. TargetCamera.prototype._computeViewMatrix = function (position, target, up) {
  49000. if (this.parent) {
  49001. var parentWorldMatrix = this.parent.getWorldMatrix();
  49002. BABYLON.Vector3.TransformCoordinatesToRef(position, parentWorldMatrix, this._globalPosition);
  49003. BABYLON.Vector3.TransformCoordinatesToRef(target, parentWorldMatrix, this._globalCurrentTarget);
  49004. BABYLON.Vector3.TransformNormalToRef(up, parentWorldMatrix, this._globalCurrentUpVector);
  49005. this._markSyncedWithParent();
  49006. }
  49007. else {
  49008. this._globalPosition.copyFrom(position);
  49009. this._globalCurrentTarget.copyFrom(target);
  49010. this._globalCurrentUpVector.copyFrom(up);
  49011. }
  49012. if (this.getScene().useRightHandedSystem) {
  49013. BABYLON.Matrix.LookAtRHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  49014. }
  49015. else {
  49016. BABYLON.Matrix.LookAtLHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  49017. }
  49018. };
  49019. /**
  49020. * @hidden
  49021. */
  49022. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  49023. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  49024. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  49025. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  49026. if (!this.rotationQuaternion) {
  49027. this.rotationQuaternion = new BABYLON.Quaternion();
  49028. }
  49029. rigCamera._cameraRigParams = {};
  49030. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  49031. }
  49032. return rigCamera;
  49033. }
  49034. return null;
  49035. };
  49036. /**
  49037. * @hidden
  49038. */
  49039. TargetCamera.prototype._updateRigCameras = function () {
  49040. var camLeft = this._rigCameras[0];
  49041. var camRight = this._rigCameras[1];
  49042. this.computeWorldMatrix();
  49043. switch (this.cameraRigMode) {
  49044. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  49045. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  49046. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  49047. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  49048. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  49049. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  49050. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  49051. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  49052. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  49053. camLeft.setTarget(this.getTarget());
  49054. camRight.setTarget(this.getTarget());
  49055. break;
  49056. case BABYLON.Camera.RIG_MODE_VR:
  49057. if (camLeft.rotationQuaternion) {
  49058. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  49059. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  49060. }
  49061. else {
  49062. camLeft.rotation.copyFrom(this.rotation);
  49063. camRight.rotation.copyFrom(this.rotation);
  49064. }
  49065. camLeft.position.copyFrom(this.position);
  49066. camRight.position.copyFrom(this.position);
  49067. break;
  49068. }
  49069. _super.prototype._updateRigCameras.call(this);
  49070. };
  49071. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  49072. var target = this.getTarget();
  49073. BABYLON.Matrix.TranslationToRef(-target.x, -target.y, -target.z, TargetCamera._TargetTransformMatrix);
  49074. TargetCamera._TargetTransformMatrix.multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), TargetCamera._RigCamTransformMatrix);
  49075. BABYLON.Matrix.TranslationToRef(target.x, target.y, target.z, TargetCamera._TargetTransformMatrix);
  49076. TargetCamera._RigCamTransformMatrix.multiplyToRef(TargetCamera._TargetTransformMatrix, TargetCamera._RigCamTransformMatrix);
  49077. BABYLON.Vector3.TransformCoordinatesToRef(this.position, TargetCamera._RigCamTransformMatrix, result);
  49078. };
  49079. /**
  49080. * Gets the current object class name.
  49081. * @return the class name
  49082. */
  49083. TargetCamera.prototype.getClassName = function () {
  49084. return "TargetCamera";
  49085. };
  49086. TargetCamera._RigCamTransformMatrix = new BABYLON.Matrix();
  49087. TargetCamera._TargetTransformMatrix = new BABYLON.Matrix();
  49088. __decorate([
  49089. BABYLON.serializeAsVector3()
  49090. ], TargetCamera.prototype, "rotation", void 0);
  49091. __decorate([
  49092. BABYLON.serialize()
  49093. ], TargetCamera.prototype, "speed", void 0);
  49094. __decorate([
  49095. BABYLON.serializeAsMeshReference("lockedTargetId")
  49096. ], TargetCamera.prototype, "lockedTarget", void 0);
  49097. return TargetCamera;
  49098. }(BABYLON.Camera));
  49099. BABYLON.TargetCamera = TargetCamera;
  49100. })(BABYLON || (BABYLON = {}));
  49101. //# sourceMappingURL=babylon.targetCamera.js.map
  49102. var BABYLON;
  49103. (function (BABYLON) {
  49104. /**
  49105. * Manage the mouse inputs to control the movement of a free camera.
  49106. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  49107. */
  49108. var FreeCameraMouseInput = /** @class */ (function () {
  49109. /**
  49110. * Manage the mouse inputs to control the movement of a free camera.
  49111. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  49112. * @param touchEnabled Defines if touch is enabled or not
  49113. */
  49114. function FreeCameraMouseInput(
  49115. /**
  49116. * Define if touch is enabled in the mouse input
  49117. */
  49118. touchEnabled) {
  49119. if (touchEnabled === void 0) { touchEnabled = true; }
  49120. this.touchEnabled = touchEnabled;
  49121. /**
  49122. * Defines the buttons associated with the input to handle camera move.
  49123. */
  49124. this.buttons = [0, 1, 2];
  49125. /**
  49126. * Defines the pointer angular sensibility along the X and Y axis or how fast is the camera rotating.
  49127. */
  49128. this.angularSensibility = 2000.0;
  49129. this.previousPosition = null;
  49130. }
  49131. /**
  49132. * Attach the input controls to a specific dom element to get the input from.
  49133. * @param element Defines the element the controls should be listened from
  49134. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  49135. */
  49136. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  49137. var _this = this;
  49138. var engine = this.camera.getEngine();
  49139. if (!this._pointerInput) {
  49140. this._pointerInput = function (p, s) {
  49141. var evt = p.event;
  49142. if (engine.isInVRExclusivePointerMode) {
  49143. return;
  49144. }
  49145. if (!_this.touchEnabled && evt.pointerType === "touch") {
  49146. return;
  49147. }
  49148. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  49149. return;
  49150. }
  49151. var srcElement = (evt.srcElement || evt.target);
  49152. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  49153. try {
  49154. srcElement.setPointerCapture(evt.pointerId);
  49155. }
  49156. catch (e) {
  49157. //Nothing to do with the error. Execution will continue.
  49158. }
  49159. _this.previousPosition = {
  49160. x: evt.clientX,
  49161. y: evt.clientY
  49162. };
  49163. if (!noPreventDefault) {
  49164. evt.preventDefault();
  49165. element.focus();
  49166. }
  49167. }
  49168. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  49169. try {
  49170. srcElement.releasePointerCapture(evt.pointerId);
  49171. }
  49172. catch (e) {
  49173. //Nothing to do with the error.
  49174. }
  49175. _this.previousPosition = null;
  49176. if (!noPreventDefault) {
  49177. evt.preventDefault();
  49178. }
  49179. }
  49180. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  49181. if (!_this.previousPosition || engine.isPointerLock) {
  49182. return;
  49183. }
  49184. var offsetX = evt.clientX - _this.previousPosition.x;
  49185. if (_this.camera.getScene().useRightHandedSystem) {
  49186. offsetX *= -1;
  49187. }
  49188. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0) {
  49189. offsetX *= -1;
  49190. }
  49191. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  49192. var offsetY = evt.clientY - _this.previousPosition.y;
  49193. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  49194. _this.previousPosition = {
  49195. x: evt.clientX,
  49196. y: evt.clientY
  49197. };
  49198. if (!noPreventDefault) {
  49199. evt.preventDefault();
  49200. }
  49201. }
  49202. };
  49203. }
  49204. this._onMouseMove = function (evt) {
  49205. if (!engine.isPointerLock) {
  49206. return;
  49207. }
  49208. if (engine.isInVRExclusivePointerMode) {
  49209. return;
  49210. }
  49211. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  49212. if (_this.camera.getScene().useRightHandedSystem) {
  49213. offsetX *= -1;
  49214. }
  49215. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0) {
  49216. offsetX *= -1;
  49217. }
  49218. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  49219. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  49220. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  49221. _this.previousPosition = null;
  49222. if (!noPreventDefault) {
  49223. evt.preventDefault();
  49224. }
  49225. };
  49226. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  49227. element.addEventListener("mousemove", this._onMouseMove, false);
  49228. };
  49229. /**
  49230. * Detach the current controls from the specified dom element.
  49231. * @param element Defines the element to stop listening the inputs from
  49232. */
  49233. FreeCameraMouseInput.prototype.detachControl = function (element) {
  49234. if (this._observer && element) {
  49235. this.camera.getScene().onPointerObservable.remove(this._observer);
  49236. if (this._onMouseMove) {
  49237. element.removeEventListener("mousemove", this._onMouseMove);
  49238. }
  49239. this._observer = null;
  49240. this._onMouseMove = null;
  49241. this.previousPosition = null;
  49242. }
  49243. };
  49244. /**
  49245. * Gets the class name of the current intput.
  49246. * @returns the class name
  49247. */
  49248. FreeCameraMouseInput.prototype.getClassName = function () {
  49249. return "FreeCameraMouseInput";
  49250. };
  49251. /**
  49252. * Get the friendly name associated with the input class.
  49253. * @returns the input friendly name
  49254. */
  49255. FreeCameraMouseInput.prototype.getSimpleName = function () {
  49256. return "mouse";
  49257. };
  49258. __decorate([
  49259. BABYLON.serialize()
  49260. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  49261. __decorate([
  49262. BABYLON.serialize()
  49263. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  49264. return FreeCameraMouseInput;
  49265. }());
  49266. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  49267. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  49268. })(BABYLON || (BABYLON = {}));
  49269. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  49270. var BABYLON;
  49271. (function (BABYLON) {
  49272. /**
  49273. * Manage the keyboard inputs to control the movement of a free camera.
  49274. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  49275. */
  49276. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  49277. function FreeCameraKeyboardMoveInput() {
  49278. /**
  49279. * Gets or Set the list of keyboard keys used to control the forward move of the camera.
  49280. */
  49281. this.keysUp = [38];
  49282. /**
  49283. * Gets or Set the list of keyboard keys used to control the backward move of the camera.
  49284. */
  49285. this.keysDown = [40];
  49286. /**
  49287. * Gets or Set the list of keyboard keys used to control the left strafe move of the camera.
  49288. */
  49289. this.keysLeft = [37];
  49290. /**
  49291. * Gets or Set the list of keyboard keys used to control the right strafe move of the camera.
  49292. */
  49293. this.keysRight = [39];
  49294. this._keys = new Array();
  49295. }
  49296. /**
  49297. * Attach the input controls to a specific dom element to get the input from.
  49298. * @param element Defines the element the controls should be listened from
  49299. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  49300. */
  49301. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  49302. var _this = this;
  49303. if (this._onCanvasBlurObserver) {
  49304. return;
  49305. }
  49306. this._scene = this.camera.getScene();
  49307. this._engine = this._scene.getEngine();
  49308. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  49309. _this._keys = [];
  49310. });
  49311. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  49312. var evt = info.event;
  49313. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  49314. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  49315. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  49316. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  49317. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  49318. var index = _this._keys.indexOf(evt.keyCode);
  49319. if (index === -1) {
  49320. _this._keys.push(evt.keyCode);
  49321. }
  49322. if (!noPreventDefault) {
  49323. evt.preventDefault();
  49324. }
  49325. }
  49326. }
  49327. else {
  49328. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  49329. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  49330. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  49331. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  49332. var index = _this._keys.indexOf(evt.keyCode);
  49333. if (index >= 0) {
  49334. _this._keys.splice(index, 1);
  49335. }
  49336. if (!noPreventDefault) {
  49337. evt.preventDefault();
  49338. }
  49339. }
  49340. }
  49341. });
  49342. };
  49343. /**
  49344. * Detach the current controls from the specified dom element.
  49345. * @param element Defines the element to stop listening the inputs from
  49346. */
  49347. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  49348. if (this._scene) {
  49349. if (this._onKeyboardObserver) {
  49350. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  49351. }
  49352. if (this._onCanvasBlurObserver) {
  49353. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  49354. }
  49355. this._onKeyboardObserver = null;
  49356. this._onCanvasBlurObserver = null;
  49357. }
  49358. this._keys = [];
  49359. };
  49360. /**
  49361. * Update the current camera state depending on the inputs that have been used this frame.
  49362. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  49363. */
  49364. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  49365. if (this._onKeyboardObserver) {
  49366. var camera = this.camera;
  49367. // Keyboard
  49368. for (var index = 0; index < this._keys.length; index++) {
  49369. var keyCode = this._keys[index];
  49370. var speed = camera._computeLocalCameraSpeed();
  49371. if (this.keysLeft.indexOf(keyCode) !== -1) {
  49372. camera._localDirection.copyFromFloats(-speed, 0, 0);
  49373. }
  49374. else if (this.keysUp.indexOf(keyCode) !== -1) {
  49375. camera._localDirection.copyFromFloats(0, 0, speed);
  49376. }
  49377. else if (this.keysRight.indexOf(keyCode) !== -1) {
  49378. camera._localDirection.copyFromFloats(speed, 0, 0);
  49379. }
  49380. else if (this.keysDown.indexOf(keyCode) !== -1) {
  49381. camera._localDirection.copyFromFloats(0, 0, -speed);
  49382. }
  49383. if (camera.getScene().useRightHandedSystem) {
  49384. camera._localDirection.z *= -1;
  49385. }
  49386. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  49387. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  49388. camera.cameraDirection.addInPlace(camera._transformedDirection);
  49389. }
  49390. }
  49391. };
  49392. /**
  49393. * Gets the class name of the current intput.
  49394. * @returns the class name
  49395. */
  49396. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  49397. return "FreeCameraKeyboardMoveInput";
  49398. };
  49399. /** @hidden */
  49400. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  49401. this._keys = [];
  49402. };
  49403. /**
  49404. * Get the friendly name associated with the input class.
  49405. * @returns the input friendly name
  49406. */
  49407. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  49408. return "keyboard";
  49409. };
  49410. __decorate([
  49411. BABYLON.serialize()
  49412. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  49413. __decorate([
  49414. BABYLON.serialize()
  49415. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  49416. __decorate([
  49417. BABYLON.serialize()
  49418. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  49419. __decorate([
  49420. BABYLON.serialize()
  49421. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  49422. return FreeCameraKeyboardMoveInput;
  49423. }());
  49424. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  49425. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  49426. })(BABYLON || (BABYLON = {}));
  49427. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  49428. var BABYLON;
  49429. (function (BABYLON) {
  49430. /**
  49431. * Default Inputs manager for the FreeCamera.
  49432. * It groups all the default supported inputs for ease of use.
  49433. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  49434. */
  49435. var FreeCameraInputsManager = /** @class */ (function (_super) {
  49436. __extends(FreeCameraInputsManager, _super);
  49437. /**
  49438. * Instantiates a new FreeCameraInputsManager.
  49439. * @param camera Defines the camera the inputs belong to
  49440. */
  49441. function FreeCameraInputsManager(camera) {
  49442. return _super.call(this, camera) || this;
  49443. }
  49444. /**
  49445. * Add keyboard input support to the input manager.
  49446. * @returns the current input manager
  49447. */
  49448. FreeCameraInputsManager.prototype.addKeyboard = function () {
  49449. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  49450. return this;
  49451. };
  49452. /**
  49453. * Add mouse input support to the input manager.
  49454. * @param touchEnabled if the FreeCameraMouseInput should support touch (default: true)
  49455. * @returns the current input manager
  49456. */
  49457. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  49458. if (touchEnabled === void 0) { touchEnabled = true; }
  49459. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  49460. return this;
  49461. };
  49462. /**
  49463. * Add orientation input support to the input manager.
  49464. * @returns the current input manager
  49465. */
  49466. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  49467. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  49468. return this;
  49469. };
  49470. /**
  49471. * Add touch input support to the input manager.
  49472. * @returns the current input manager
  49473. */
  49474. FreeCameraInputsManager.prototype.addTouch = function () {
  49475. this.add(new BABYLON.FreeCameraTouchInput());
  49476. return this;
  49477. };
  49478. /**
  49479. * Add virtual joystick input support to the input manager.
  49480. * @returns the current input manager
  49481. */
  49482. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  49483. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  49484. return this;
  49485. };
  49486. return FreeCameraInputsManager;
  49487. }(BABYLON.CameraInputsManager));
  49488. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  49489. })(BABYLON || (BABYLON = {}));
  49490. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  49491. var BABYLON;
  49492. (function (BABYLON) {
  49493. BABYLON.Node.AddNodeConstructor("FreeCamera", function (name, scene) {
  49494. // Forcing to use the Universal camera
  49495. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  49496. });
  49497. /**
  49498. * This represents a free type of camera. It can be usefull in First Person Shooter game for instance.
  49499. * Please consider using the new UniversalCamera instead as it adds more functionality like the gamepad.
  49500. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  49501. */
  49502. var FreeCamera = /** @class */ (function (_super) {
  49503. __extends(FreeCamera, _super);
  49504. /**
  49505. * Instantiates a Free Camera.
  49506. * This represents a free type of camera. It can be usefull in First Person Shooter game for instance.
  49507. * Please consider using the new UniversalCamera instead as it adds more functionality like touch to this camera.
  49508. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  49509. * @param name Define the name of the camera in the scene
  49510. * @param position Define the start position of the camera in the scene
  49511. * @param scene Define the scene the camera belongs to
  49512. * @param setActiveOnSceneIfNoneActive Defines wheter the camera should be marked as active if not other active cameras have been defined
  49513. */
  49514. function FreeCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  49515. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  49516. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  49517. /**
  49518. * Define the collision ellipsoid of the camera.
  49519. * This is helpful to simulate a camera body like the player body around the camera
  49520. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#arcrotatecamera
  49521. */
  49522. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  49523. /**
  49524. * Define an offset for the position of the ellipsoid around the camera.
  49525. * This can be helpful to determine the center of the body near the gravity center of the body
  49526. * instead of its head.
  49527. */
  49528. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  49529. /**
  49530. * Enable or disable collisions of the camera with the rest of the scene objects.
  49531. */
  49532. _this.checkCollisions = false;
  49533. /**
  49534. * Enable or disable gravity on the camera.
  49535. */
  49536. _this.applyGravity = false;
  49537. _this._needMoveForGravity = false;
  49538. _this._oldPosition = BABYLON.Vector3.Zero();
  49539. _this._diffPosition = BABYLON.Vector3.Zero();
  49540. _this._newPosition = BABYLON.Vector3.Zero();
  49541. // Collisions
  49542. _this._collisionMask = -1;
  49543. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  49544. if (collidedMesh === void 0) { collidedMesh = null; }
  49545. //TODO move this to the collision coordinator!
  49546. if (_this.getScene().workerCollisions) {
  49547. newPosition.multiplyInPlace(_this._collider._radius);
  49548. }
  49549. var updatePosition = function (newPos) {
  49550. _this._newPosition.copyFrom(newPos);
  49551. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  49552. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  49553. _this.position.addInPlace(_this._diffPosition);
  49554. if (_this.onCollide && collidedMesh) {
  49555. _this.onCollide(collidedMesh);
  49556. }
  49557. }
  49558. };
  49559. updatePosition(newPosition);
  49560. };
  49561. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  49562. _this.inputs.addKeyboard().addMouse();
  49563. return _this;
  49564. }
  49565. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  49566. /**
  49567. * Gets the input sensibility for a mouse input. (default is 2000.0)
  49568. * Higher values reduce sensitivity.
  49569. */
  49570. get: function () {
  49571. var mouse = this.inputs.attached["mouse"];
  49572. if (mouse) {
  49573. return mouse.angularSensibility;
  49574. }
  49575. return 0;
  49576. },
  49577. /**
  49578. * Sets the input sensibility for a mouse input. (default is 2000.0)
  49579. * Higher values reduce sensitivity.
  49580. */
  49581. set: function (value) {
  49582. var mouse = this.inputs.attached["mouse"];
  49583. if (mouse) {
  49584. mouse.angularSensibility = value;
  49585. }
  49586. },
  49587. enumerable: true,
  49588. configurable: true
  49589. });
  49590. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  49591. /**
  49592. * Gets or Set the list of keyboard keys used to control the forward move of the camera.
  49593. */
  49594. get: function () {
  49595. var keyboard = this.inputs.attached["keyboard"];
  49596. if (keyboard) {
  49597. return keyboard.keysUp;
  49598. }
  49599. return [];
  49600. },
  49601. set: function (value) {
  49602. var keyboard = this.inputs.attached["keyboard"];
  49603. if (keyboard) {
  49604. keyboard.keysUp = value;
  49605. }
  49606. },
  49607. enumerable: true,
  49608. configurable: true
  49609. });
  49610. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  49611. /**
  49612. * Gets or Set the list of keyboard keys used to control the backward move of the camera.
  49613. */
  49614. get: function () {
  49615. var keyboard = this.inputs.attached["keyboard"];
  49616. if (keyboard) {
  49617. return keyboard.keysDown;
  49618. }
  49619. return [];
  49620. },
  49621. set: function (value) {
  49622. var keyboard = this.inputs.attached["keyboard"];
  49623. if (keyboard) {
  49624. keyboard.keysDown = value;
  49625. }
  49626. },
  49627. enumerable: true,
  49628. configurable: true
  49629. });
  49630. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  49631. /**
  49632. * Gets or Set the list of keyboard keys used to control the left strafe move of the camera.
  49633. */
  49634. get: function () {
  49635. var keyboard = this.inputs.attached["keyboard"];
  49636. if (keyboard) {
  49637. return keyboard.keysLeft;
  49638. }
  49639. return [];
  49640. },
  49641. set: function (value) {
  49642. var keyboard = this.inputs.attached["keyboard"];
  49643. if (keyboard) {
  49644. keyboard.keysLeft = value;
  49645. }
  49646. },
  49647. enumerable: true,
  49648. configurable: true
  49649. });
  49650. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  49651. /**
  49652. * Gets or Set the list of keyboard keys used to control the right strafe move of the camera.
  49653. */
  49654. get: function () {
  49655. var keyboard = this.inputs.attached["keyboard"];
  49656. if (keyboard) {
  49657. return keyboard.keysRight;
  49658. }
  49659. return [];
  49660. },
  49661. set: function (value) {
  49662. var keyboard = this.inputs.attached["keyboard"];
  49663. if (keyboard) {
  49664. keyboard.keysRight = value;
  49665. }
  49666. },
  49667. enumerable: true,
  49668. configurable: true
  49669. });
  49670. /**
  49671. * Attached controls to the current camera.
  49672. * @param element Defines the element the controls should be listened from
  49673. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  49674. */
  49675. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  49676. this.inputs.attachElement(element, noPreventDefault);
  49677. };
  49678. /**
  49679. * Detach the current controls from the camera.
  49680. * The camera will stop reacting to inputs.
  49681. * @param element Defines the element to stop listening the inputs from
  49682. */
  49683. FreeCamera.prototype.detachControl = function (element) {
  49684. this.inputs.detachElement(element);
  49685. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  49686. this.cameraRotation = new BABYLON.Vector2(0, 0);
  49687. };
  49688. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  49689. /**
  49690. * Define a collision mask to limit the list of object the camera can collide with
  49691. */
  49692. get: function () {
  49693. return this._collisionMask;
  49694. },
  49695. set: function (mask) {
  49696. this._collisionMask = !isNaN(mask) ? mask : -1;
  49697. },
  49698. enumerable: true,
  49699. configurable: true
  49700. });
  49701. /** @hidden */
  49702. FreeCamera.prototype._collideWithWorld = function (displacement) {
  49703. var globalPosition;
  49704. if (this.parent) {
  49705. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  49706. }
  49707. else {
  49708. globalPosition = this.position;
  49709. }
  49710. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  49711. this._oldPosition.addInPlace(this.ellipsoidOffset);
  49712. if (!this._collider) {
  49713. this._collider = new BABYLON.Collider();
  49714. }
  49715. this._collider._radius = this.ellipsoid;
  49716. this._collider.collisionMask = this._collisionMask;
  49717. //no need for clone, as long as gravity is not on.
  49718. var actualDisplacement = displacement;
  49719. //add gravity to the direction to prevent the dual-collision checking
  49720. if (this.applyGravity) {
  49721. //this prevents mending with cameraDirection, a global variable of the free camera class.
  49722. actualDisplacement = displacement.add(this.getScene().gravity);
  49723. }
  49724. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  49725. };
  49726. /** @hidden */
  49727. FreeCamera.prototype._checkInputs = function () {
  49728. if (!this._localDirection) {
  49729. this._localDirection = BABYLON.Vector3.Zero();
  49730. this._transformedDirection = BABYLON.Vector3.Zero();
  49731. }
  49732. this.inputs.checkInputs();
  49733. _super.prototype._checkInputs.call(this);
  49734. };
  49735. /** @hidden */
  49736. FreeCamera.prototype._decideIfNeedsToMove = function () {
  49737. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  49738. };
  49739. /** @hidden */
  49740. FreeCamera.prototype._updatePosition = function () {
  49741. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  49742. this._collideWithWorld(this.cameraDirection);
  49743. }
  49744. else {
  49745. _super.prototype._updatePosition.call(this);
  49746. }
  49747. };
  49748. /**
  49749. * Destroy the camera and release the current resources hold by it.
  49750. */
  49751. FreeCamera.prototype.dispose = function () {
  49752. this.inputs.clear();
  49753. _super.prototype.dispose.call(this);
  49754. };
  49755. /**
  49756. * Gets the current object class name.
  49757. * @return the class name
  49758. */
  49759. FreeCamera.prototype.getClassName = function () {
  49760. return "FreeCamera";
  49761. };
  49762. __decorate([
  49763. BABYLON.serializeAsVector3()
  49764. ], FreeCamera.prototype, "ellipsoid", void 0);
  49765. __decorate([
  49766. BABYLON.serializeAsVector3()
  49767. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  49768. __decorate([
  49769. BABYLON.serialize()
  49770. ], FreeCamera.prototype, "checkCollisions", void 0);
  49771. __decorate([
  49772. BABYLON.serialize()
  49773. ], FreeCamera.prototype, "applyGravity", void 0);
  49774. return FreeCamera;
  49775. }(BABYLON.TargetCamera));
  49776. BABYLON.FreeCamera = FreeCamera;
  49777. })(BABYLON || (BABYLON = {}));
  49778. //# sourceMappingURL=babylon.freeCamera.js.map
  49779. var BABYLON;
  49780. (function (BABYLON) {
  49781. /**
  49782. * Listen to mouse events to control the camera.
  49783. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  49784. */
  49785. var FlyCameraMouseInput = /** @class */ (function () {
  49786. /**
  49787. * Listen to mouse events to control the camera.
  49788. * @param touchEnabled Define if touch is enabled. (Default is true.)
  49789. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  49790. */
  49791. function FlyCameraMouseInput(touchEnabled) {
  49792. if (touchEnabled === void 0) { touchEnabled = true; }
  49793. /**
  49794. * Defines the buttons associated with the input to handle camera rotation.
  49795. */
  49796. this.buttons = [0, 1, 2];
  49797. /**
  49798. * Assign buttons for Yaw control.
  49799. */
  49800. this.buttonsYaw = [-1, 0, 1];
  49801. /**
  49802. * Assign buttons for Pitch control.
  49803. */
  49804. this.buttonsPitch = [-1, 0, 1];
  49805. /**
  49806. * Assign buttons for Roll control.
  49807. */
  49808. this.buttonsRoll = [2];
  49809. /**
  49810. * Detect if any button is being pressed while mouse is moved.
  49811. * -1 = Mouse locked.
  49812. * 0 = Left button.
  49813. * 1 = Middle Button.
  49814. * 2 = Right Button.
  49815. */
  49816. this.activeButton = -1;
  49817. /**
  49818. * Defines the pointer's angular sensibility, to control the camera rotation speed.
  49819. * Higher values reduce its sensitivity.
  49820. */
  49821. this.angularSensibility = 1000.0;
  49822. this.previousPosition = null;
  49823. }
  49824. /**
  49825. * Attach the mouse control to the HTML DOM element.
  49826. * @param element Defines the element that listens to the input events.
  49827. * @param noPreventDefault Defines whether events caught by the controls should call preventdefault().
  49828. */
  49829. FlyCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  49830. var _this = this;
  49831. this.element = element;
  49832. this.noPreventDefault = noPreventDefault;
  49833. this._observer = this.camera.getScene().onPointerObservable.add(function (p, s) {
  49834. _this._pointerInput(p, s);
  49835. }, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  49836. // Correct Roll by rate, if enabled.
  49837. this._rollObserver = this.camera.getScene().onBeforeRenderObservable.add(function () {
  49838. if (_this.camera.rollCorrect) {
  49839. _this.camera.restoreRoll(_this.camera.rollCorrect);
  49840. }
  49841. });
  49842. // Helper function to keep 'this'.
  49843. this._mousemoveCallback = function (e) {
  49844. _this._onMouseMove(e);
  49845. };
  49846. element.addEventListener("mousemove", this._mousemoveCallback, false);
  49847. };
  49848. /**
  49849. * Detach the current controls from the specified dom element.
  49850. * @param element Defines the element to stop listening the inputs from
  49851. */
  49852. FlyCameraMouseInput.prototype.detachControl = function (element) {
  49853. if (this._observer && element) {
  49854. this.camera.getScene().onPointerObservable.remove(this._observer);
  49855. this.camera.getScene().onBeforeRenderObservable.remove(this._rollObserver);
  49856. if (this._mousemoveCallback) {
  49857. element.removeEventListener("mousemove", this._mousemoveCallback);
  49858. }
  49859. this._observer = null;
  49860. this._rollObserver = null;
  49861. this.previousPosition = null;
  49862. this.noPreventDefault = undefined;
  49863. }
  49864. };
  49865. /**
  49866. * Gets the class name of the current input.
  49867. * @returns the class name.
  49868. */
  49869. FlyCameraMouseInput.prototype.getClassName = function () {
  49870. return "FlyCameraMouseInput";
  49871. };
  49872. /**
  49873. * Get the friendly name associated with the input class.
  49874. * @returns the input's friendly name.
  49875. */
  49876. FlyCameraMouseInput.prototype.getSimpleName = function () {
  49877. return "mouse";
  49878. };
  49879. // Track mouse movement, when the pointer is not locked.
  49880. FlyCameraMouseInput.prototype._pointerInput = function (p, s) {
  49881. var e = p.event;
  49882. var camera = this.camera;
  49883. var engine = camera.getEngine();
  49884. if (engine.isInVRExclusivePointerMode) {
  49885. return;
  49886. }
  49887. if (!this.touchEnabled && e.pointerType === "touch") {
  49888. return;
  49889. }
  49890. // Mouse is moved but an unknown mouse button is pressed.
  49891. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && this.buttons.indexOf(e.button) === -1) {
  49892. return;
  49893. }
  49894. var srcElement = (e.srcElement || e.target);
  49895. // Mouse down.
  49896. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  49897. try {
  49898. srcElement.setPointerCapture(e.pointerId);
  49899. }
  49900. catch (e) {
  49901. // Nothing to do with the error. Execution continues.
  49902. }
  49903. this.previousPosition = {
  49904. x: e.clientX,
  49905. y: e.clientY
  49906. };
  49907. this.activeButton = e.button;
  49908. if (!this.noPreventDefault) {
  49909. e.preventDefault();
  49910. this.element.focus();
  49911. }
  49912. }
  49913. else
  49914. // Mouse up.
  49915. if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  49916. try {
  49917. srcElement.releasePointerCapture(e.pointerId);
  49918. }
  49919. catch (e) {
  49920. // Nothing to do with the error. Execution continues.
  49921. }
  49922. this.activeButton = -1;
  49923. this.previousPosition = null;
  49924. if (!this.noPreventDefault) {
  49925. e.preventDefault();
  49926. }
  49927. }
  49928. else
  49929. // Mouse move.
  49930. if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  49931. if (!this.previousPosition || engine.isPointerLock) {
  49932. return;
  49933. }
  49934. var offsetX = e.clientX - this.previousPosition.x;
  49935. var offsetY = e.clientY - this.previousPosition.y;
  49936. this.rotateCamera(offsetX, offsetY);
  49937. this.previousPosition = {
  49938. x: e.clientX,
  49939. y: e.clientY
  49940. };
  49941. if (!this.noPreventDefault) {
  49942. e.preventDefault();
  49943. }
  49944. }
  49945. };
  49946. // Track mouse movement, when pointer is locked.
  49947. FlyCameraMouseInput.prototype._onMouseMove = function (e) {
  49948. var camera = this.camera;
  49949. var engine = camera.getEngine();
  49950. if (!engine.isPointerLock || engine.isInVRExclusivePointerMode) {
  49951. return;
  49952. }
  49953. var offsetX = e.movementX || e.mozMovementX || e.webkitMovementX || e.msMovementX || 0;
  49954. var offsetY = e.movementY || e.mozMovementY || e.webkitMovementY || e.msMovementY || 0;
  49955. this.rotateCamera(offsetX, offsetY);
  49956. this.previousPosition = null;
  49957. if (!this.noPreventDefault) {
  49958. e.preventDefault();
  49959. }
  49960. };
  49961. /**
  49962. * Rotate camera by mouse offset.
  49963. */
  49964. FlyCameraMouseInput.prototype.rotateCamera = function (offsetX, offsetY) {
  49965. var _this = this;
  49966. var camera = this.camera;
  49967. var scene = this.camera.getScene();
  49968. if (scene.useRightHandedSystem) {
  49969. offsetX *= -1;
  49970. }
  49971. if (camera.parent && camera.parent._getWorldMatrixDeterminant() < 0) {
  49972. offsetX *= -1;
  49973. }
  49974. var x = offsetX / this.angularSensibility;
  49975. var y = offsetY / this.angularSensibility;
  49976. // Initialize to current rotation.
  49977. var currentRotation = BABYLON.Quaternion.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, camera.rotation.z);
  49978. var rotationChange;
  49979. // Pitch.
  49980. if (this.buttonsPitch.some(function (v) { return v === _this.activeButton; })) {
  49981. // Apply change in Radians to vector Angle.
  49982. rotationChange = BABYLON.Quaternion.RotationAxis(BABYLON.Axis.X, y);
  49983. // Apply Pitch to quaternion.
  49984. currentRotation.multiplyInPlace(rotationChange);
  49985. }
  49986. // Yaw.
  49987. if (this.buttonsYaw.some(function (v) { return v === _this.activeButton; })) {
  49988. // Apply change in Radians to vector Angle.
  49989. rotationChange = BABYLON.Quaternion.RotationAxis(BABYLON.Axis.Y, x);
  49990. // Apply Yaw to quaternion.
  49991. currentRotation.multiplyInPlace(rotationChange);
  49992. // Add Roll, if banked turning is enabled, within Roll limit.
  49993. var limit = (camera.bankedTurnLimit) + camera._trackRoll; // Defaults to 90° plus manual roll.
  49994. if (camera.bankedTurn && -limit < camera.rotation.z && camera.rotation.z < limit) {
  49995. var bankingDelta = camera.bankedTurnMultiplier * -x;
  49996. // Apply change in Radians to vector Angle.
  49997. rotationChange = BABYLON.Quaternion.RotationAxis(BABYLON.Axis.Z, bankingDelta);
  49998. // Apply Yaw to quaternion.
  49999. currentRotation.multiplyInPlace(rotationChange);
  50000. }
  50001. }
  50002. // Roll.
  50003. if (this.buttonsRoll.some(function (v) { return v === _this.activeButton; })) {
  50004. // Apply change in Radians to vector Angle.
  50005. rotationChange = BABYLON.Quaternion.RotationAxis(BABYLON.Axis.Z, -x);
  50006. // Track Rolling.
  50007. camera._trackRoll -= x;
  50008. // Apply Pitch to quaternion.
  50009. currentRotation.multiplyInPlace(rotationChange);
  50010. }
  50011. // Apply rotationQuaternion to Euler camera.rotation.
  50012. currentRotation.toEulerAnglesToRef(camera.rotation);
  50013. };
  50014. __decorate([
  50015. BABYLON.serialize()
  50016. ], FlyCameraMouseInput.prototype, "buttons", void 0);
  50017. __decorate([
  50018. BABYLON.serialize()
  50019. ], FlyCameraMouseInput.prototype, "angularSensibility", void 0);
  50020. return FlyCameraMouseInput;
  50021. }());
  50022. BABYLON.FlyCameraMouseInput = FlyCameraMouseInput;
  50023. BABYLON.CameraInputTypes["FlyCameraMouseInput"] = FlyCameraMouseInput;
  50024. })(BABYLON || (BABYLON = {}));
  50025. //# sourceMappingURL=babylon.flyCameraMouseInput.js.map
  50026. var BABYLON;
  50027. (function (BABYLON) {
  50028. /**
  50029. * Listen to keyboard events to control the camera.
  50030. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  50031. */
  50032. var FlyCameraKeyboardInput = /** @class */ (function () {
  50033. function FlyCameraKeyboardInput() {
  50034. /**
  50035. * The list of keyboard keys used to control the forward move of the camera.
  50036. */
  50037. this.keysForward = [87];
  50038. /**
  50039. * The list of keyboard keys used to control the backward move of the camera.
  50040. */
  50041. this.keysBackward = [83];
  50042. /**
  50043. * The list of keyboard keys used to control the forward move of the camera.
  50044. */
  50045. this.keysUp = [69];
  50046. /**
  50047. * The list of keyboard keys used to control the backward move of the camera.
  50048. */
  50049. this.keysDown = [81];
  50050. /**
  50051. * The list of keyboard keys used to control the right strafe move of the camera.
  50052. */
  50053. this.keysRight = [68];
  50054. /**
  50055. * The list of keyboard keys used to control the left strafe move of the camera.
  50056. */
  50057. this.keysLeft = [65];
  50058. this._keys = new Array();
  50059. }
  50060. /**
  50061. * Attach the input controls to a specific dom element to get the input from.
  50062. * @param element Defines the element the controls should be listened from
  50063. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  50064. */
  50065. FlyCameraKeyboardInput.prototype.attachControl = function (element, noPreventDefault) {
  50066. var _this = this;
  50067. if (this._onCanvasBlurObserver) {
  50068. return;
  50069. }
  50070. this._scene = this.camera.getScene();
  50071. this._engine = this._scene.getEngine();
  50072. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  50073. _this._keys = [];
  50074. });
  50075. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  50076. var evt = info.event;
  50077. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  50078. if (_this.keysForward.indexOf(evt.keyCode) !== -1 ||
  50079. _this.keysBackward.indexOf(evt.keyCode) !== -1 ||
  50080. _this.keysUp.indexOf(evt.keyCode) !== -1 ||
  50081. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  50082. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  50083. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  50084. var index = _this._keys.indexOf(evt.keyCode);
  50085. if (index === -1) {
  50086. _this._keys.push(evt.keyCode);
  50087. }
  50088. if (!noPreventDefault) {
  50089. evt.preventDefault();
  50090. }
  50091. }
  50092. }
  50093. else {
  50094. if (_this.keysForward.indexOf(evt.keyCode) !== -1 ||
  50095. _this.keysBackward.indexOf(evt.keyCode) !== -1 ||
  50096. _this.keysUp.indexOf(evt.keyCode) !== -1 ||
  50097. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  50098. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  50099. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  50100. var index = _this._keys.indexOf(evt.keyCode);
  50101. if (index >= 0) {
  50102. _this._keys.splice(index, 1);
  50103. }
  50104. if (!noPreventDefault) {
  50105. evt.preventDefault();
  50106. }
  50107. }
  50108. }
  50109. });
  50110. };
  50111. /**
  50112. * Detach the current controls from the specified dom element.
  50113. * @param element Defines the element to stop listening the inputs from
  50114. */
  50115. FlyCameraKeyboardInput.prototype.detachControl = function (element) {
  50116. if (this._scene) {
  50117. if (this._onKeyboardObserver) {
  50118. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  50119. }
  50120. if (this._onCanvasBlurObserver) {
  50121. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  50122. }
  50123. this._onKeyboardObserver = null;
  50124. this._onCanvasBlurObserver = null;
  50125. }
  50126. this._keys = [];
  50127. };
  50128. /**
  50129. * Gets the class name of the current intput.
  50130. * @returns the class name
  50131. */
  50132. FlyCameraKeyboardInput.prototype.getClassName = function () {
  50133. return "FlyCameraKeyboardInput";
  50134. };
  50135. /** @hidden */
  50136. FlyCameraKeyboardInput.prototype._onLostFocus = function (e) {
  50137. this._keys = [];
  50138. };
  50139. /**
  50140. * Get the friendly name associated with the input class.
  50141. * @returns the input friendly name
  50142. */
  50143. FlyCameraKeyboardInput.prototype.getSimpleName = function () {
  50144. return "keyboard";
  50145. };
  50146. /**
  50147. * Update the current camera state depending on the inputs that have been used this frame.
  50148. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  50149. */
  50150. FlyCameraKeyboardInput.prototype.checkInputs = function () {
  50151. if (this._onKeyboardObserver) {
  50152. var camera = this.camera;
  50153. // Keyboard
  50154. for (var index = 0; index < this._keys.length; index++) {
  50155. var keyCode = this._keys[index];
  50156. var speed = camera._computeLocalCameraSpeed();
  50157. if (this.keysForward.indexOf(keyCode) !== -1) {
  50158. camera._localDirection.copyFromFloats(0, 0, speed);
  50159. }
  50160. else if (this.keysBackward.indexOf(keyCode) !== -1) {
  50161. camera._localDirection.copyFromFloats(0, 0, -speed);
  50162. }
  50163. else if (this.keysUp.indexOf(keyCode) !== -1) {
  50164. camera._localDirection.copyFromFloats(0, speed, 0);
  50165. }
  50166. else if (this.keysDown.indexOf(keyCode) !== -1) {
  50167. camera._localDirection.copyFromFloats(0, -speed, 0);
  50168. }
  50169. else if (this.keysRight.indexOf(keyCode) !== -1) {
  50170. camera._localDirection.copyFromFloats(speed, 0, 0);
  50171. }
  50172. else if (this.keysLeft.indexOf(keyCode) !== -1) {
  50173. camera._localDirection.copyFromFloats(-speed, 0, 0);
  50174. }
  50175. if (camera.getScene().useRightHandedSystem) {
  50176. camera._localDirection.z *= -1;
  50177. }
  50178. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  50179. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  50180. camera.cameraDirection.addInPlace(camera._transformedDirection);
  50181. }
  50182. }
  50183. };
  50184. __decorate([
  50185. BABYLON.serialize()
  50186. ], FlyCameraKeyboardInput.prototype, "keysForward", void 0);
  50187. __decorate([
  50188. BABYLON.serialize()
  50189. ], FlyCameraKeyboardInput.prototype, "keysBackward", void 0);
  50190. __decorate([
  50191. BABYLON.serialize()
  50192. ], FlyCameraKeyboardInput.prototype, "keysUp", void 0);
  50193. __decorate([
  50194. BABYLON.serialize()
  50195. ], FlyCameraKeyboardInput.prototype, "keysDown", void 0);
  50196. __decorate([
  50197. BABYLON.serialize()
  50198. ], FlyCameraKeyboardInput.prototype, "keysRight", void 0);
  50199. __decorate([
  50200. BABYLON.serialize()
  50201. ], FlyCameraKeyboardInput.prototype, "keysLeft", void 0);
  50202. return FlyCameraKeyboardInput;
  50203. }());
  50204. BABYLON.FlyCameraKeyboardInput = FlyCameraKeyboardInput;
  50205. BABYLON.CameraInputTypes["FlyCameraKeyboardInput"] = FlyCameraKeyboardInput;
  50206. })(BABYLON || (BABYLON = {}));
  50207. //# sourceMappingURL=babylon.flyCameraKeyboardInput.js.map
  50208. var BABYLON;
  50209. (function (BABYLON) {
  50210. /**
  50211. * Default Inputs manager for the FlyCamera.
  50212. * It groups all the default supported inputs for ease of use.
  50213. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  50214. */
  50215. var FlyCameraInputsManager = /** @class */ (function (_super) {
  50216. __extends(FlyCameraInputsManager, _super);
  50217. /**
  50218. * Instantiates a new FlyCameraInputsManager.
  50219. * @param camera Defines the camera the inputs belong to.
  50220. */
  50221. function FlyCameraInputsManager(camera) {
  50222. return _super.call(this, camera) || this;
  50223. }
  50224. /**
  50225. * Add keyboard input support to the input manager.
  50226. * @returns the new FlyCameraKeyboardMoveInput().
  50227. */
  50228. FlyCameraInputsManager.prototype.addKeyboard = function () {
  50229. this.add(new BABYLON.FlyCameraKeyboardInput());
  50230. return this;
  50231. };
  50232. /**
  50233. * Add mouse input support to the input manager.
  50234. * @param touchEnabled Enable touch screen support.
  50235. * @returns the new FlyCameraMouseInput().
  50236. */
  50237. FlyCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  50238. if (touchEnabled === void 0) { touchEnabled = true; }
  50239. this.add(new BABYLON.FlyCameraMouseInput(touchEnabled));
  50240. return this;
  50241. };
  50242. return FlyCameraInputsManager;
  50243. }(BABYLON.CameraInputsManager));
  50244. BABYLON.FlyCameraInputsManager = FlyCameraInputsManager;
  50245. })(BABYLON || (BABYLON = {}));
  50246. //# sourceMappingURL=babylon.flyCameraInputsManager.js.map
  50247. var BABYLON;
  50248. (function (BABYLON) {
  50249. /**
  50250. * This is a flying camera, designed for 3D movement and rotation in all directions,
  50251. * such as in a 3D Space Shooter or a Flight Simulator.
  50252. */
  50253. var FlyCamera = /** @class */ (function (_super) {
  50254. __extends(FlyCamera, _super);
  50255. /**
  50256. * Instantiates a FlyCamera.
  50257. * This is a flying camera, designed for 3D movement and rotation in all directions,
  50258. * such as in a 3D Space Shooter or a Flight Simulator.
  50259. * @param name Define the name of the camera in the scene.
  50260. * @param position Define the starting position of the camera in the scene.
  50261. * @param scene Define the scene the camera belongs to.
  50262. * @param setActiveOnSceneIfNoneActive Defines wheter the camera should be marked as active, if no other camera has been defined as active.
  50263. */
  50264. function FlyCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  50265. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  50266. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  50267. /**
  50268. * Define the collision ellipsoid of the camera.
  50269. * This is helpful for simulating a camera body, like a player's body.
  50270. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#arcrotatecamera
  50271. */
  50272. _this.ellipsoid = new BABYLON.Vector3(1, 1, 1);
  50273. /**
  50274. * Define an offset for the position of the ellipsoid around the camera.
  50275. * This can be helpful if the camera is attached away from the player's body center,
  50276. * such as at its head.
  50277. */
  50278. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  50279. /**
  50280. * Enable or disable collisions of the camera with the rest of the scene objects.
  50281. */
  50282. _this.checkCollisions = false;
  50283. /**
  50284. * Enable or disable gravity on the camera.
  50285. */
  50286. _this.applyGravity = false;
  50287. /**
  50288. * Define the current direction the camera is moving to.
  50289. */
  50290. _this.cameraDirection = BABYLON.Vector3.Zero();
  50291. /**
  50292. * Track Roll to maintain the wanted Rolling when looking around.
  50293. */
  50294. _this._trackRoll = 0;
  50295. /**
  50296. * Slowly correct the Roll to its original value after a Pitch+Yaw rotation.
  50297. */
  50298. _this.rollCorrect = 100;
  50299. /**
  50300. * Mimic a banked turn, Rolling the camera when Yawing.
  50301. * It's recommended to use rollCorrect = 10 for faster banking correction.
  50302. */
  50303. _this.bankedTurn = false;
  50304. /**
  50305. * Limit in radians for how much Roll banking will add. (Default: 90°)
  50306. */
  50307. _this.bankedTurnLimit = Math.PI / 2;
  50308. /**
  50309. * Value of 0 disables the banked Roll.
  50310. * Value of 1 is equal to the Yaw angle in radians.
  50311. */
  50312. _this.bankedTurnMultiplier = 1;
  50313. _this._needMoveForGravity = false;
  50314. _this._oldPosition = BABYLON.Vector3.Zero();
  50315. _this._diffPosition = BABYLON.Vector3.Zero();
  50316. _this._newPosition = BABYLON.Vector3.Zero();
  50317. // Collisions.
  50318. _this._collisionMask = -1;
  50319. /** @hidden */
  50320. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  50321. if (collidedMesh === void 0) { collidedMesh = null; }
  50322. // TODO Move this to the collision coordinator!
  50323. if (_this.getScene().workerCollisions) {
  50324. newPosition.multiplyInPlace(_this._collider._radius);
  50325. }
  50326. var updatePosition = function (newPos) {
  50327. _this._newPosition.copyFrom(newPos);
  50328. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  50329. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  50330. _this.position.addInPlace(_this._diffPosition);
  50331. if (_this.onCollide && collidedMesh) {
  50332. _this.onCollide(collidedMesh);
  50333. }
  50334. }
  50335. };
  50336. updatePosition(newPosition);
  50337. };
  50338. _this.inputs = new BABYLON.FlyCameraInputsManager(_this);
  50339. _this.inputs.addKeyboard().addMouse();
  50340. return _this;
  50341. }
  50342. Object.defineProperty(FlyCamera.prototype, "angularSensibility", {
  50343. /**
  50344. * Gets the input sensibility for mouse input.
  50345. * Higher values reduce sensitivity.
  50346. */
  50347. get: function () {
  50348. var mouse = this.inputs.attached["mouse"];
  50349. if (mouse) {
  50350. return mouse.angularSensibility;
  50351. }
  50352. return 0;
  50353. },
  50354. /**
  50355. * Sets the input sensibility for a mouse input.
  50356. * Higher values reduce sensitivity.
  50357. */
  50358. set: function (value) {
  50359. var mouse = this.inputs.attached["mouse"];
  50360. if (mouse) {
  50361. mouse.angularSensibility = value;
  50362. }
  50363. },
  50364. enumerable: true,
  50365. configurable: true
  50366. });
  50367. Object.defineProperty(FlyCamera.prototype, "keysForward", {
  50368. /**
  50369. * Get the keys for camera movement forward.
  50370. */
  50371. get: function () {
  50372. var keyboard = this.inputs.attached["keyboard"];
  50373. if (keyboard) {
  50374. return keyboard.keysForward;
  50375. }
  50376. return [];
  50377. },
  50378. /**
  50379. * Set the keys for camera movement forward.
  50380. */
  50381. set: function (value) {
  50382. var keyboard = this.inputs.attached["keyboard"];
  50383. if (keyboard) {
  50384. keyboard.keysForward = value;
  50385. }
  50386. },
  50387. enumerable: true,
  50388. configurable: true
  50389. });
  50390. Object.defineProperty(FlyCamera.prototype, "keysBackward", {
  50391. /**
  50392. * Get the keys for camera movement backward.
  50393. */
  50394. get: function () {
  50395. var keyboard = this.inputs.attached["keyboard"];
  50396. if (keyboard) {
  50397. return keyboard.keysBackward;
  50398. }
  50399. return [];
  50400. },
  50401. set: function (value) {
  50402. var keyboard = this.inputs.attached["keyboard"];
  50403. if (keyboard) {
  50404. keyboard.keysBackward = value;
  50405. }
  50406. },
  50407. enumerable: true,
  50408. configurable: true
  50409. });
  50410. Object.defineProperty(FlyCamera.prototype, "keysUp", {
  50411. /**
  50412. * Get the keys for camera movement up.
  50413. */
  50414. get: function () {
  50415. var keyboard = this.inputs.attached["keyboard"];
  50416. if (keyboard) {
  50417. return keyboard.keysUp;
  50418. }
  50419. return [];
  50420. },
  50421. /**
  50422. * Set the keys for camera movement up.
  50423. */
  50424. set: function (value) {
  50425. var keyboard = this.inputs.attached["keyboard"];
  50426. if (keyboard) {
  50427. keyboard.keysUp = value;
  50428. }
  50429. },
  50430. enumerable: true,
  50431. configurable: true
  50432. });
  50433. Object.defineProperty(FlyCamera.prototype, "keysDown", {
  50434. /**
  50435. * Get the keys for camera movement down.
  50436. */
  50437. get: function () {
  50438. var keyboard = this.inputs.attached["keyboard"];
  50439. if (keyboard) {
  50440. return keyboard.keysDown;
  50441. }
  50442. return [];
  50443. },
  50444. /**
  50445. * Set the keys for camera movement down.
  50446. */
  50447. set: function (value) {
  50448. var keyboard = this.inputs.attached["keyboard"];
  50449. if (keyboard) {
  50450. keyboard.keysDown = value;
  50451. }
  50452. },
  50453. enumerable: true,
  50454. configurable: true
  50455. });
  50456. Object.defineProperty(FlyCamera.prototype, "keysLeft", {
  50457. /**
  50458. * Get the keys for camera movement left.
  50459. */
  50460. get: function () {
  50461. var keyboard = this.inputs.attached["keyboard"];
  50462. if (keyboard) {
  50463. return keyboard.keysLeft;
  50464. }
  50465. return [];
  50466. },
  50467. /**
  50468. * Set the keys for camera movement left.
  50469. */
  50470. set: function (value) {
  50471. var keyboard = this.inputs.attached["keyboard"];
  50472. if (keyboard) {
  50473. keyboard.keysLeft = value;
  50474. }
  50475. },
  50476. enumerable: true,
  50477. configurable: true
  50478. });
  50479. Object.defineProperty(FlyCamera.prototype, "keysRight", {
  50480. /**
  50481. * Set the keys for camera movement right.
  50482. */
  50483. get: function () {
  50484. var keyboard = this.inputs.attached["keyboard"];
  50485. if (keyboard) {
  50486. return keyboard.keysRight;
  50487. }
  50488. return [];
  50489. },
  50490. /**
  50491. * Set the keys for camera movement right.
  50492. */
  50493. set: function (value) {
  50494. var keyboard = this.inputs.attached["keyboard"];
  50495. if (keyboard) {
  50496. keyboard.keysRight = value;
  50497. }
  50498. },
  50499. enumerable: true,
  50500. configurable: true
  50501. });
  50502. /**
  50503. * Attach a control to the HTML DOM element.
  50504. * @param element Defines the element that listens to the input events.
  50505. * @param noPreventDefault Defines whether events caught by the controls should call preventdefault(). https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault
  50506. */
  50507. FlyCamera.prototype.attachControl = function (element, noPreventDefault) {
  50508. this.inputs.attachElement(element, noPreventDefault);
  50509. };
  50510. /**
  50511. * Detach a control from the HTML DOM element.
  50512. * The camera will stop reacting to that input.
  50513. * @param element Defines the element that listens to the input events.
  50514. */
  50515. FlyCamera.prototype.detachControl = function (element) {
  50516. this.inputs.detachElement(element);
  50517. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  50518. };
  50519. Object.defineProperty(FlyCamera.prototype, "collisionMask", {
  50520. /**
  50521. * Get the mask that the camera ignores in collision events.
  50522. */
  50523. get: function () {
  50524. return this._collisionMask;
  50525. },
  50526. /**
  50527. * Set the mask that the camera ignores in collision events.
  50528. */
  50529. set: function (mask) {
  50530. this._collisionMask = !isNaN(mask) ? mask : -1;
  50531. },
  50532. enumerable: true,
  50533. configurable: true
  50534. });
  50535. /** @hidden */
  50536. FlyCamera.prototype._collideWithWorld = function (displacement) {
  50537. var globalPosition;
  50538. if (this.parent) {
  50539. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  50540. }
  50541. else {
  50542. globalPosition = this.position;
  50543. }
  50544. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  50545. this._oldPosition.addInPlace(this.ellipsoidOffset);
  50546. if (!this._collider) {
  50547. this._collider = new BABYLON.Collider();
  50548. }
  50549. this._collider._radius = this.ellipsoid;
  50550. this._collider.collisionMask = this._collisionMask;
  50551. // No need for clone, as long as gravity is not on.
  50552. var actualDisplacement = displacement;
  50553. // Add gravity to direction to prevent dual-collision checking.
  50554. if (this.applyGravity) {
  50555. // This prevents mending with cameraDirection, a global variable of the fly camera class.
  50556. actualDisplacement = displacement.add(this.getScene().gravity);
  50557. }
  50558. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  50559. };
  50560. /** @hidden */
  50561. FlyCamera.prototype._checkInputs = function () {
  50562. if (!this._localDirection) {
  50563. this._localDirection = BABYLON.Vector3.Zero();
  50564. this._transformedDirection = BABYLON.Vector3.Zero();
  50565. }
  50566. this.inputs.checkInputs();
  50567. _super.prototype._checkInputs.call(this);
  50568. };
  50569. /** @hidden */
  50570. FlyCamera.prototype._decideIfNeedsToMove = function () {
  50571. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  50572. };
  50573. /** @hidden */
  50574. FlyCamera.prototype._updatePosition = function () {
  50575. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  50576. this._collideWithWorld(this.cameraDirection);
  50577. }
  50578. else {
  50579. _super.prototype._updatePosition.call(this);
  50580. }
  50581. };
  50582. /**
  50583. * Restore the Roll to its target value at the rate specified.
  50584. * @param rate - Higher means slower restoring.
  50585. * @hidden
  50586. */
  50587. FlyCamera.prototype.restoreRoll = function (rate) {
  50588. var limit = this._trackRoll; // Target Roll.
  50589. var z = this.rotation.z; // Current Roll.
  50590. var delta = limit - z; // Difference in Roll.
  50591. var minRad = 0.001; // Tenth of a radian is a barely noticable difference.
  50592. // If the difference is noticable, restore the Roll.
  50593. if (Math.abs(delta) >= minRad) {
  50594. // Change Z rotation towards the target Roll.
  50595. this.rotation.z += delta / rate;
  50596. // Match when near enough.
  50597. if (Math.abs(limit - this.rotation.z) <= minRad) {
  50598. this.rotation.z = limit;
  50599. }
  50600. }
  50601. };
  50602. /**
  50603. * Destroy the camera and release the current resources held by it.
  50604. */
  50605. FlyCamera.prototype.dispose = function () {
  50606. this.inputs.clear();
  50607. _super.prototype.dispose.call(this);
  50608. };
  50609. /**
  50610. * Get the current object class name.
  50611. * @returns the class name.
  50612. */
  50613. FlyCamera.prototype.getClassName = function () {
  50614. return "FlyCamera";
  50615. };
  50616. __decorate([
  50617. BABYLON.serializeAsVector3()
  50618. ], FlyCamera.prototype, "ellipsoid", void 0);
  50619. __decorate([
  50620. BABYLON.serializeAsVector3()
  50621. ], FlyCamera.prototype, "ellipsoidOffset", void 0);
  50622. __decorate([
  50623. BABYLON.serialize()
  50624. ], FlyCamera.prototype, "checkCollisions", void 0);
  50625. __decorate([
  50626. BABYLON.serialize()
  50627. ], FlyCamera.prototype, "applyGravity", void 0);
  50628. return FlyCamera;
  50629. }(BABYLON.TargetCamera));
  50630. BABYLON.FlyCamera = FlyCamera;
  50631. })(BABYLON || (BABYLON = {}));
  50632. //# sourceMappingURL=babylon.flyCamera.js.map
  50633. var BABYLON;
  50634. (function (BABYLON) {
  50635. /**
  50636. * Manage the keyboard inputs to control the movement of an arc rotate camera.
  50637. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  50638. */
  50639. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  50640. function ArcRotateCameraKeyboardMoveInput() {
  50641. /**
  50642. * Defines the list of key codes associated with the up action (increase alpha)
  50643. */
  50644. this.keysUp = [38];
  50645. /**
  50646. * Defines the list of key codes associated with the down action (decrease alpha)
  50647. */
  50648. this.keysDown = [40];
  50649. /**
  50650. * Defines the list of key codes associated with the left action (increase beta)
  50651. */
  50652. this.keysLeft = [37];
  50653. /**
  50654. * Defines the list of key codes associated with the right action (decrease beta)
  50655. */
  50656. this.keysRight = [39];
  50657. /**
  50658. * Defines the list of key codes associated with the reset action.
  50659. * Those keys reset the camera to its last stored state (with the method camera.storeState())
  50660. */
  50661. this.keysReset = [220];
  50662. /**
  50663. * Defines the panning sensibility of the inputs.
  50664. * (How fast is the camera paning)
  50665. */
  50666. this.panningSensibility = 50.0;
  50667. /**
  50668. * Defines the zooming sensibility of the inputs.
  50669. * (How fast is the camera zooming)
  50670. */
  50671. this.zoomingSensibility = 25.0;
  50672. /**
  50673. * Defines wether maintaining the alt key down switch the movement mode from
  50674. * orientation to zoom.
  50675. */
  50676. this.useAltToZoom = true;
  50677. /**
  50678. * Rotation speed of the camera
  50679. */
  50680. this.angularSpeed = 0.01;
  50681. this._keys = new Array();
  50682. }
  50683. /**
  50684. * Attach the input controls to a specific dom element to get the input from.
  50685. * @param element Defines the element the controls should be listened from
  50686. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  50687. */
  50688. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  50689. var _this = this;
  50690. if (this._onCanvasBlurObserver) {
  50691. return;
  50692. }
  50693. this._scene = this.camera.getScene();
  50694. this._engine = this._scene.getEngine();
  50695. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  50696. _this._keys = [];
  50697. });
  50698. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  50699. var evt = info.event;
  50700. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  50701. _this._ctrlPressed = evt.ctrlKey;
  50702. _this._altPressed = evt.altKey;
  50703. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  50704. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  50705. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  50706. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  50707. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  50708. var index = _this._keys.indexOf(evt.keyCode);
  50709. if (index === -1) {
  50710. _this._keys.push(evt.keyCode);
  50711. }
  50712. if (evt.preventDefault) {
  50713. if (!noPreventDefault) {
  50714. evt.preventDefault();
  50715. }
  50716. }
  50717. }
  50718. }
  50719. else {
  50720. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  50721. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  50722. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  50723. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  50724. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  50725. var index = _this._keys.indexOf(evt.keyCode);
  50726. if (index >= 0) {
  50727. _this._keys.splice(index, 1);
  50728. }
  50729. if (evt.preventDefault) {
  50730. if (!noPreventDefault) {
  50731. evt.preventDefault();
  50732. }
  50733. }
  50734. }
  50735. }
  50736. });
  50737. };
  50738. /**
  50739. * Detach the current controls from the specified dom element.
  50740. * @param element Defines the element to stop listening the inputs from
  50741. */
  50742. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  50743. if (this._scene) {
  50744. if (this._onKeyboardObserver) {
  50745. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  50746. }
  50747. if (this._onCanvasBlurObserver) {
  50748. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  50749. }
  50750. this._onKeyboardObserver = null;
  50751. this._onCanvasBlurObserver = null;
  50752. }
  50753. this._keys = [];
  50754. };
  50755. /**
  50756. * Update the current camera state depending on the inputs that have been used this frame.
  50757. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  50758. */
  50759. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  50760. if (this._onKeyboardObserver) {
  50761. var camera = this.camera;
  50762. for (var index = 0; index < this._keys.length; index++) {
  50763. var keyCode = this._keys[index];
  50764. if (this.keysLeft.indexOf(keyCode) !== -1) {
  50765. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  50766. camera.inertialPanningX -= 1 / this.panningSensibility;
  50767. }
  50768. else {
  50769. camera.inertialAlphaOffset -= this.angularSpeed;
  50770. }
  50771. }
  50772. else if (this.keysUp.indexOf(keyCode) !== -1) {
  50773. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  50774. camera.inertialPanningY += 1 / this.panningSensibility;
  50775. }
  50776. else if (this._altPressed && this.useAltToZoom) {
  50777. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  50778. }
  50779. else {
  50780. camera.inertialBetaOffset -= this.angularSpeed;
  50781. }
  50782. }
  50783. else if (this.keysRight.indexOf(keyCode) !== -1) {
  50784. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  50785. camera.inertialPanningX += 1 / this.panningSensibility;
  50786. }
  50787. else {
  50788. camera.inertialAlphaOffset += this.angularSpeed;
  50789. }
  50790. }
  50791. else if (this.keysDown.indexOf(keyCode) !== -1) {
  50792. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  50793. camera.inertialPanningY -= 1 / this.panningSensibility;
  50794. }
  50795. else if (this._altPressed && this.useAltToZoom) {
  50796. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  50797. }
  50798. else {
  50799. camera.inertialBetaOffset += this.angularSpeed;
  50800. }
  50801. }
  50802. else if (this.keysReset.indexOf(keyCode) !== -1) {
  50803. if (camera.useInputToRestoreState) {
  50804. camera.restoreState();
  50805. }
  50806. }
  50807. }
  50808. }
  50809. };
  50810. /**
  50811. * Gets the class name of the current intput.
  50812. * @returns the class name
  50813. */
  50814. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  50815. return "ArcRotateCameraKeyboardMoveInput";
  50816. };
  50817. /**
  50818. * Get the friendly name associated with the input class.
  50819. * @returns the input friendly name
  50820. */
  50821. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  50822. return "keyboard";
  50823. };
  50824. __decorate([
  50825. BABYLON.serialize()
  50826. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  50827. __decorate([
  50828. BABYLON.serialize()
  50829. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  50830. __decorate([
  50831. BABYLON.serialize()
  50832. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  50833. __decorate([
  50834. BABYLON.serialize()
  50835. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  50836. __decorate([
  50837. BABYLON.serialize()
  50838. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  50839. __decorate([
  50840. BABYLON.serialize()
  50841. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  50842. __decorate([
  50843. BABYLON.serialize()
  50844. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  50845. __decorate([
  50846. BABYLON.serialize()
  50847. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  50848. __decorate([
  50849. BABYLON.serialize()
  50850. ], ArcRotateCameraKeyboardMoveInput.prototype, "angularSpeed", void 0);
  50851. return ArcRotateCameraKeyboardMoveInput;
  50852. }());
  50853. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  50854. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  50855. })(BABYLON || (BABYLON = {}));
  50856. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  50857. var BABYLON;
  50858. (function (BABYLON) {
  50859. /**
  50860. * Manage the mouse wheel inputs to control an arc rotate camera.
  50861. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  50862. */
  50863. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  50864. function ArcRotateCameraMouseWheelInput() {
  50865. /**
  50866. * Gets or Set the mouse wheel precision or how fast is the camera zooming.
  50867. */
  50868. this.wheelPrecision = 3.0;
  50869. /**
  50870. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  50871. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  50872. */
  50873. this.wheelDeltaPercentage = 0;
  50874. }
  50875. /**
  50876. * Attach the input controls to a specific dom element to get the input from.
  50877. * @param element Defines the element the controls should be listened from
  50878. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  50879. */
  50880. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  50881. var _this = this;
  50882. this._wheel = function (p, s) {
  50883. //sanity check - this should be a PointerWheel event.
  50884. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL) {
  50885. return;
  50886. }
  50887. var event = p.event;
  50888. var delta = 0;
  50889. if (event.wheelDelta) {
  50890. if (_this.wheelDeltaPercentage) {
  50891. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  50892. if (event.wheelDelta > 0) {
  50893. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  50894. }
  50895. else {
  50896. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  50897. }
  50898. }
  50899. else {
  50900. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  50901. }
  50902. }
  50903. else {
  50904. var deltaValue = event.deltaY || event.detail;
  50905. delta = -deltaValue / _this.wheelPrecision;
  50906. }
  50907. if (delta) {
  50908. _this.camera.inertialRadiusOffset += delta;
  50909. }
  50910. if (event.preventDefault) {
  50911. if (!noPreventDefault) {
  50912. event.preventDefault();
  50913. }
  50914. }
  50915. };
  50916. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  50917. };
  50918. /**
  50919. * Detach the current controls from the specified dom element.
  50920. * @param element Defines the element to stop listening the inputs from
  50921. */
  50922. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  50923. if (this._observer && element) {
  50924. this.camera.getScene().onPointerObservable.remove(this._observer);
  50925. this._observer = null;
  50926. this._wheel = null;
  50927. }
  50928. };
  50929. /**
  50930. * Gets the class name of the current intput.
  50931. * @returns the class name
  50932. */
  50933. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  50934. return "ArcRotateCameraMouseWheelInput";
  50935. };
  50936. /**
  50937. * Get the friendly name associated with the input class.
  50938. * @returns the input friendly name
  50939. */
  50940. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  50941. return "mousewheel";
  50942. };
  50943. __decorate([
  50944. BABYLON.serialize()
  50945. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  50946. __decorate([
  50947. BABYLON.serialize()
  50948. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  50949. return ArcRotateCameraMouseWheelInput;
  50950. }());
  50951. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  50952. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  50953. })(BABYLON || (BABYLON = {}));
  50954. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  50955. var BABYLON;
  50956. (function (BABYLON) {
  50957. /**
  50958. * Manage the pointers inputs to control an arc rotate camera.
  50959. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  50960. */
  50961. var ArcRotateCameraPointersInput = /** @class */ (function () {
  50962. function ArcRotateCameraPointersInput() {
  50963. /**
  50964. * Defines the buttons associated with the input to handle camera move.
  50965. */
  50966. this.buttons = [0, 1, 2];
  50967. /**
  50968. * Defines the pointer angular sensibility along the X axis or how fast is the camera rotating.
  50969. */
  50970. this.angularSensibilityX = 1000.0;
  50971. /**
  50972. * Defines the pointer angular sensibility along the Y axis or how fast is the camera rotating.
  50973. */
  50974. this.angularSensibilityY = 1000.0;
  50975. /**
  50976. * Defines the pointer pinch precision or how fast is the camera zooming.
  50977. */
  50978. this.pinchPrecision = 12.0;
  50979. /**
  50980. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  50981. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  50982. */
  50983. this.pinchDeltaPercentage = 0;
  50984. /**
  50985. * Defines the pointer panning sensibility or how fast is the camera moving.
  50986. */
  50987. this.panningSensibility = 1000.0;
  50988. /**
  50989. * Defines whether panning (2 fingers swipe) is enabled through multitouch.
  50990. */
  50991. this.multiTouchPanning = true;
  50992. /**
  50993. * Defines whether panning is enabled for both pan (2 fingers swipe) and zoom (pinch) through multitouch.
  50994. */
  50995. this.multiTouchPanAndZoom = true;
  50996. /**
  50997. * Revers pinch action direction.
  50998. */
  50999. this.pinchInwards = true;
  51000. this._isPanClick = false;
  51001. }
  51002. /**
  51003. * Attach the input controls to a specific dom element to get the input from.
  51004. * @param element Defines the element the controls should be listened from
  51005. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  51006. */
  51007. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  51008. var _this = this;
  51009. var engine = this.camera.getEngine();
  51010. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  51011. var pointA = null;
  51012. var pointB = null;
  51013. var previousPinchSquaredDistance = 0;
  51014. var initialDistance = 0;
  51015. var twoFingerActivityCount = 0;
  51016. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  51017. this._pointerInput = function (p, s) {
  51018. var evt = p.event;
  51019. var isTouch = p.event.pointerType === "touch";
  51020. if (engine.isInVRExclusivePointerMode) {
  51021. return;
  51022. }
  51023. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  51024. return;
  51025. }
  51026. var srcElement = (evt.srcElement || evt.target);
  51027. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  51028. try {
  51029. srcElement.setPointerCapture(evt.pointerId);
  51030. }
  51031. catch (e) {
  51032. //Nothing to do with the error. Execution will continue.
  51033. }
  51034. // Manage panning with pan button click
  51035. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  51036. // manage pointers
  51037. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  51038. if (pointA === null) {
  51039. pointA = cacheSoloPointer;
  51040. }
  51041. else if (pointB === null) {
  51042. pointB = cacheSoloPointer;
  51043. }
  51044. if (!noPreventDefault) {
  51045. evt.preventDefault();
  51046. element.focus();
  51047. }
  51048. }
  51049. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  51050. if (_this.camera.useInputToRestoreState) {
  51051. _this.camera.restoreState();
  51052. }
  51053. }
  51054. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  51055. try {
  51056. srcElement.releasePointerCapture(evt.pointerId);
  51057. }
  51058. catch (e) {
  51059. //Nothing to do with the error.
  51060. }
  51061. cacheSoloPointer = null;
  51062. previousPinchSquaredDistance = 0;
  51063. previousMultiTouchPanPosition.isPaning = false;
  51064. previousMultiTouchPanPosition.isPinching = false;
  51065. twoFingerActivityCount = 0;
  51066. initialDistance = 0;
  51067. if (!isTouch) {
  51068. pointB = null; // Mouse and pen are mono pointer
  51069. }
  51070. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  51071. //but emptying completly pointers collection is required to fix a bug on iPhone :
  51072. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  51073. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  51074. if (engine._badOS) {
  51075. pointA = pointB = null;
  51076. }
  51077. else {
  51078. //only remove the impacted pointer in case of multitouch allowing on most
  51079. //platforms switching from rotate to zoom and pan seamlessly.
  51080. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  51081. pointA = pointB;
  51082. pointB = null;
  51083. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  51084. }
  51085. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  51086. pointB = null;
  51087. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  51088. }
  51089. else {
  51090. pointA = pointB = null;
  51091. }
  51092. }
  51093. if (!noPreventDefault) {
  51094. evt.preventDefault();
  51095. }
  51096. }
  51097. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  51098. if (!noPreventDefault) {
  51099. evt.preventDefault();
  51100. }
  51101. // One button down
  51102. if (pointA && pointB === null && cacheSoloPointer) {
  51103. if (_this.panningSensibility !== 0 &&
  51104. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  51105. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  51106. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  51107. }
  51108. else {
  51109. var offsetX = evt.clientX - cacheSoloPointer.x;
  51110. var offsetY = evt.clientY - cacheSoloPointer.y;
  51111. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  51112. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  51113. }
  51114. cacheSoloPointer.x = evt.clientX;
  51115. cacheSoloPointer.y = evt.clientY;
  51116. }
  51117. // Two buttons down: pinch/pan
  51118. else if (pointA && pointB) {
  51119. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  51120. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  51121. ed.x = evt.clientX;
  51122. ed.y = evt.clientY;
  51123. var direction = _this.pinchInwards ? 1 : -1;
  51124. var distX = pointA.x - pointB.x;
  51125. var distY = pointA.y - pointB.y;
  51126. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  51127. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  51128. if (previousPinchSquaredDistance === 0) {
  51129. initialDistance = pinchDistance;
  51130. previousPinchSquaredDistance = pinchSquaredDistance;
  51131. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  51132. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  51133. return;
  51134. }
  51135. if (_this.multiTouchPanAndZoom) {
  51136. if (_this.pinchDeltaPercentage) {
  51137. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  51138. }
  51139. else {
  51140. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  51141. (_this.pinchPrecision *
  51142. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  51143. direction);
  51144. }
  51145. if (_this.panningSensibility !== 0) {
  51146. var pointersCenterX = (pointA.x + pointB.x) / 2;
  51147. var pointersCenterY = (pointA.y + pointB.y) / 2;
  51148. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  51149. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  51150. previousMultiTouchPanPosition.x = pointersCenterX;
  51151. previousMultiTouchPanPosition.y = pointersCenterY;
  51152. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  51153. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  51154. }
  51155. }
  51156. else {
  51157. twoFingerActivityCount++;
  51158. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  51159. if (_this.pinchDeltaPercentage) {
  51160. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  51161. }
  51162. else {
  51163. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  51164. (_this.pinchPrecision *
  51165. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  51166. direction);
  51167. }
  51168. previousMultiTouchPanPosition.isPaning = false;
  51169. previousMultiTouchPanPosition.isPinching = true;
  51170. }
  51171. else {
  51172. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  51173. if (!previousMultiTouchPanPosition.isPaning) {
  51174. previousMultiTouchPanPosition.isPaning = true;
  51175. previousMultiTouchPanPosition.isPinching = false;
  51176. previousMultiTouchPanPosition.x = ed.x;
  51177. previousMultiTouchPanPosition.y = ed.y;
  51178. return;
  51179. }
  51180. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  51181. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  51182. }
  51183. }
  51184. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  51185. previousMultiTouchPanPosition.x = ed.x;
  51186. previousMultiTouchPanPosition.y = ed.y;
  51187. }
  51188. }
  51189. previousPinchSquaredDistance = pinchSquaredDistance;
  51190. }
  51191. }
  51192. };
  51193. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  51194. this._onContextMenu = function (evt) {
  51195. evt.preventDefault();
  51196. };
  51197. if (!this.camera._useCtrlForPanning) {
  51198. element.addEventListener("contextmenu", this._onContextMenu, false);
  51199. }
  51200. this._onLostFocus = function () {
  51201. //this._keys = [];
  51202. pointA = pointB = null;
  51203. previousPinchSquaredDistance = 0;
  51204. previousMultiTouchPanPosition.isPaning = false;
  51205. previousMultiTouchPanPosition.isPinching = false;
  51206. twoFingerActivityCount = 0;
  51207. cacheSoloPointer = null;
  51208. initialDistance = 0;
  51209. };
  51210. this._onMouseMove = function (evt) {
  51211. if (!engine.isPointerLock) {
  51212. return;
  51213. }
  51214. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  51215. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  51216. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  51217. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  51218. if (!noPreventDefault) {
  51219. evt.preventDefault();
  51220. }
  51221. };
  51222. this._onGestureStart = function (e) {
  51223. if (window.MSGesture === undefined) {
  51224. return;
  51225. }
  51226. if (!_this._MSGestureHandler) {
  51227. _this._MSGestureHandler = new MSGesture();
  51228. _this._MSGestureHandler.target = element;
  51229. }
  51230. _this._MSGestureHandler.addPointer(e.pointerId);
  51231. };
  51232. this._onGesture = function (e) {
  51233. _this.camera.radius *= e.scale;
  51234. if (e.preventDefault) {
  51235. if (!noPreventDefault) {
  51236. e.stopPropagation();
  51237. e.preventDefault();
  51238. }
  51239. }
  51240. };
  51241. element.addEventListener("mousemove", this._onMouseMove, false);
  51242. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  51243. element.addEventListener("MSGestureChange", this._onGesture, false);
  51244. BABYLON.Tools.RegisterTopRootEvents([
  51245. { name: "blur", handler: this._onLostFocus }
  51246. ]);
  51247. };
  51248. /**
  51249. * Detach the current controls from the specified dom element.
  51250. * @param element Defines the element to stop listening the inputs from
  51251. */
  51252. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  51253. if (this._onLostFocus) {
  51254. BABYLON.Tools.UnregisterTopRootEvents([
  51255. { name: "blur", handler: this._onLostFocus }
  51256. ]);
  51257. }
  51258. if (element && this._observer) {
  51259. this.camera.getScene().onPointerObservable.remove(this._observer);
  51260. this._observer = null;
  51261. if (this._onContextMenu) {
  51262. element.removeEventListener("contextmenu", this._onContextMenu);
  51263. }
  51264. if (this._onMouseMove) {
  51265. element.removeEventListener("mousemove", this._onMouseMove);
  51266. }
  51267. if (this._onGestureStart) {
  51268. element.removeEventListener("MSPointerDown", this._onGestureStart);
  51269. }
  51270. if (this._onGesture) {
  51271. element.removeEventListener("MSGestureChange", this._onGesture);
  51272. }
  51273. this._isPanClick = false;
  51274. this.pinchInwards = true;
  51275. this._onMouseMove = null;
  51276. this._onGestureStart = null;
  51277. this._onGesture = null;
  51278. this._MSGestureHandler = null;
  51279. this._onLostFocus = null;
  51280. this._onContextMenu = null;
  51281. }
  51282. };
  51283. /**
  51284. * Gets the class name of the current intput.
  51285. * @returns the class name
  51286. */
  51287. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  51288. return "ArcRotateCameraPointersInput";
  51289. };
  51290. /**
  51291. * Get the friendly name associated with the input class.
  51292. * @returns the input friendly name
  51293. */
  51294. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  51295. return "pointers";
  51296. };
  51297. __decorate([
  51298. BABYLON.serialize()
  51299. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  51300. __decorate([
  51301. BABYLON.serialize()
  51302. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  51303. __decorate([
  51304. BABYLON.serialize()
  51305. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  51306. __decorate([
  51307. BABYLON.serialize()
  51308. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  51309. __decorate([
  51310. BABYLON.serialize()
  51311. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  51312. __decorate([
  51313. BABYLON.serialize()
  51314. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  51315. __decorate([
  51316. BABYLON.serialize()
  51317. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  51318. __decorate([
  51319. BABYLON.serialize()
  51320. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  51321. return ArcRotateCameraPointersInput;
  51322. }());
  51323. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  51324. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  51325. })(BABYLON || (BABYLON = {}));
  51326. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  51327. var BABYLON;
  51328. (function (BABYLON) {
  51329. /**
  51330. * Default Inputs manager for the ArcRotateCamera.
  51331. * It groups all the default supported inputs for ease of use.
  51332. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  51333. */
  51334. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  51335. __extends(ArcRotateCameraInputsManager, _super);
  51336. /**
  51337. * Instantiates a new ArcRotateCameraInputsManager.
  51338. * @param camera Defines the camera the inputs belong to
  51339. */
  51340. function ArcRotateCameraInputsManager(camera) {
  51341. return _super.call(this, camera) || this;
  51342. }
  51343. /**
  51344. * Add mouse wheel input support to the input manager.
  51345. * @returns the current input manager
  51346. */
  51347. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  51348. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  51349. return this;
  51350. };
  51351. /**
  51352. * Add pointers input support to the input manager.
  51353. * @returns the current input manager
  51354. */
  51355. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  51356. this.add(new BABYLON.ArcRotateCameraPointersInput());
  51357. return this;
  51358. };
  51359. /**
  51360. * Add keyboard input support to the input manager.
  51361. * @returns the current input manager
  51362. */
  51363. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  51364. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  51365. return this;
  51366. };
  51367. /**
  51368. * Add orientation input support to the input manager.
  51369. * @returns the current input manager
  51370. */
  51371. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  51372. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  51373. return this;
  51374. };
  51375. return ArcRotateCameraInputsManager;
  51376. }(BABYLON.CameraInputsManager));
  51377. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  51378. })(BABYLON || (BABYLON = {}));
  51379. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  51380. var BABYLON;
  51381. (function (BABYLON) {
  51382. BABYLON.Node.AddNodeConstructor("ArcRotateCamera", function (name, scene) {
  51383. return function () { return new ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  51384. });
  51385. /**
  51386. * This represents an orbital type of camera.
  51387. *
  51388. * 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.
  51389. * 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.
  51390. * @see http://doc.babylonjs.com/babylon101/cameras#arc-rotate-camera
  51391. */
  51392. var ArcRotateCamera = /** @class */ (function (_super) {
  51393. __extends(ArcRotateCamera, _super);
  51394. /**
  51395. * Instantiates a new ArcRotateCamera in a given scene
  51396. * @param name Defines the name of the camera
  51397. * @param alpha Defines the camera rotation along the logitudinal axis
  51398. * @param beta Defines the camera rotation along the latitudinal axis
  51399. * @param radius Defines the camera distance from its target
  51400. * @param target Defines the camera target
  51401. * @param scene Defines the scene the camera belongs to
  51402. * @param setActiveOnSceneIfNoneActive Defines wheter the camera should be marked as active if not other active cameras have been defined
  51403. */
  51404. function ArcRotateCamera(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive) {
  51405. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  51406. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene, setActiveOnSceneIfNoneActive) || this;
  51407. /**
  51408. * Current inertia value on the longitudinal axis.
  51409. * The bigger this number the longer it will take for the camera to stop.
  51410. */
  51411. _this.inertialAlphaOffset = 0;
  51412. /**
  51413. * Current inertia value on the latitudinal axis.
  51414. * The bigger this number the longer it will take for the camera to stop.
  51415. */
  51416. _this.inertialBetaOffset = 0;
  51417. /**
  51418. * Current inertia value on the radius axis.
  51419. * The bigger this number the longer it will take for the camera to stop.
  51420. */
  51421. _this.inertialRadiusOffset = 0;
  51422. /**
  51423. * Minimum allowed angle on the longitudinal axis.
  51424. * This can help limiting how the Camera is able to move in the scene.
  51425. */
  51426. _this.lowerAlphaLimit = null;
  51427. /**
  51428. * Maximum allowed angle on the longitudinal axis.
  51429. * This can help limiting how the Camera is able to move in the scene.
  51430. */
  51431. _this.upperAlphaLimit = null;
  51432. /**
  51433. * Minimum allowed angle on the latitudinal axis.
  51434. * This can help limiting how the Camera is able to move in the scene.
  51435. */
  51436. _this.lowerBetaLimit = 0.01;
  51437. /**
  51438. * Maximum allowed angle on the latitudinal axis.
  51439. * This can help limiting how the Camera is able to move in the scene.
  51440. */
  51441. _this.upperBetaLimit = Math.PI;
  51442. /**
  51443. * Minimum allowed distance of the camera to the target (The camera can not get closer).
  51444. * This can help limiting how the Camera is able to move in the scene.
  51445. */
  51446. _this.lowerRadiusLimit = null;
  51447. /**
  51448. * Maximum allowed distance of the camera to the target (The camera can not get further).
  51449. * This can help limiting how the Camera is able to move in the scene.
  51450. */
  51451. _this.upperRadiusLimit = null;
  51452. /**
  51453. * Defines the current inertia value used during panning of the camera along the X axis.
  51454. */
  51455. _this.inertialPanningX = 0;
  51456. /**
  51457. * Defines the current inertia value used during panning of the camera along the Y axis.
  51458. */
  51459. _this.inertialPanningY = 0;
  51460. /**
  51461. * Defines the distance used to consider the camera in pan mode vs pinch/zoom.
  51462. * Basically if your fingers moves away from more than this distance you will be considered
  51463. * in pinch mode.
  51464. */
  51465. _this.pinchToPanMaxDistance = 20;
  51466. /**
  51467. * Defines the maximum distance the camera can pan.
  51468. * This could help keeping the cammera always in your scene.
  51469. */
  51470. _this.panningDistanceLimit = null;
  51471. /**
  51472. * Defines the target of the camera before paning.
  51473. */
  51474. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  51475. /**
  51476. * Defines the value of the inertia used during panning.
  51477. * 0 would mean stop inertia and one would mean no decelleration at all.
  51478. */
  51479. _this.panningInertia = 0.9;
  51480. //-- end properties for backward compatibility for inputs
  51481. /**
  51482. * Defines how much the radius should be scaled while zomming on a particular mesh (through the zoomOn function)
  51483. */
  51484. _this.zoomOnFactor = 1;
  51485. /**
  51486. * Defines a screen offset for the camera position.
  51487. */
  51488. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  51489. /**
  51490. * Allows the camera to be completely reversed.
  51491. * If false the camera can not arrive upside down.
  51492. */
  51493. _this.allowUpsideDown = true;
  51494. /**
  51495. * Define if double tap/click is used to restore the previously saved state of the camera.
  51496. */
  51497. _this.useInputToRestoreState = true;
  51498. /** @hidden */
  51499. _this._viewMatrix = new BABYLON.Matrix();
  51500. /**
  51501. * Defines the allowed panning axis.
  51502. */
  51503. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  51504. /**
  51505. * Observable triggered when the mesh target has been changed on the camera.
  51506. */
  51507. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  51508. /**
  51509. * Defines whether the camera should check collision with the objects oh the scene.
  51510. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#how-can-i-do-this
  51511. */
  51512. _this.checkCollisions = false;
  51513. /**
  51514. * Defines the collision radius of the camera.
  51515. * This simulates a sphere around the camera.
  51516. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#arcrotatecamera
  51517. */
  51518. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  51519. _this._previousPosition = BABYLON.Vector3.Zero();
  51520. _this._collisionVelocity = BABYLON.Vector3.Zero();
  51521. _this._newPosition = BABYLON.Vector3.Zero();
  51522. _this._computationVector = BABYLON.Vector3.Zero();
  51523. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  51524. if (collidedMesh === void 0) { collidedMesh = null; }
  51525. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  51526. newPosition.multiplyInPlace(_this._collider._radius);
  51527. }
  51528. if (!collidedMesh) {
  51529. _this._previousPosition.copyFrom(_this.position);
  51530. }
  51531. else {
  51532. _this.setPosition(newPosition);
  51533. if (_this.onCollide) {
  51534. _this.onCollide(collidedMesh);
  51535. }
  51536. }
  51537. // Recompute because of constraints
  51538. var cosa = Math.cos(_this.alpha);
  51539. var sina = Math.sin(_this.alpha);
  51540. var cosb = Math.cos(_this.beta);
  51541. var sinb = Math.sin(_this.beta);
  51542. if (sinb === 0) {
  51543. sinb = 0.0001;
  51544. }
  51545. var target = _this._getTargetPosition();
  51546. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  51547. target.addToRef(_this._computationVector, _this._newPosition);
  51548. _this.position.copyFrom(_this._newPosition);
  51549. var up = _this.upVector;
  51550. if (_this.allowUpsideDown && _this.beta < 0) {
  51551. up = up.clone();
  51552. up = up.negate();
  51553. }
  51554. _this._computeViewMatrix(_this.position, target, up);
  51555. _this._viewMatrix.addAtIndex(12, _this.targetScreenOffset.x);
  51556. _this._viewMatrix.addAtIndex(13, _this.targetScreenOffset.y);
  51557. _this._collisionTriggered = false;
  51558. };
  51559. _this._target = BABYLON.Vector3.Zero();
  51560. if (target) {
  51561. _this.setTarget(target);
  51562. }
  51563. _this.alpha = alpha;
  51564. _this.beta = beta;
  51565. _this.radius = radius;
  51566. _this.getViewMatrix();
  51567. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  51568. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  51569. return _this;
  51570. }
  51571. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  51572. /**
  51573. * Defines the target point of the camera.
  51574. * The camera looks towards it form the radius distance.
  51575. */
  51576. get: function () {
  51577. return this._target;
  51578. },
  51579. set: function (value) {
  51580. this.setTarget(value);
  51581. },
  51582. enumerable: true,
  51583. configurable: true
  51584. });
  51585. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  51586. //-- begin properties for backward compatibility for inputs
  51587. /**
  51588. * Gets or Set the pointer angular sensibility along the X axis or how fast is the camera rotating.
  51589. */
  51590. get: function () {
  51591. var pointers = this.inputs.attached["pointers"];
  51592. if (pointers) {
  51593. return pointers.angularSensibilityX;
  51594. }
  51595. return 0;
  51596. },
  51597. set: function (value) {
  51598. var pointers = this.inputs.attached["pointers"];
  51599. if (pointers) {
  51600. pointers.angularSensibilityX = value;
  51601. }
  51602. },
  51603. enumerable: true,
  51604. configurable: true
  51605. });
  51606. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  51607. /**
  51608. * Gets or Set the pointer angular sensibility along the Y axis or how fast is the camera rotating.
  51609. */
  51610. get: function () {
  51611. var pointers = this.inputs.attached["pointers"];
  51612. if (pointers) {
  51613. return pointers.angularSensibilityY;
  51614. }
  51615. return 0;
  51616. },
  51617. set: function (value) {
  51618. var pointers = this.inputs.attached["pointers"];
  51619. if (pointers) {
  51620. pointers.angularSensibilityY = value;
  51621. }
  51622. },
  51623. enumerable: true,
  51624. configurable: true
  51625. });
  51626. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  51627. /**
  51628. * Gets or Set the pointer pinch precision or how fast is the camera zooming.
  51629. */
  51630. get: function () {
  51631. var pointers = this.inputs.attached["pointers"];
  51632. if (pointers) {
  51633. return pointers.pinchPrecision;
  51634. }
  51635. return 0;
  51636. },
  51637. set: function (value) {
  51638. var pointers = this.inputs.attached["pointers"];
  51639. if (pointers) {
  51640. pointers.pinchPrecision = value;
  51641. }
  51642. },
  51643. enumerable: true,
  51644. configurable: true
  51645. });
  51646. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  51647. /**
  51648. * Gets or Set the pointer pinch delta percentage or how fast is the camera zooming.
  51649. * It will be used instead of pinchDeltaPrecision if different from 0.
  51650. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  51651. */
  51652. get: function () {
  51653. var pointers = this.inputs.attached["pointers"];
  51654. if (pointers) {
  51655. return pointers.pinchDeltaPercentage;
  51656. }
  51657. return 0;
  51658. },
  51659. set: function (value) {
  51660. var pointers = this.inputs.attached["pointers"];
  51661. if (pointers) {
  51662. pointers.pinchDeltaPercentage = value;
  51663. }
  51664. },
  51665. enumerable: true,
  51666. configurable: true
  51667. });
  51668. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  51669. /**
  51670. * Gets or Set the pointer panning sensibility or how fast is the camera moving.
  51671. */
  51672. get: function () {
  51673. var pointers = this.inputs.attached["pointers"];
  51674. if (pointers) {
  51675. return pointers.panningSensibility;
  51676. }
  51677. return 0;
  51678. },
  51679. set: function (value) {
  51680. var pointers = this.inputs.attached["pointers"];
  51681. if (pointers) {
  51682. pointers.panningSensibility = value;
  51683. }
  51684. },
  51685. enumerable: true,
  51686. configurable: true
  51687. });
  51688. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  51689. /**
  51690. * Gets or Set the list of keyboard keys used to control beta angle in a positive direction.
  51691. */
  51692. get: function () {
  51693. var keyboard = this.inputs.attached["keyboard"];
  51694. if (keyboard) {
  51695. return keyboard.keysUp;
  51696. }
  51697. return [];
  51698. },
  51699. set: function (value) {
  51700. var keyboard = this.inputs.attached["keyboard"];
  51701. if (keyboard) {
  51702. keyboard.keysUp = value;
  51703. }
  51704. },
  51705. enumerable: true,
  51706. configurable: true
  51707. });
  51708. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  51709. /**
  51710. * Gets or Set the list of keyboard keys used to control beta angle in a negative direction.
  51711. */
  51712. get: function () {
  51713. var keyboard = this.inputs.attached["keyboard"];
  51714. if (keyboard) {
  51715. return keyboard.keysDown;
  51716. }
  51717. return [];
  51718. },
  51719. set: function (value) {
  51720. var keyboard = this.inputs.attached["keyboard"];
  51721. if (keyboard) {
  51722. keyboard.keysDown = value;
  51723. }
  51724. },
  51725. enumerable: true,
  51726. configurable: true
  51727. });
  51728. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  51729. /**
  51730. * Gets or Set the list of keyboard keys used to control alpha angle in a negative direction.
  51731. */
  51732. get: function () {
  51733. var keyboard = this.inputs.attached["keyboard"];
  51734. if (keyboard) {
  51735. return keyboard.keysLeft;
  51736. }
  51737. return [];
  51738. },
  51739. set: function (value) {
  51740. var keyboard = this.inputs.attached["keyboard"];
  51741. if (keyboard) {
  51742. keyboard.keysLeft = value;
  51743. }
  51744. },
  51745. enumerable: true,
  51746. configurable: true
  51747. });
  51748. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  51749. /**
  51750. * Gets or Set the list of keyboard keys used to control alpha angle in a positive direction.
  51751. */
  51752. get: function () {
  51753. var keyboard = this.inputs.attached["keyboard"];
  51754. if (keyboard) {
  51755. return keyboard.keysRight;
  51756. }
  51757. return [];
  51758. },
  51759. set: function (value) {
  51760. var keyboard = this.inputs.attached["keyboard"];
  51761. if (keyboard) {
  51762. keyboard.keysRight = value;
  51763. }
  51764. },
  51765. enumerable: true,
  51766. configurable: true
  51767. });
  51768. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  51769. /**
  51770. * Gets or Set the mouse wheel precision or how fast is the camera zooming.
  51771. */
  51772. get: function () {
  51773. var mousewheel = this.inputs.attached["mousewheel"];
  51774. if (mousewheel) {
  51775. return mousewheel.wheelPrecision;
  51776. }
  51777. return 0;
  51778. },
  51779. set: function (value) {
  51780. var mousewheel = this.inputs.attached["mousewheel"];
  51781. if (mousewheel) {
  51782. mousewheel.wheelPrecision = value;
  51783. }
  51784. },
  51785. enumerable: true,
  51786. configurable: true
  51787. });
  51788. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  51789. /**
  51790. * Gets or Set the mouse wheel delta percentage or how fast is the camera zooming.
  51791. * It will be used instead of pinchDeltaPrecision if different from 0.
  51792. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  51793. */
  51794. get: function () {
  51795. var mousewheel = this.inputs.attached["mousewheel"];
  51796. if (mousewheel) {
  51797. return mousewheel.wheelDeltaPercentage;
  51798. }
  51799. return 0;
  51800. },
  51801. set: function (value) {
  51802. var mousewheel = this.inputs.attached["mousewheel"];
  51803. if (mousewheel) {
  51804. mousewheel.wheelDeltaPercentage = value;
  51805. }
  51806. },
  51807. enumerable: true,
  51808. configurable: true
  51809. });
  51810. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  51811. /**
  51812. * Gets the bouncing behavior of the camera if it has been enabled.
  51813. * @see http://doc.babylonjs.com/how_to/camera_behaviors#bouncing-behavior
  51814. */
  51815. get: function () {
  51816. return this._bouncingBehavior;
  51817. },
  51818. enumerable: true,
  51819. configurable: true
  51820. });
  51821. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  51822. /**
  51823. * Defines if the bouncing behavior of the camera is enabled on the camera.
  51824. * @see http://doc.babylonjs.com/how_to/camera_behaviors#bouncing-behavior
  51825. */
  51826. get: function () {
  51827. return this._bouncingBehavior != null;
  51828. },
  51829. set: function (value) {
  51830. if (value === this.useBouncingBehavior) {
  51831. return;
  51832. }
  51833. if (value) {
  51834. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  51835. this.addBehavior(this._bouncingBehavior);
  51836. }
  51837. else if (this._bouncingBehavior) {
  51838. this.removeBehavior(this._bouncingBehavior);
  51839. this._bouncingBehavior = null;
  51840. }
  51841. },
  51842. enumerable: true,
  51843. configurable: true
  51844. });
  51845. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  51846. /**
  51847. * Gets the framing behavior of the camera if it has been enabled.
  51848. * @see http://doc.babylonjs.com/how_to/camera_behaviors#framing-behavior
  51849. */
  51850. get: function () {
  51851. return this._framingBehavior;
  51852. },
  51853. enumerable: true,
  51854. configurable: true
  51855. });
  51856. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  51857. /**
  51858. * Defines if the framing behavior of the camera is enabled on the camera.
  51859. * @see http://doc.babylonjs.com/how_to/camera_behaviors#framing-behavior
  51860. */
  51861. get: function () {
  51862. return this._framingBehavior != null;
  51863. },
  51864. set: function (value) {
  51865. if (value === this.useFramingBehavior) {
  51866. return;
  51867. }
  51868. if (value) {
  51869. this._framingBehavior = new BABYLON.FramingBehavior();
  51870. this.addBehavior(this._framingBehavior);
  51871. }
  51872. else if (this._framingBehavior) {
  51873. this.removeBehavior(this._framingBehavior);
  51874. this._framingBehavior = null;
  51875. }
  51876. },
  51877. enumerable: true,
  51878. configurable: true
  51879. });
  51880. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  51881. /**
  51882. * Gets the auto rotation behavior of the camera if it has been enabled.
  51883. * @see http://doc.babylonjs.com/how_to/camera_behaviors#autorotation-behavior
  51884. */
  51885. get: function () {
  51886. return this._autoRotationBehavior;
  51887. },
  51888. enumerable: true,
  51889. configurable: true
  51890. });
  51891. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  51892. /**
  51893. * Defines if the auto rotation behavior of the camera is enabled on the camera.
  51894. * @see http://doc.babylonjs.com/how_to/camera_behaviors#autorotation-behavior
  51895. */
  51896. get: function () {
  51897. return this._autoRotationBehavior != null;
  51898. },
  51899. set: function (value) {
  51900. if (value === this.useAutoRotationBehavior) {
  51901. return;
  51902. }
  51903. if (value) {
  51904. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  51905. this.addBehavior(this._autoRotationBehavior);
  51906. }
  51907. else if (this._autoRotationBehavior) {
  51908. this.removeBehavior(this._autoRotationBehavior);
  51909. this._autoRotationBehavior = null;
  51910. }
  51911. },
  51912. enumerable: true,
  51913. configurable: true
  51914. });
  51915. // Cache
  51916. /** @hidden */
  51917. ArcRotateCamera.prototype._initCache = function () {
  51918. _super.prototype._initCache.call(this);
  51919. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  51920. this._cache.alpha = undefined;
  51921. this._cache.beta = undefined;
  51922. this._cache.radius = undefined;
  51923. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  51924. };
  51925. /** @hidden */
  51926. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  51927. if (!ignoreParentClass) {
  51928. _super.prototype._updateCache.call(this);
  51929. }
  51930. this._cache._target.copyFrom(this._getTargetPosition());
  51931. this._cache.alpha = this.alpha;
  51932. this._cache.beta = this.beta;
  51933. this._cache.radius = this.radius;
  51934. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  51935. };
  51936. ArcRotateCamera.prototype._getTargetPosition = function () {
  51937. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  51938. var pos = this._targetHost.absolutePosition;
  51939. if (this._targetBoundingCenter) {
  51940. pos.addToRef(this._targetBoundingCenter, this._target);
  51941. }
  51942. else {
  51943. this._target.copyFrom(pos);
  51944. }
  51945. }
  51946. var lockedTargetPosition = this._getLockedTargetPosition();
  51947. if (lockedTargetPosition) {
  51948. return lockedTargetPosition;
  51949. }
  51950. return this._target;
  51951. };
  51952. /**
  51953. * Stores the current state of the camera (alpha, beta, radius and target)
  51954. * @returns the camera itself
  51955. */
  51956. ArcRotateCamera.prototype.storeState = function () {
  51957. this._storedAlpha = this.alpha;
  51958. this._storedBeta = this.beta;
  51959. this._storedRadius = this.radius;
  51960. this._storedTarget = this._getTargetPosition().clone();
  51961. return _super.prototype.storeState.call(this);
  51962. };
  51963. /**
  51964. * @hidden
  51965. * Restored camera state. You must call storeState() first
  51966. */
  51967. ArcRotateCamera.prototype._restoreStateValues = function () {
  51968. if (!_super.prototype._restoreStateValues.call(this)) {
  51969. return false;
  51970. }
  51971. this.alpha = this._storedAlpha;
  51972. this.beta = this._storedBeta;
  51973. this.radius = this._storedRadius;
  51974. this.setTarget(this._storedTarget.clone());
  51975. this.inertialAlphaOffset = 0;
  51976. this.inertialBetaOffset = 0;
  51977. this.inertialRadiusOffset = 0;
  51978. this.inertialPanningX = 0;
  51979. this.inertialPanningY = 0;
  51980. return true;
  51981. };
  51982. // Synchronized
  51983. /** @hidden */
  51984. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  51985. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  51986. return false;
  51987. }
  51988. return this._cache._target.equals(this._getTargetPosition())
  51989. && this._cache.alpha === this.alpha
  51990. && this._cache.beta === this.beta
  51991. && this._cache.radius === this.radius
  51992. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  51993. };
  51994. /**
  51995. * Attached controls to the current camera.
  51996. * @param element Defines the element the controls should be listened from
  51997. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  51998. * @param useCtrlForPanning Defines whether ctrl is used for paning within the controls
  51999. * @param panningMouseButton Defines whether panning is allowed through mouse click button
  52000. */
  52001. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  52002. var _this = this;
  52003. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  52004. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  52005. this._useCtrlForPanning = useCtrlForPanning;
  52006. this._panningMouseButton = panningMouseButton;
  52007. this.inputs.attachElement(element, noPreventDefault);
  52008. this._reset = function () {
  52009. _this.inertialAlphaOffset = 0;
  52010. _this.inertialBetaOffset = 0;
  52011. _this.inertialRadiusOffset = 0;
  52012. _this.inertialPanningX = 0;
  52013. _this.inertialPanningY = 0;
  52014. };
  52015. };
  52016. /**
  52017. * Detach the current controls from the camera.
  52018. * The camera will stop reacting to inputs.
  52019. * @param element Defines the element to stop listening the inputs from
  52020. */
  52021. ArcRotateCamera.prototype.detachControl = function (element) {
  52022. this.inputs.detachElement(element);
  52023. if (this._reset) {
  52024. this._reset();
  52025. }
  52026. };
  52027. /** @hidden */
  52028. ArcRotateCamera.prototype._checkInputs = function () {
  52029. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  52030. if (this._collisionTriggered) {
  52031. return;
  52032. }
  52033. this.inputs.checkInputs();
  52034. // Inertia
  52035. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  52036. var inertialAlphaOffset = this.inertialAlphaOffset;
  52037. if (this.beta <= 0) {
  52038. inertialAlphaOffset *= -1;
  52039. }
  52040. if (this.getScene().useRightHandedSystem) {
  52041. inertialAlphaOffset *= -1;
  52042. }
  52043. if (this.parent && this.parent._getWorldMatrixDeterminant() < 0) {
  52044. inertialAlphaOffset *= -1;
  52045. }
  52046. this.alpha += inertialAlphaOffset;
  52047. this.beta += this.inertialBetaOffset;
  52048. this.radius -= this.inertialRadiusOffset;
  52049. this.inertialAlphaOffset *= this.inertia;
  52050. this.inertialBetaOffset *= this.inertia;
  52051. this.inertialRadiusOffset *= this.inertia;
  52052. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon) {
  52053. this.inertialAlphaOffset = 0;
  52054. }
  52055. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon) {
  52056. this.inertialBetaOffset = 0;
  52057. }
  52058. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon) {
  52059. this.inertialRadiusOffset = 0;
  52060. }
  52061. }
  52062. // Panning inertia
  52063. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  52064. if (!this._localDirection) {
  52065. this._localDirection = BABYLON.Vector3.Zero();
  52066. this._transformedDirection = BABYLON.Vector3.Zero();
  52067. }
  52068. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  52069. this._localDirection.multiplyInPlace(this.panningAxis);
  52070. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  52071. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  52072. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  52073. if (!this.panningAxis.y) {
  52074. this._transformedDirection.y = 0;
  52075. }
  52076. if (!this._targetHost) {
  52077. if (this.panningDistanceLimit) {
  52078. this._transformedDirection.addInPlace(this._target);
  52079. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  52080. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  52081. this._target.copyFrom(this._transformedDirection);
  52082. }
  52083. }
  52084. else {
  52085. this._target.addInPlace(this._transformedDirection);
  52086. }
  52087. }
  52088. this.inertialPanningX *= this.panningInertia;
  52089. this.inertialPanningY *= this.panningInertia;
  52090. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon) {
  52091. this.inertialPanningX = 0;
  52092. }
  52093. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon) {
  52094. this.inertialPanningY = 0;
  52095. }
  52096. }
  52097. // Limits
  52098. this._checkLimits();
  52099. _super.prototype._checkInputs.call(this);
  52100. };
  52101. ArcRotateCamera.prototype._checkLimits = function () {
  52102. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  52103. if (this.allowUpsideDown && this.beta > Math.PI) {
  52104. this.beta = this.beta - (2 * Math.PI);
  52105. }
  52106. }
  52107. else {
  52108. if (this.beta < this.lowerBetaLimit) {
  52109. this.beta = this.lowerBetaLimit;
  52110. }
  52111. }
  52112. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  52113. if (this.allowUpsideDown && this.beta < -Math.PI) {
  52114. this.beta = this.beta + (2 * Math.PI);
  52115. }
  52116. }
  52117. else {
  52118. if (this.beta > this.upperBetaLimit) {
  52119. this.beta = this.upperBetaLimit;
  52120. }
  52121. }
  52122. if (this.lowerAlphaLimit !== null && this.alpha < this.lowerAlphaLimit) {
  52123. this.alpha = this.lowerAlphaLimit;
  52124. }
  52125. if (this.upperAlphaLimit !== null && this.alpha > this.upperAlphaLimit) {
  52126. this.alpha = this.upperAlphaLimit;
  52127. }
  52128. if (this.lowerRadiusLimit !== null && this.radius < this.lowerRadiusLimit) {
  52129. this.radius = this.lowerRadiusLimit;
  52130. this.inertialRadiusOffset = 0;
  52131. }
  52132. if (this.upperRadiusLimit !== null && this.radius > this.upperRadiusLimit) {
  52133. this.radius = this.upperRadiusLimit;
  52134. this.inertialRadiusOffset = 0;
  52135. }
  52136. };
  52137. /**
  52138. * Rebuilds angles (alpha, beta) and radius from the give position and target.
  52139. */
  52140. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  52141. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  52142. this.radius = this._computationVector.length();
  52143. if (this.radius === 0) {
  52144. this.radius = 0.0001; // Just to avoid division by zero
  52145. }
  52146. // Alpha
  52147. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  52148. if (this._computationVector.z < 0) {
  52149. this.alpha = 2 * Math.PI - this.alpha;
  52150. }
  52151. // Beta
  52152. this.beta = Math.acos(this._computationVector.y / this.radius);
  52153. this._checkLimits();
  52154. };
  52155. /**
  52156. * Use a position to define the current camera related information like aplha, beta and radius
  52157. * @param position Defines the position to set the camera at
  52158. */
  52159. ArcRotateCamera.prototype.setPosition = function (position) {
  52160. if (this.position.equals(position)) {
  52161. return;
  52162. }
  52163. this.position.copyFrom(position);
  52164. this.rebuildAnglesAndRadius();
  52165. };
  52166. /**
  52167. * Defines the target the camera should look at.
  52168. * This will automatically adapt alpha beta and radius to fit within the new target.
  52169. * @param target Defines the new target as a Vector or a mesh
  52170. * @param toBoundingCenter In case of a mesh target, defines wether to target the mesh position or its bounding information center
  52171. * @param allowSamePosition If false, prevents reapplying the new computed position if it is identical to the current one (optim)
  52172. */
  52173. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  52174. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  52175. if (allowSamePosition === void 0) { allowSamePosition = false; }
  52176. if (target.getBoundingInfo) {
  52177. if (toBoundingCenter) {
  52178. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  52179. }
  52180. else {
  52181. this._targetBoundingCenter = null;
  52182. }
  52183. this._targetHost = target;
  52184. this._target = this._getTargetPosition();
  52185. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  52186. }
  52187. else {
  52188. var newTarget = target;
  52189. var currentTarget = this._getTargetPosition();
  52190. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  52191. return;
  52192. }
  52193. this._targetHost = null;
  52194. this._target = newTarget;
  52195. this._targetBoundingCenter = null;
  52196. this.onMeshTargetChangedObservable.notifyObservers(null);
  52197. }
  52198. this.rebuildAnglesAndRadius();
  52199. };
  52200. /** @hidden */
  52201. ArcRotateCamera.prototype._getViewMatrix = function () {
  52202. // Compute
  52203. var cosa = Math.cos(this.alpha);
  52204. var sina = Math.sin(this.alpha);
  52205. var cosb = Math.cos(this.beta);
  52206. var sinb = Math.sin(this.beta);
  52207. if (sinb === 0) {
  52208. sinb = 0.0001;
  52209. }
  52210. var target = this._getTargetPosition();
  52211. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  52212. target.addToRef(this._computationVector, this._newPosition);
  52213. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  52214. if (!this._collider) {
  52215. this._collider = new BABYLON.Collider();
  52216. }
  52217. this._collider._radius = this.collisionRadius;
  52218. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  52219. this._collisionTriggered = true;
  52220. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  52221. }
  52222. else {
  52223. this.position.copyFrom(this._newPosition);
  52224. var up = this.upVector;
  52225. if (this.allowUpsideDown && sinb < 0) {
  52226. up = up.clone();
  52227. up = up.negate();
  52228. }
  52229. this._computeViewMatrix(this.position, target, up);
  52230. this._viewMatrix.addAtIndex(12, this.targetScreenOffset.x);
  52231. this._viewMatrix.addAtIndex(13, this.targetScreenOffset.y);
  52232. }
  52233. this._currentTarget = target;
  52234. return this._viewMatrix;
  52235. };
  52236. /**
  52237. * Zooms on a mesh to be at the min distance where we could see it fully in the current viewport.
  52238. * @param meshes Defines the mesh to zoom on
  52239. * @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)
  52240. */
  52241. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  52242. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  52243. meshes = meshes || this.getScene().meshes;
  52244. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  52245. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  52246. this.radius = distance * this.zoomOnFactor;
  52247. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  52248. };
  52249. /**
  52250. * Focus on a mesh or a bounding box. This adapts the target and maxRadius if necessary but does not update the current radius.
  52251. * The target will be changed but the radius
  52252. * @param meshesOrMinMaxVectorAndDistance Defines the mesh or bounding info to focus on
  52253. * @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)
  52254. */
  52255. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  52256. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  52257. var meshesOrMinMaxVector;
  52258. var distance;
  52259. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  52260. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  52261. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  52262. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  52263. }
  52264. else { //minMaxVector and distance
  52265. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  52266. meshesOrMinMaxVector = minMaxVectorAndDistance;
  52267. distance = minMaxVectorAndDistance.distance;
  52268. }
  52269. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  52270. if (!doNotUpdateMaxZ) {
  52271. this.maxZ = distance * 2;
  52272. }
  52273. };
  52274. /**
  52275. * @override
  52276. * Override Camera.createRigCamera
  52277. */
  52278. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  52279. var alphaShift = 0;
  52280. switch (this.cameraRigMode) {
  52281. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  52282. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  52283. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  52284. case BABYLON.Camera.RIG_MODE_VR:
  52285. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  52286. break;
  52287. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  52288. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  52289. break;
  52290. }
  52291. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  52292. rigCam._cameraRigParams = {};
  52293. return rigCam;
  52294. };
  52295. /**
  52296. * @hidden
  52297. * @override
  52298. * Override Camera._updateRigCameras
  52299. */
  52300. ArcRotateCamera.prototype._updateRigCameras = function () {
  52301. var camLeft = this._rigCameras[0];
  52302. var camRight = this._rigCameras[1];
  52303. camLeft.beta = camRight.beta = this.beta;
  52304. camLeft.radius = camRight.radius = this.radius;
  52305. switch (this.cameraRigMode) {
  52306. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  52307. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  52308. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  52309. case BABYLON.Camera.RIG_MODE_VR:
  52310. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  52311. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  52312. break;
  52313. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  52314. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  52315. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  52316. break;
  52317. }
  52318. _super.prototype._updateRigCameras.call(this);
  52319. };
  52320. /**
  52321. * Destroy the camera and release the current resources hold by it.
  52322. */
  52323. ArcRotateCamera.prototype.dispose = function () {
  52324. this.inputs.clear();
  52325. _super.prototype.dispose.call(this);
  52326. };
  52327. /**
  52328. * Gets the current object class name.
  52329. * @return the class name
  52330. */
  52331. ArcRotateCamera.prototype.getClassName = function () {
  52332. return "ArcRotateCamera";
  52333. };
  52334. __decorate([
  52335. BABYLON.serialize()
  52336. ], ArcRotateCamera.prototype, "alpha", void 0);
  52337. __decorate([
  52338. BABYLON.serialize()
  52339. ], ArcRotateCamera.prototype, "beta", void 0);
  52340. __decorate([
  52341. BABYLON.serialize()
  52342. ], ArcRotateCamera.prototype, "radius", void 0);
  52343. __decorate([
  52344. BABYLON.serializeAsVector3("target")
  52345. ], ArcRotateCamera.prototype, "_target", void 0);
  52346. __decorate([
  52347. BABYLON.serialize()
  52348. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  52349. __decorate([
  52350. BABYLON.serialize()
  52351. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  52352. __decorate([
  52353. BABYLON.serialize()
  52354. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  52355. __decorate([
  52356. BABYLON.serialize()
  52357. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  52358. __decorate([
  52359. BABYLON.serialize()
  52360. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  52361. __decorate([
  52362. BABYLON.serialize()
  52363. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  52364. __decorate([
  52365. BABYLON.serialize()
  52366. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  52367. __decorate([
  52368. BABYLON.serialize()
  52369. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  52370. __decorate([
  52371. BABYLON.serialize()
  52372. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  52373. __decorate([
  52374. BABYLON.serialize()
  52375. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  52376. __decorate([
  52377. BABYLON.serialize()
  52378. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  52379. __decorate([
  52380. BABYLON.serialize()
  52381. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  52382. __decorate([
  52383. BABYLON.serialize()
  52384. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  52385. __decorate([
  52386. BABYLON.serializeAsVector3()
  52387. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  52388. __decorate([
  52389. BABYLON.serialize()
  52390. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  52391. __decorate([
  52392. BABYLON.serialize()
  52393. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  52394. __decorate([
  52395. BABYLON.serialize()
  52396. ], ArcRotateCamera.prototype, "targetScreenOffset", void 0);
  52397. __decorate([
  52398. BABYLON.serialize()
  52399. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  52400. __decorate([
  52401. BABYLON.serialize()
  52402. ], ArcRotateCamera.prototype, "useInputToRestoreState", void 0);
  52403. return ArcRotateCamera;
  52404. }(BABYLON.TargetCamera));
  52405. BABYLON.ArcRotateCamera = ArcRotateCamera;
  52406. })(BABYLON || (BABYLON = {}));
  52407. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  52408. var BABYLON;
  52409. (function (BABYLON) {
  52410. BABYLON.Node.AddNodeConstructor("Light_Type_3", function (name, scene) {
  52411. return function () { return new HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  52412. });
  52413. /**
  52414. * The HemisphericLight simulates the ambient environment light,
  52415. * so the passed direction is the light reflection direction, not the incoming direction.
  52416. */
  52417. var HemisphericLight = /** @class */ (function (_super) {
  52418. __extends(HemisphericLight, _super);
  52419. /**
  52420. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  52421. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  52422. * The HemisphericLight can't cast shadows.
  52423. * Documentation : http://doc.babylonjs.com/tutorials/lights
  52424. * @param name The friendly name of the light
  52425. * @param direction The direction of the light reflection
  52426. * @param scene The scene the light belongs to
  52427. */
  52428. function HemisphericLight(name, direction, scene) {
  52429. var _this = _super.call(this, name, scene) || this;
  52430. /**
  52431. * The groundColor is the light in the opposite direction to the one specified during creation.
  52432. * 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.
  52433. */
  52434. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  52435. _this.direction = direction || BABYLON.Vector3.Up();
  52436. return _this;
  52437. }
  52438. HemisphericLight.prototype._buildUniformLayout = function () {
  52439. this._uniformBuffer.addUniform("vLightData", 4);
  52440. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  52441. this._uniformBuffer.addUniform("vLightSpecular", 3);
  52442. this._uniformBuffer.addUniform("vLightGround", 3);
  52443. this._uniformBuffer.addUniform("shadowsInfo", 3);
  52444. this._uniformBuffer.addUniform("depthValues", 2);
  52445. this._uniformBuffer.create();
  52446. };
  52447. /**
  52448. * Returns the string "HemisphericLight".
  52449. * @return The class name
  52450. */
  52451. HemisphericLight.prototype.getClassName = function () {
  52452. return "HemisphericLight";
  52453. };
  52454. /**
  52455. * Sets the HemisphericLight direction towards the passed target (Vector3).
  52456. * Returns the updated direction.
  52457. * @param target The target the direction should point to
  52458. * @return The computed direction
  52459. */
  52460. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  52461. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  52462. return this.direction;
  52463. };
  52464. /**
  52465. * Returns the shadow generator associated to the light.
  52466. * @returns Always null for hemispheric lights because it does not support shadows.
  52467. */
  52468. HemisphericLight.prototype.getShadowGenerator = function () {
  52469. return null;
  52470. };
  52471. /**
  52472. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  52473. * @param effect The effect to update
  52474. * @param lightIndex The index of the light in the effect to update
  52475. * @returns The hemispheric light
  52476. */
  52477. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  52478. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  52479. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  52480. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  52481. return this;
  52482. };
  52483. /**
  52484. * Computes the world matrix of the node
  52485. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  52486. * @param useWasUpdatedFlag defines a reserved property
  52487. * @returns the world matrix
  52488. */
  52489. HemisphericLight.prototype.computeWorldMatrix = function (force, useWasUpdatedFlag) {
  52490. if (!this._worldMatrix) {
  52491. this._worldMatrix = BABYLON.Matrix.Identity();
  52492. }
  52493. return this._worldMatrix;
  52494. };
  52495. /**
  52496. * Returns the integer 3.
  52497. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  52498. */
  52499. HemisphericLight.prototype.getTypeID = function () {
  52500. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  52501. };
  52502. /**
  52503. * Prepares the list of defines specific to the light type.
  52504. * @param defines the list of defines
  52505. * @param lightIndex defines the index of the light for the effect
  52506. */
  52507. HemisphericLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  52508. defines["HEMILIGHT" + lightIndex] = true;
  52509. };
  52510. __decorate([
  52511. BABYLON.serializeAsColor3()
  52512. ], HemisphericLight.prototype, "groundColor", void 0);
  52513. __decorate([
  52514. BABYLON.serializeAsVector3()
  52515. ], HemisphericLight.prototype, "direction", void 0);
  52516. return HemisphericLight;
  52517. }(BABYLON.Light));
  52518. BABYLON.HemisphericLight = HemisphericLight;
  52519. })(BABYLON || (BABYLON = {}));
  52520. //# sourceMappingURL=babylon.hemisphericLight.js.map
  52521. var BABYLON;
  52522. (function (BABYLON) {
  52523. /**
  52524. * Base implementation IShadowLight
  52525. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  52526. */
  52527. var ShadowLight = /** @class */ (function (_super) {
  52528. __extends(ShadowLight, _super);
  52529. function ShadowLight() {
  52530. var _this = _super !== null && _super.apply(this, arguments) || this;
  52531. _this._needProjectionMatrixCompute = true;
  52532. return _this;
  52533. }
  52534. ShadowLight.prototype._setPosition = function (value) {
  52535. this._position = value;
  52536. };
  52537. Object.defineProperty(ShadowLight.prototype, "position", {
  52538. /**
  52539. * Sets the position the shadow will be casted from. Also use as the light position for both
  52540. * point and spot lights.
  52541. */
  52542. get: function () {
  52543. return this._position;
  52544. },
  52545. /**
  52546. * Sets the position the shadow will be casted from. Also use as the light position for both
  52547. * point and spot lights.
  52548. */
  52549. set: function (value) {
  52550. this._setPosition(value);
  52551. },
  52552. enumerable: true,
  52553. configurable: true
  52554. });
  52555. ShadowLight.prototype._setDirection = function (value) {
  52556. this._direction = value;
  52557. };
  52558. Object.defineProperty(ShadowLight.prototype, "direction", {
  52559. /**
  52560. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  52561. * Also use as the light direction on spot and directional lights.
  52562. */
  52563. get: function () {
  52564. return this._direction;
  52565. },
  52566. /**
  52567. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  52568. * Also use as the light direction on spot and directional lights.
  52569. */
  52570. set: function (value) {
  52571. this._setDirection(value);
  52572. },
  52573. enumerable: true,
  52574. configurable: true
  52575. });
  52576. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  52577. /**
  52578. * Gets the shadow projection clipping minimum z value.
  52579. */
  52580. get: function () {
  52581. return this._shadowMinZ;
  52582. },
  52583. /**
  52584. * Sets the shadow projection clipping minimum z value.
  52585. */
  52586. set: function (value) {
  52587. this._shadowMinZ = value;
  52588. this.forceProjectionMatrixCompute();
  52589. },
  52590. enumerable: true,
  52591. configurable: true
  52592. });
  52593. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  52594. /**
  52595. * Sets the shadow projection clipping maximum z value.
  52596. */
  52597. get: function () {
  52598. return this._shadowMaxZ;
  52599. },
  52600. /**
  52601. * Gets the shadow projection clipping maximum z value.
  52602. */
  52603. set: function (value) {
  52604. this._shadowMaxZ = value;
  52605. this.forceProjectionMatrixCompute();
  52606. },
  52607. enumerable: true,
  52608. configurable: true
  52609. });
  52610. /**
  52611. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  52612. * @returns true if the information has been computed, false if it does not need to (no parenting)
  52613. */
  52614. ShadowLight.prototype.computeTransformedInformation = function () {
  52615. if (this.parent && this.parent.getWorldMatrix) {
  52616. if (!this.transformedPosition) {
  52617. this.transformedPosition = BABYLON.Vector3.Zero();
  52618. }
  52619. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  52620. // In case the direction is present.
  52621. if (this.direction) {
  52622. if (!this.transformedDirection) {
  52623. this.transformedDirection = BABYLON.Vector3.Zero();
  52624. }
  52625. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  52626. }
  52627. return true;
  52628. }
  52629. return false;
  52630. };
  52631. /**
  52632. * Return the depth scale used for the shadow map.
  52633. * @returns the depth scale.
  52634. */
  52635. ShadowLight.prototype.getDepthScale = function () {
  52636. return 50.0;
  52637. };
  52638. /**
  52639. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  52640. * @param faceIndex The index of the face we are computed the direction to generate shadow
  52641. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  52642. */
  52643. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  52644. return this.transformedDirection ? this.transformedDirection : this.direction;
  52645. };
  52646. /**
  52647. * Returns the ShadowLight absolute position in the World.
  52648. * @returns the position vector in world space
  52649. */
  52650. ShadowLight.prototype.getAbsolutePosition = function () {
  52651. return this.transformedPosition ? this.transformedPosition : this.position;
  52652. };
  52653. /**
  52654. * Sets the ShadowLight direction toward the passed target.
  52655. * @param target The point tot target in local space
  52656. * @returns the updated ShadowLight direction
  52657. */
  52658. ShadowLight.prototype.setDirectionToTarget = function (target) {
  52659. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  52660. return this.direction;
  52661. };
  52662. /**
  52663. * Returns the light rotation in euler definition.
  52664. * @returns the x y z rotation in local space.
  52665. */
  52666. ShadowLight.prototype.getRotation = function () {
  52667. this.direction.normalize();
  52668. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  52669. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  52670. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  52671. };
  52672. /**
  52673. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  52674. * @returns true if a cube texture needs to be use
  52675. */
  52676. ShadowLight.prototype.needCube = function () {
  52677. return false;
  52678. };
  52679. /**
  52680. * Detects if the projection matrix requires to be recomputed this frame.
  52681. * @returns true if it requires to be recomputed otherwise, false.
  52682. */
  52683. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  52684. return this._needProjectionMatrixCompute;
  52685. };
  52686. /**
  52687. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  52688. */
  52689. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  52690. this._needProjectionMatrixCompute = true;
  52691. };
  52692. /** @hidden */
  52693. ShadowLight.prototype._initCache = function () {
  52694. _super.prototype._initCache.call(this);
  52695. this._cache.position = BABYLON.Vector3.Zero();
  52696. };
  52697. /** @hidden */
  52698. ShadowLight.prototype._isSynchronized = function () {
  52699. if (!this._cache.position.equals(this.position)) {
  52700. return false;
  52701. }
  52702. return true;
  52703. };
  52704. /**
  52705. * Computes the world matrix of the node
  52706. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  52707. * @returns the world matrix
  52708. */
  52709. ShadowLight.prototype.computeWorldMatrix = function (force) {
  52710. if (!force && this.isSynchronized()) {
  52711. this._currentRenderId = this.getScene().getRenderId();
  52712. return this._worldMatrix;
  52713. }
  52714. this._updateCache();
  52715. this._cache.position.copyFrom(this.position);
  52716. if (!this._worldMatrix) {
  52717. this._worldMatrix = BABYLON.Matrix.Identity();
  52718. }
  52719. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  52720. if (this.parent && this.parent.getWorldMatrix) {
  52721. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  52722. this._markSyncedWithParent();
  52723. }
  52724. // Cache the determinant
  52725. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  52726. return this._worldMatrix;
  52727. };
  52728. /**
  52729. * Gets the minZ used for shadow according to both the scene and the light.
  52730. * @param activeCamera The camera we are returning the min for
  52731. * @returns the depth min z
  52732. */
  52733. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  52734. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  52735. };
  52736. /**
  52737. * Gets the maxZ used for shadow according to both the scene and the light.
  52738. * @param activeCamera The camera we are returning the max for
  52739. * @returns the depth max z
  52740. */
  52741. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  52742. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  52743. };
  52744. /**
  52745. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  52746. * @param matrix The materix to updated with the projection information
  52747. * @param viewMatrix The transform matrix of the light
  52748. * @param renderList The list of mesh to render in the map
  52749. * @returns The current light
  52750. */
  52751. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  52752. if (this.customProjectionMatrixBuilder) {
  52753. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  52754. }
  52755. else {
  52756. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  52757. }
  52758. return this;
  52759. };
  52760. __decorate([
  52761. BABYLON.serializeAsVector3()
  52762. ], ShadowLight.prototype, "position", null);
  52763. __decorate([
  52764. BABYLON.serializeAsVector3()
  52765. ], ShadowLight.prototype, "direction", null);
  52766. __decorate([
  52767. BABYLON.serialize()
  52768. ], ShadowLight.prototype, "shadowMinZ", null);
  52769. __decorate([
  52770. BABYLON.serialize()
  52771. ], ShadowLight.prototype, "shadowMaxZ", null);
  52772. return ShadowLight;
  52773. }(BABYLON.Light));
  52774. BABYLON.ShadowLight = ShadowLight;
  52775. })(BABYLON || (BABYLON = {}));
  52776. //# sourceMappingURL=babylon.shadowLight.js.map
  52777. var BABYLON;
  52778. (function (BABYLON) {
  52779. BABYLON.Node.AddNodeConstructor("Light_Type_0", function (name, scene) {
  52780. return function () { return new PointLight(name, BABYLON.Vector3.Zero(), scene); };
  52781. });
  52782. /**
  52783. * A point light is a light defined by an unique point in world space.
  52784. * The light is emitted in every direction from this point.
  52785. * A good example of a point light is a standard light bulb.
  52786. * Documentation: https://doc.babylonjs.com/babylon101/lights
  52787. */
  52788. var PointLight = /** @class */ (function (_super) {
  52789. __extends(PointLight, _super);
  52790. /**
  52791. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  52792. * A PointLight emits the light in every direction.
  52793. * It can cast shadows.
  52794. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  52795. * ```javascript
  52796. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  52797. * ```
  52798. * Documentation : http://doc.babylonjs.com/tutorials/lights
  52799. * @param name The light friendly name
  52800. * @param position The position of the point light in the scene
  52801. * @param scene The scene the lights belongs to
  52802. */
  52803. function PointLight(name, position, scene) {
  52804. var _this = _super.call(this, name, scene) || this;
  52805. _this._shadowAngle = Math.PI / 2;
  52806. _this.position = position;
  52807. return _this;
  52808. }
  52809. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  52810. /**
  52811. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  52812. * This specifies what angle the shadow will use to be created.
  52813. *
  52814. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  52815. */
  52816. get: function () {
  52817. return this._shadowAngle;
  52818. },
  52819. /**
  52820. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  52821. * This specifies what angle the shadow will use to be created.
  52822. *
  52823. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  52824. */
  52825. set: function (value) {
  52826. this._shadowAngle = value;
  52827. this.forceProjectionMatrixCompute();
  52828. },
  52829. enumerable: true,
  52830. configurable: true
  52831. });
  52832. Object.defineProperty(PointLight.prototype, "direction", {
  52833. /**
  52834. * Gets the direction if it has been set.
  52835. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  52836. */
  52837. get: function () {
  52838. return this._direction;
  52839. },
  52840. /**
  52841. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  52842. */
  52843. set: function (value) {
  52844. var previousNeedCube = this.needCube();
  52845. this._direction = value;
  52846. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  52847. this._shadowGenerator.recreateShadowMap();
  52848. }
  52849. },
  52850. enumerable: true,
  52851. configurable: true
  52852. });
  52853. /**
  52854. * Returns the string "PointLight"
  52855. * @returns the class name
  52856. */
  52857. PointLight.prototype.getClassName = function () {
  52858. return "PointLight";
  52859. };
  52860. /**
  52861. * Returns the integer 0.
  52862. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  52863. */
  52864. PointLight.prototype.getTypeID = function () {
  52865. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  52866. };
  52867. /**
  52868. * Specifies wether or not the shadowmap should be a cube texture.
  52869. * @returns true if the shadowmap needs to be a cube texture.
  52870. */
  52871. PointLight.prototype.needCube = function () {
  52872. return !this.direction;
  52873. };
  52874. /**
  52875. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  52876. * @param faceIndex The index of the face we are computed the direction to generate shadow
  52877. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  52878. */
  52879. PointLight.prototype.getShadowDirection = function (faceIndex) {
  52880. if (this.direction) {
  52881. return _super.prototype.getShadowDirection.call(this, faceIndex);
  52882. }
  52883. else {
  52884. switch (faceIndex) {
  52885. case 0:
  52886. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  52887. case 1:
  52888. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  52889. case 2:
  52890. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  52891. case 3:
  52892. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  52893. case 4:
  52894. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  52895. case 5:
  52896. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  52897. }
  52898. }
  52899. return BABYLON.Vector3.Zero();
  52900. };
  52901. /**
  52902. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  52903. * - fov = PI / 2
  52904. * - aspect ratio : 1.0
  52905. * - z-near and far equal to the active camera minZ and maxZ.
  52906. * Returns the PointLight.
  52907. */
  52908. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  52909. var activeCamera = this.getScene().activeCamera;
  52910. if (!activeCamera) {
  52911. return;
  52912. }
  52913. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  52914. };
  52915. PointLight.prototype._buildUniformLayout = function () {
  52916. this._uniformBuffer.addUniform("vLightData", 4);
  52917. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  52918. this._uniformBuffer.addUniform("vLightSpecular", 3);
  52919. this._uniformBuffer.addUniform("vLightFalloff", 4);
  52920. this._uniformBuffer.addUniform("shadowsInfo", 3);
  52921. this._uniformBuffer.addUniform("depthValues", 2);
  52922. this._uniformBuffer.create();
  52923. };
  52924. /**
  52925. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  52926. * @param effect The effect to update
  52927. * @param lightIndex The index of the light in the effect to update
  52928. * @returns The point light
  52929. */
  52930. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  52931. if (this.computeTransformedInformation()) {
  52932. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  52933. }
  52934. else {
  52935. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  52936. }
  52937. this._uniformBuffer.updateFloat4("vLightFalloff", this.range, this._inverseSquaredRange, 0, 0, lightIndex);
  52938. return this;
  52939. };
  52940. /**
  52941. * Prepares the list of defines specific to the light type.
  52942. * @param defines the list of defines
  52943. * @param lightIndex defines the index of the light for the effect
  52944. */
  52945. PointLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  52946. defines["POINTLIGHT" + lightIndex] = true;
  52947. };
  52948. __decorate([
  52949. BABYLON.serialize()
  52950. ], PointLight.prototype, "shadowAngle", null);
  52951. return PointLight;
  52952. }(BABYLON.ShadowLight));
  52953. BABYLON.PointLight = PointLight;
  52954. })(BABYLON || (BABYLON = {}));
  52955. //# sourceMappingURL=babylon.pointLight.js.map
  52956. var BABYLON;
  52957. (function (BABYLON) {
  52958. BABYLON.Node.AddNodeConstructor("Light_Type_1", function (name, scene) {
  52959. return function () { return new DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  52960. });
  52961. /**
  52962. * A directional light is defined by a direction (what a surprise!).
  52963. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  52964. * 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.
  52965. * Documentation: https://doc.babylonjs.com/babylon101/lights
  52966. */
  52967. var DirectionalLight = /** @class */ (function (_super) {
  52968. __extends(DirectionalLight, _super);
  52969. /**
  52970. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  52971. * The directional light is emitted from everywhere in the given direction.
  52972. * It can cast shadows.
  52973. * Documentation : http://doc.babylonjs.com/tutorials/lights
  52974. * @param name The friendly name of the light
  52975. * @param direction The direction of the light
  52976. * @param scene The scene the light belongs to
  52977. */
  52978. function DirectionalLight(name, direction, scene) {
  52979. var _this = _super.call(this, name, scene) || this;
  52980. _this._shadowFrustumSize = 0;
  52981. _this._shadowOrthoScale = 0.1;
  52982. /**
  52983. * Automatically compute the projection matrix to best fit (including all the casters)
  52984. * on each frame.
  52985. */
  52986. _this.autoUpdateExtends = true;
  52987. // Cache
  52988. _this._orthoLeft = Number.MAX_VALUE;
  52989. _this._orthoRight = Number.MIN_VALUE;
  52990. _this._orthoTop = Number.MIN_VALUE;
  52991. _this._orthoBottom = Number.MAX_VALUE;
  52992. _this.position = direction.scale(-1.0);
  52993. _this.direction = direction;
  52994. return _this;
  52995. }
  52996. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  52997. /**
  52998. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  52999. */
  53000. get: function () {
  53001. return this._shadowFrustumSize;
  53002. },
  53003. /**
  53004. * Specifies a fix frustum size for the shadow generation.
  53005. */
  53006. set: function (value) {
  53007. this._shadowFrustumSize = value;
  53008. this.forceProjectionMatrixCompute();
  53009. },
  53010. enumerable: true,
  53011. configurable: true
  53012. });
  53013. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  53014. /**
  53015. * Gets the shadow projection scale against the optimal computed one.
  53016. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  53017. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  53018. */
  53019. get: function () {
  53020. return this._shadowOrthoScale;
  53021. },
  53022. /**
  53023. * Sets the shadow projection scale against the optimal computed one.
  53024. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  53025. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  53026. */
  53027. set: function (value) {
  53028. this._shadowOrthoScale = value;
  53029. this.forceProjectionMatrixCompute();
  53030. },
  53031. enumerable: true,
  53032. configurable: true
  53033. });
  53034. /**
  53035. * Returns the string "DirectionalLight".
  53036. * @return The class name
  53037. */
  53038. DirectionalLight.prototype.getClassName = function () {
  53039. return "DirectionalLight";
  53040. };
  53041. /**
  53042. * Returns the integer 1.
  53043. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  53044. */
  53045. DirectionalLight.prototype.getTypeID = function () {
  53046. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  53047. };
  53048. /**
  53049. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  53050. * Returns the DirectionalLight Shadow projection matrix.
  53051. */
  53052. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  53053. if (this.shadowFrustumSize > 0) {
  53054. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  53055. }
  53056. else {
  53057. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  53058. }
  53059. };
  53060. /**
  53061. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  53062. * Returns the DirectionalLight Shadow projection matrix.
  53063. */
  53064. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  53065. var activeCamera = this.getScene().activeCamera;
  53066. if (!activeCamera) {
  53067. return;
  53068. }
  53069. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  53070. };
  53071. /**
  53072. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  53073. * Returns the DirectionalLight Shadow projection matrix.
  53074. */
  53075. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  53076. var activeCamera = this.getScene().activeCamera;
  53077. if (!activeCamera) {
  53078. return;
  53079. }
  53080. // Check extends
  53081. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  53082. var tempVector3 = BABYLON.Vector3.Zero();
  53083. this._orthoLeft = Number.MAX_VALUE;
  53084. this._orthoRight = Number.MIN_VALUE;
  53085. this._orthoTop = Number.MIN_VALUE;
  53086. this._orthoBottom = Number.MAX_VALUE;
  53087. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  53088. var mesh = renderList[meshIndex];
  53089. if (!mesh) {
  53090. continue;
  53091. }
  53092. var boundingInfo = mesh.getBoundingInfo();
  53093. var boundingBox = boundingInfo.boundingBox;
  53094. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  53095. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  53096. if (tempVector3.x < this._orthoLeft) {
  53097. this._orthoLeft = tempVector3.x;
  53098. }
  53099. if (tempVector3.y < this._orthoBottom) {
  53100. this._orthoBottom = tempVector3.y;
  53101. }
  53102. if (tempVector3.x > this._orthoRight) {
  53103. this._orthoRight = tempVector3.x;
  53104. }
  53105. if (tempVector3.y > this._orthoTop) {
  53106. this._orthoTop = tempVector3.y;
  53107. }
  53108. }
  53109. }
  53110. }
  53111. var xOffset = this._orthoRight - this._orthoLeft;
  53112. var yOffset = this._orthoTop - this._orthoBottom;
  53113. 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);
  53114. };
  53115. DirectionalLight.prototype._buildUniformLayout = function () {
  53116. this._uniformBuffer.addUniform("vLightData", 4);
  53117. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  53118. this._uniformBuffer.addUniform("vLightSpecular", 3);
  53119. this._uniformBuffer.addUniform("shadowsInfo", 3);
  53120. this._uniformBuffer.addUniform("depthValues", 2);
  53121. this._uniformBuffer.create();
  53122. };
  53123. /**
  53124. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  53125. * @param effect The effect to update
  53126. * @param lightIndex The index of the light in the effect to update
  53127. * @returns The directional light
  53128. */
  53129. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  53130. if (this.computeTransformedInformation()) {
  53131. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  53132. return this;
  53133. }
  53134. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  53135. return this;
  53136. };
  53137. /**
  53138. * Gets the minZ used for shadow according to both the scene and the light.
  53139. *
  53140. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  53141. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  53142. * @param activeCamera The camera we are returning the min for
  53143. * @returns the depth min z
  53144. */
  53145. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  53146. return 1;
  53147. };
  53148. /**
  53149. * Gets the maxZ used for shadow according to both the scene and the light.
  53150. *
  53151. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  53152. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  53153. * @param activeCamera The camera we are returning the max for
  53154. * @returns the depth max z
  53155. */
  53156. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  53157. return 1;
  53158. };
  53159. /**
  53160. * Prepares the list of defines specific to the light type.
  53161. * @param defines the list of defines
  53162. * @param lightIndex defines the index of the light for the effect
  53163. */
  53164. DirectionalLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  53165. defines["DIRLIGHT" + lightIndex] = true;
  53166. };
  53167. __decorate([
  53168. BABYLON.serialize()
  53169. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  53170. __decorate([
  53171. BABYLON.serialize()
  53172. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  53173. __decorate([
  53174. BABYLON.serialize()
  53175. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  53176. return DirectionalLight;
  53177. }(BABYLON.ShadowLight));
  53178. BABYLON.DirectionalLight = DirectionalLight;
  53179. })(BABYLON || (BABYLON = {}));
  53180. //# sourceMappingURL=babylon.directionalLight.js.map
  53181. var BABYLON;
  53182. (function (BABYLON) {
  53183. BABYLON.Node.AddNodeConstructor("Light_Type_2", function (name, scene) {
  53184. return function () { return new SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  53185. });
  53186. /**
  53187. * A spot light is defined by a position, a direction, an angle, and an exponent.
  53188. * These values define a cone of light starting from the position, emitting toward the direction.
  53189. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  53190. * and the exponent defines the speed of the decay of the light with distance (reach).
  53191. * Documentation: https://doc.babylonjs.com/babylon101/lights
  53192. */
  53193. var SpotLight = /** @class */ (function (_super) {
  53194. __extends(SpotLight, _super);
  53195. /**
  53196. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  53197. * It can cast shadows.
  53198. * Documentation : http://doc.babylonjs.com/tutorials/lights
  53199. * @param name The light friendly name
  53200. * @param position The position of the spot light in the scene
  53201. * @param direction The direction of the light in the scene
  53202. * @param angle The cone angle of the light in Radians
  53203. * @param exponent The light decay speed with the distance from the emission spot
  53204. * @param scene The scene the lights belongs to
  53205. */
  53206. function SpotLight(name, position, direction, angle, exponent, scene) {
  53207. var _this = _super.call(this, name, scene) || this;
  53208. _this._innerAngle = 0;
  53209. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  53210. _this._projectionTextureLightNear = 1e-6;
  53211. _this._projectionTextureLightFar = 1000.0;
  53212. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  53213. _this._projectionTextureViewLightDirty = true;
  53214. _this._projectionTextureProjectionLightDirty = true;
  53215. _this._projectionTextureDirty = true;
  53216. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  53217. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  53218. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  53219. _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);
  53220. _this.position = position;
  53221. _this.direction = direction;
  53222. _this.angle = angle;
  53223. _this.exponent = exponent;
  53224. return _this;
  53225. }
  53226. Object.defineProperty(SpotLight.prototype, "angle", {
  53227. /**
  53228. * Gets the cone angle of the spot light in Radians.
  53229. */
  53230. get: function () {
  53231. return this._angle;
  53232. },
  53233. /**
  53234. * Sets the cone angle of the spot light in Radians.
  53235. */
  53236. set: function (value) {
  53237. this._angle = value;
  53238. this._cosHalfAngle = Math.cos(value * 0.5);
  53239. this._projectionTextureProjectionLightDirty = true;
  53240. this.forceProjectionMatrixCompute();
  53241. this._computeAngleValues();
  53242. },
  53243. enumerable: true,
  53244. configurable: true
  53245. });
  53246. Object.defineProperty(SpotLight.prototype, "innerAngle", {
  53247. /**
  53248. * Only used in gltf falloff mode, this defines the angle where
  53249. * the directional falloff will start before cutting at angle which could be seen
  53250. * as outer angle.
  53251. */
  53252. get: function () {
  53253. return this._innerAngle;
  53254. },
  53255. /**
  53256. * Only used in gltf falloff mode, this defines the angle where
  53257. * the directional falloff will start before cutting at angle which could be seen
  53258. * as outer angle.
  53259. */
  53260. set: function (value) {
  53261. this._innerAngle = value;
  53262. this._computeAngleValues();
  53263. },
  53264. enumerable: true,
  53265. configurable: true
  53266. });
  53267. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  53268. /**
  53269. * Allows scaling the angle of the light for shadow generation only.
  53270. */
  53271. get: function () {
  53272. return this._shadowAngleScale;
  53273. },
  53274. /**
  53275. * Allows scaling the angle of the light for shadow generation only.
  53276. */
  53277. set: function (value) {
  53278. this._shadowAngleScale = value;
  53279. this.forceProjectionMatrixCompute();
  53280. },
  53281. enumerable: true,
  53282. configurable: true
  53283. });
  53284. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  53285. /**
  53286. * Allows reading the projecton texture
  53287. */
  53288. get: function () {
  53289. return this._projectionTextureMatrix;
  53290. },
  53291. enumerable: true,
  53292. configurable: true
  53293. });
  53294. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  53295. /**
  53296. * Gets the near clip of the Spotlight for texture projection.
  53297. */
  53298. get: function () {
  53299. return this._projectionTextureLightNear;
  53300. },
  53301. /**
  53302. * Sets the near clip of the Spotlight for texture projection.
  53303. */
  53304. set: function (value) {
  53305. this._projectionTextureLightNear = value;
  53306. this._projectionTextureProjectionLightDirty = true;
  53307. },
  53308. enumerable: true,
  53309. configurable: true
  53310. });
  53311. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  53312. /**
  53313. * Gets the far clip of the Spotlight for texture projection.
  53314. */
  53315. get: function () {
  53316. return this._projectionTextureLightFar;
  53317. },
  53318. /**
  53319. * Sets the far clip of the Spotlight for texture projection.
  53320. */
  53321. set: function (value) {
  53322. this._projectionTextureLightFar = value;
  53323. this._projectionTextureProjectionLightDirty = true;
  53324. },
  53325. enumerable: true,
  53326. configurable: true
  53327. });
  53328. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  53329. /**
  53330. * Gets the Up vector of the Spotlight for texture projection.
  53331. */
  53332. get: function () {
  53333. return this._projectionTextureUpDirection;
  53334. },
  53335. /**
  53336. * Sets the Up vector of the Spotlight for texture projection.
  53337. */
  53338. set: function (value) {
  53339. this._projectionTextureUpDirection = value;
  53340. this._projectionTextureProjectionLightDirty = true;
  53341. },
  53342. enumerable: true,
  53343. configurable: true
  53344. });
  53345. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  53346. /**
  53347. * Gets the projection texture of the light.
  53348. */
  53349. get: function () {
  53350. return this._projectionTexture;
  53351. },
  53352. /**
  53353. * Sets the projection texture of the light.
  53354. */
  53355. set: function (value) {
  53356. this._projectionTexture = value;
  53357. this._projectionTextureDirty = true;
  53358. },
  53359. enumerable: true,
  53360. configurable: true
  53361. });
  53362. /**
  53363. * Returns the string "SpotLight".
  53364. * @returns the class name
  53365. */
  53366. SpotLight.prototype.getClassName = function () {
  53367. return "SpotLight";
  53368. };
  53369. /**
  53370. * Returns the integer 2.
  53371. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  53372. */
  53373. SpotLight.prototype.getTypeID = function () {
  53374. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  53375. };
  53376. /**
  53377. * Overrides the direction setter to recompute the projection texture view light Matrix.
  53378. */
  53379. SpotLight.prototype._setDirection = function (value) {
  53380. _super.prototype._setDirection.call(this, value);
  53381. this._projectionTextureViewLightDirty = true;
  53382. };
  53383. /**
  53384. * Overrides the position setter to recompute the projection texture view light Matrix.
  53385. */
  53386. SpotLight.prototype._setPosition = function (value) {
  53387. _super.prototype._setPosition.call(this, value);
  53388. this._projectionTextureViewLightDirty = true;
  53389. };
  53390. /**
  53391. * 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.
  53392. * Returns the SpotLight.
  53393. */
  53394. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  53395. var activeCamera = this.getScene().activeCamera;
  53396. if (!activeCamera) {
  53397. return;
  53398. }
  53399. this._shadowAngleScale = this._shadowAngleScale || 1;
  53400. var angle = this._shadowAngleScale * this._angle;
  53401. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  53402. };
  53403. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  53404. this._projectionTextureViewLightDirty = false;
  53405. this._projectionTextureDirty = true;
  53406. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  53407. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  53408. };
  53409. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  53410. this._projectionTextureProjectionLightDirty = false;
  53411. this._projectionTextureDirty = true;
  53412. var light_far = this.projectionTextureLightFar;
  53413. var light_near = this.projectionTextureLightNear;
  53414. var P = light_far / (light_far - light_near);
  53415. var Q = -P * light_near;
  53416. var S = 1.0 / Math.tan(this._angle / 2.0);
  53417. var A = 1.0;
  53418. 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);
  53419. };
  53420. /**
  53421. * Main function for light texture projection matrix computing.
  53422. */
  53423. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  53424. this._projectionTextureDirty = false;
  53425. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  53426. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  53427. };
  53428. SpotLight.prototype._buildUniformLayout = function () {
  53429. this._uniformBuffer.addUniform("vLightData", 4);
  53430. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  53431. this._uniformBuffer.addUniform("vLightSpecular", 3);
  53432. this._uniformBuffer.addUniform("vLightDirection", 3);
  53433. this._uniformBuffer.addUniform("vLightFalloff", 4);
  53434. this._uniformBuffer.addUniform("shadowsInfo", 3);
  53435. this._uniformBuffer.addUniform("depthValues", 2);
  53436. this._uniformBuffer.create();
  53437. };
  53438. SpotLight.prototype._computeAngleValues = function () {
  53439. this._lightAngleScale = 1.0 / Math.max(0.001, (Math.cos(this._innerAngle * 0.5) - this._cosHalfAngle));
  53440. this._lightAngleOffset = -this._cosHalfAngle * this._lightAngleScale;
  53441. };
  53442. /**
  53443. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  53444. * @param effect The effect to update
  53445. * @param lightIndex The index of the light in the effect to update
  53446. * @returns The spot light
  53447. */
  53448. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  53449. var normalizeDirection;
  53450. if (this.computeTransformedInformation()) {
  53451. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  53452. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  53453. }
  53454. else {
  53455. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  53456. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  53457. }
  53458. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, this._cosHalfAngle, lightIndex);
  53459. this._uniformBuffer.updateFloat4("vLightFalloff", this.range, this._inverseSquaredRange, this._lightAngleScale, this._lightAngleOffset, lightIndex);
  53460. if (this.projectionTexture && this.projectionTexture.isReady()) {
  53461. if (this._projectionTextureViewLightDirty) {
  53462. this._computeProjectionTextureViewLightMatrix();
  53463. }
  53464. if (this._projectionTextureProjectionLightDirty) {
  53465. this._computeProjectionTextureProjectionLightMatrix();
  53466. }
  53467. if (this._projectionTextureDirty) {
  53468. this._computeProjectionTextureMatrix();
  53469. }
  53470. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  53471. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  53472. }
  53473. return this;
  53474. };
  53475. /**
  53476. * Disposes the light and the associated resources.
  53477. */
  53478. SpotLight.prototype.dispose = function () {
  53479. _super.prototype.dispose.call(this);
  53480. if (this._projectionTexture) {
  53481. this._projectionTexture.dispose();
  53482. }
  53483. };
  53484. /**
  53485. * Prepares the list of defines specific to the light type.
  53486. * @param defines the list of defines
  53487. * @param lightIndex defines the index of the light for the effect
  53488. */
  53489. SpotLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  53490. defines["SPOTLIGHT" + lightIndex] = true;
  53491. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = this.projectionTexture ? true : false;
  53492. };
  53493. __decorate([
  53494. BABYLON.serialize()
  53495. ], SpotLight.prototype, "angle", null);
  53496. __decorate([
  53497. BABYLON.serialize()
  53498. ], SpotLight.prototype, "innerAngle", null);
  53499. __decorate([
  53500. BABYLON.serialize()
  53501. ], SpotLight.prototype, "shadowAngleScale", null);
  53502. __decorate([
  53503. BABYLON.serialize()
  53504. ], SpotLight.prototype, "exponent", void 0);
  53505. __decorate([
  53506. BABYLON.serialize()
  53507. ], SpotLight.prototype, "projectionTextureLightNear", null);
  53508. __decorate([
  53509. BABYLON.serialize()
  53510. ], SpotLight.prototype, "projectionTextureLightFar", null);
  53511. __decorate([
  53512. BABYLON.serialize()
  53513. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  53514. __decorate([
  53515. BABYLON.serializeAsTexture("projectedLightTexture")
  53516. ], SpotLight.prototype, "_projectionTexture", void 0);
  53517. return SpotLight;
  53518. }(BABYLON.ShadowLight));
  53519. BABYLON.SpotLight = SpotLight;
  53520. })(BABYLON || (BABYLON = {}));
  53521. //# sourceMappingURL=babylon.spotLight.js.map
  53522. var BABYLON;
  53523. (function (BABYLON) {
  53524. /**
  53525. * Class used to override all child animations of a given target
  53526. */
  53527. var AnimationPropertiesOverride = /** @class */ (function () {
  53528. function AnimationPropertiesOverride() {
  53529. /**
  53530. * Gets or sets a value indicating if animation blending must be used
  53531. */
  53532. this.enableBlending = false;
  53533. /**
  53534. * Gets or sets the blending speed to use when enableBlending is true
  53535. */
  53536. this.blendingSpeed = 0.01;
  53537. /**
  53538. * Gets or sets the default loop mode to use
  53539. */
  53540. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  53541. }
  53542. return AnimationPropertiesOverride;
  53543. }());
  53544. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  53545. })(BABYLON || (BABYLON = {}));
  53546. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  53547. var BABYLON;
  53548. (function (BABYLON) {
  53549. /**
  53550. * Represents the range of an animation
  53551. */
  53552. var AnimationRange = /** @class */ (function () {
  53553. /**
  53554. * Initializes the range of an animation
  53555. * @param name The name of the animation range
  53556. * @param from The starting frame of the animation
  53557. * @param to The ending frame of the animation
  53558. */
  53559. function AnimationRange(
  53560. /**The name of the animation range**/
  53561. name,
  53562. /**The starting frame of the animation */
  53563. from,
  53564. /**The ending frame of the animation*/
  53565. to) {
  53566. this.name = name;
  53567. this.from = from;
  53568. this.to = to;
  53569. }
  53570. /**
  53571. * Makes a copy of the animation range
  53572. * @returns A copy of the animation range
  53573. */
  53574. AnimationRange.prototype.clone = function () {
  53575. return new AnimationRange(this.name, this.from, this.to);
  53576. };
  53577. return AnimationRange;
  53578. }());
  53579. BABYLON.AnimationRange = AnimationRange;
  53580. /**
  53581. * Composed of a frame, and an action function
  53582. */
  53583. var AnimationEvent = /** @class */ (function () {
  53584. /**
  53585. * Initializes the animation event
  53586. * @param frame The frame for which the event is triggered
  53587. * @param action The event to perform when triggered
  53588. * @param onlyOnce Specifies if the event should be triggered only once
  53589. */
  53590. function AnimationEvent(
  53591. /** The frame for which the event is triggered **/
  53592. frame,
  53593. /** The event to perform when triggered **/
  53594. action,
  53595. /** Specifies if the event should be triggered only once**/
  53596. onlyOnce) {
  53597. this.frame = frame;
  53598. this.action = action;
  53599. this.onlyOnce = onlyOnce;
  53600. /**
  53601. * Specifies if the animation event is done
  53602. */
  53603. this.isDone = false;
  53604. }
  53605. /** @hidden */
  53606. AnimationEvent.prototype._clone = function () {
  53607. return new AnimationEvent(this.frame, this.action, this.onlyOnce);
  53608. };
  53609. return AnimationEvent;
  53610. }());
  53611. BABYLON.AnimationEvent = AnimationEvent;
  53612. /**
  53613. * A cursor which tracks a point on a path
  53614. */
  53615. var PathCursor = /** @class */ (function () {
  53616. /**
  53617. * Initializes the path cursor
  53618. * @param path The path to track
  53619. */
  53620. function PathCursor(path) {
  53621. this.path = path;
  53622. /**
  53623. * Stores path cursor callbacks for when an onchange event is triggered
  53624. */
  53625. this._onchange = new Array();
  53626. /**
  53627. * The value of the path cursor
  53628. */
  53629. this.value = 0;
  53630. /**
  53631. * The animation array of the path cursor
  53632. */
  53633. this.animations = new Array();
  53634. }
  53635. /**
  53636. * Gets the cursor point on the path
  53637. * @returns A point on the path cursor at the cursor location
  53638. */
  53639. PathCursor.prototype.getPoint = function () {
  53640. var point = this.path.getPointAtLengthPosition(this.value);
  53641. return new BABYLON.Vector3(point.x, 0, point.y);
  53642. };
  53643. /**
  53644. * Moves the cursor ahead by the step amount
  53645. * @param step The amount to move the cursor forward
  53646. * @returns This path cursor
  53647. */
  53648. PathCursor.prototype.moveAhead = function (step) {
  53649. if (step === void 0) { step = 0.002; }
  53650. this.move(step);
  53651. return this;
  53652. };
  53653. /**
  53654. * Moves the cursor behind by the step amount
  53655. * @param step The amount to move the cursor back
  53656. * @returns This path cursor
  53657. */
  53658. PathCursor.prototype.moveBack = function (step) {
  53659. if (step === void 0) { step = 0.002; }
  53660. this.move(-step);
  53661. return this;
  53662. };
  53663. /**
  53664. * Moves the cursor by the step amount
  53665. * If the step amount is greater than one, an exception is thrown
  53666. * @param step The amount to move the cursor
  53667. * @returns This path cursor
  53668. */
  53669. PathCursor.prototype.move = function (step) {
  53670. if (Math.abs(step) > 1) {
  53671. throw "step size should be less than 1.";
  53672. }
  53673. this.value += step;
  53674. this.ensureLimits();
  53675. this.raiseOnChange();
  53676. return this;
  53677. };
  53678. /**
  53679. * Ensures that the value is limited between zero and one
  53680. * @returns This path cursor
  53681. */
  53682. PathCursor.prototype.ensureLimits = function () {
  53683. while (this.value > 1) {
  53684. this.value -= 1;
  53685. }
  53686. while (this.value < 0) {
  53687. this.value += 1;
  53688. }
  53689. return this;
  53690. };
  53691. /**
  53692. * Runs onchange callbacks on change (used by the animation engine)
  53693. * @returns This path cursor
  53694. */
  53695. PathCursor.prototype.raiseOnChange = function () {
  53696. var _this = this;
  53697. this._onchange.forEach(function (f) { return f(_this); });
  53698. return this;
  53699. };
  53700. /**
  53701. * Executes a function on change
  53702. * @param f A path cursor onchange callback
  53703. * @returns This path cursor
  53704. */
  53705. PathCursor.prototype.onchange = function (f) {
  53706. this._onchange.push(f);
  53707. return this;
  53708. };
  53709. return PathCursor;
  53710. }());
  53711. BABYLON.PathCursor = PathCursor;
  53712. /**
  53713. * Enum for the animation key frame interpolation type
  53714. */
  53715. var AnimationKeyInterpolation;
  53716. (function (AnimationKeyInterpolation) {
  53717. /**
  53718. * Do not interpolate between keys and use the start key value only. Tangents are ignored
  53719. */
  53720. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  53721. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  53722. /**
  53723. * Class used to store any kind of animation
  53724. */
  53725. var Animation = /** @class */ (function () {
  53726. /**
  53727. * Initializes the animation
  53728. * @param name Name of the animation
  53729. * @param targetProperty Property to animate
  53730. * @param framePerSecond The frames per second of the animation
  53731. * @param dataType The data type of the animation
  53732. * @param loopMode The loop mode of the animation
  53733. * @param enableBlendings Specifies if blending should be enabled
  53734. */
  53735. function Animation(
  53736. /**Name of the animation */
  53737. name,
  53738. /**Property to animate */
  53739. targetProperty,
  53740. /**The frames per second of the animation */
  53741. framePerSecond,
  53742. /**The data type of the animation */
  53743. dataType,
  53744. /**The loop mode of the animation */
  53745. loopMode,
  53746. /**Specifies if blending should be enabled */
  53747. enableBlending) {
  53748. this.name = name;
  53749. this.targetProperty = targetProperty;
  53750. this.framePerSecond = framePerSecond;
  53751. this.dataType = dataType;
  53752. this.loopMode = loopMode;
  53753. this.enableBlending = enableBlending;
  53754. /**
  53755. * @hidden Internal use only
  53756. */
  53757. this._runtimeAnimations = new Array();
  53758. /**
  53759. * The set of event that will be linked to this animation
  53760. */
  53761. this._events = new Array();
  53762. /**
  53763. * Stores the blending speed of the animation
  53764. */
  53765. this.blendingSpeed = 0.01;
  53766. /**
  53767. * Stores the animation ranges for the animation
  53768. */
  53769. this._ranges = {};
  53770. this.targetPropertyPath = targetProperty.split(".");
  53771. this.dataType = dataType;
  53772. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  53773. }
  53774. /**
  53775. * @hidden Internal use
  53776. */
  53777. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  53778. var dataType = undefined;
  53779. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  53780. dataType = Animation.ANIMATIONTYPE_FLOAT;
  53781. }
  53782. else if (from instanceof BABYLON.Quaternion) {
  53783. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  53784. }
  53785. else if (from instanceof BABYLON.Vector3) {
  53786. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  53787. }
  53788. else if (from instanceof BABYLON.Vector2) {
  53789. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  53790. }
  53791. else if (from instanceof BABYLON.Color3) {
  53792. dataType = Animation.ANIMATIONTYPE_COLOR3;
  53793. }
  53794. else if (from instanceof BABYLON.Size) {
  53795. dataType = Animation.ANIMATIONTYPE_SIZE;
  53796. }
  53797. if (dataType == undefined) {
  53798. return null;
  53799. }
  53800. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  53801. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  53802. animation.setKeys(keys);
  53803. if (easingFunction !== undefined) {
  53804. animation.setEasingFunction(easingFunction);
  53805. }
  53806. return animation;
  53807. };
  53808. /**
  53809. * Sets up an animation
  53810. * @param property The property to animate
  53811. * @param animationType The animation type to apply
  53812. * @param framePerSecond The frames per second of the animation
  53813. * @param easingFunction The easing function used in the animation
  53814. * @returns The created animation
  53815. */
  53816. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  53817. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  53818. animation.setEasingFunction(easingFunction);
  53819. return animation;
  53820. };
  53821. /**
  53822. * Create and start an animation on a node
  53823. * @param name defines the name of the global animation that will be run on all nodes
  53824. * @param node defines the root node where the animation will take place
  53825. * @param targetProperty defines property to animate
  53826. * @param framePerSecond defines the number of frame per second yo use
  53827. * @param totalFrame defines the number of frames in total
  53828. * @param from defines the initial value
  53829. * @param to defines the final value
  53830. * @param loopMode defines which loop mode you want to use (off by default)
  53831. * @param easingFunction defines the easing function to use (linear by default)
  53832. * @param onAnimationEnd defines the callback to call when animation end
  53833. * @returns the animatable created for this animation
  53834. */
  53835. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  53836. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  53837. if (!animation) {
  53838. return null;
  53839. }
  53840. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  53841. };
  53842. /**
  53843. * Create and start an animation on a node and its descendants
  53844. * @param name defines the name of the global animation that will be run on all nodes
  53845. * @param node defines the root node where the animation will take place
  53846. * @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
  53847. * @param targetProperty defines property to animate
  53848. * @param framePerSecond defines the number of frame per second to use
  53849. * @param totalFrame defines the number of frames in total
  53850. * @param from defines the initial value
  53851. * @param to defines the final value
  53852. * @param loopMode defines which loop mode you want to use (off by default)
  53853. * @param easingFunction defines the easing function to use (linear by default)
  53854. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  53855. * @returns the list of animatables created for all nodes
  53856. * @example https://www.babylonjs-playground.com/#MH0VLI
  53857. */
  53858. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  53859. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  53860. if (!animation) {
  53861. return null;
  53862. }
  53863. var scene = node.getScene();
  53864. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  53865. };
  53866. /**
  53867. * Creates a new animation, merges it with the existing animations and starts it
  53868. * @param name Name of the animation
  53869. * @param node Node which contains the scene that begins the animations
  53870. * @param targetProperty Specifies which property to animate
  53871. * @param framePerSecond The frames per second of the animation
  53872. * @param totalFrame The total number of frames
  53873. * @param from The frame at the beginning of the animation
  53874. * @param to The frame at the end of the animation
  53875. * @param loopMode Specifies the loop mode of the animation
  53876. * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations
  53877. * @param onAnimationEnd Callback to run once the animation is complete
  53878. * @returns Nullable animation
  53879. */
  53880. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  53881. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  53882. if (!animation) {
  53883. return null;
  53884. }
  53885. node.animations.push(animation);
  53886. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  53887. };
  53888. /**
  53889. * Transition property of an host to the target Value
  53890. * @param property The property to transition
  53891. * @param targetValue The target Value of the property
  53892. * @param host The object where the property to animate belongs
  53893. * @param scene Scene used to run the animation
  53894. * @param frameRate Framerate (in frame/s) to use
  53895. * @param transition The transition type we want to use
  53896. * @param duration The duration of the animation, in milliseconds
  53897. * @param onAnimationEnd Callback trigger at the end of the animation
  53898. * @returns Nullable animation
  53899. */
  53900. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  53901. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  53902. if (duration <= 0) {
  53903. host[property] = targetValue;
  53904. if (onAnimationEnd) {
  53905. onAnimationEnd();
  53906. }
  53907. return null;
  53908. }
  53909. var endFrame = frameRate * (duration / 1000);
  53910. transition.setKeys([{
  53911. frame: 0,
  53912. value: host[property].clone ? host[property].clone() : host[property]
  53913. },
  53914. {
  53915. frame: endFrame,
  53916. value: targetValue
  53917. }]);
  53918. if (!host.animations) {
  53919. host.animations = [];
  53920. }
  53921. host.animations.push(transition);
  53922. var animation = scene.beginAnimation(host, 0, endFrame, false);
  53923. animation.onAnimationEnd = onAnimationEnd;
  53924. return animation;
  53925. };
  53926. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  53927. /**
  53928. * Return the array of runtime animations currently using this animation
  53929. */
  53930. get: function () {
  53931. return this._runtimeAnimations;
  53932. },
  53933. enumerable: true,
  53934. configurable: true
  53935. });
  53936. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  53937. /**
  53938. * Specifies if any of the runtime animations are currently running
  53939. */
  53940. get: function () {
  53941. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  53942. var runtimeAnimation = _a[_i];
  53943. if (!runtimeAnimation.isStopped) {
  53944. return true;
  53945. }
  53946. }
  53947. return false;
  53948. },
  53949. enumerable: true,
  53950. configurable: true
  53951. });
  53952. // Methods
  53953. /**
  53954. * Converts the animation to a string
  53955. * @param fullDetails support for multiple levels of logging within scene loading
  53956. * @returns String form of the animation
  53957. */
  53958. Animation.prototype.toString = function (fullDetails) {
  53959. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  53960. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  53961. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  53962. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  53963. if (fullDetails) {
  53964. ret += ", Ranges: {";
  53965. var first = true;
  53966. for (var name in this._ranges) {
  53967. if (first) {
  53968. ret += ", ";
  53969. first = false;
  53970. }
  53971. ret += name;
  53972. }
  53973. ret += "}";
  53974. }
  53975. return ret;
  53976. };
  53977. /**
  53978. * Add an event to this animation
  53979. * @param event Event to add
  53980. */
  53981. Animation.prototype.addEvent = function (event) {
  53982. this._events.push(event);
  53983. };
  53984. /**
  53985. * Remove all events found at the given frame
  53986. * @param frame The frame to remove events from
  53987. */
  53988. Animation.prototype.removeEvents = function (frame) {
  53989. for (var index = 0; index < this._events.length; index++) {
  53990. if (this._events[index].frame === frame) {
  53991. this._events.splice(index, 1);
  53992. index--;
  53993. }
  53994. }
  53995. };
  53996. /**
  53997. * Retrieves all the events from the animation
  53998. * @returns Events from the animation
  53999. */
  54000. Animation.prototype.getEvents = function () {
  54001. return this._events;
  54002. };
  54003. /**
  54004. * Creates an animation range
  54005. * @param name Name of the animation range
  54006. * @param from Starting frame of the animation range
  54007. * @param to Ending frame of the animation
  54008. */
  54009. Animation.prototype.createRange = function (name, from, to) {
  54010. // check name not already in use; could happen for bones after serialized
  54011. if (!this._ranges[name]) {
  54012. this._ranges[name] = new AnimationRange(name, from, to);
  54013. }
  54014. };
  54015. /**
  54016. * Deletes an animation range by name
  54017. * @param name Name of the animation range to delete
  54018. * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)
  54019. */
  54020. Animation.prototype.deleteRange = function (name, deleteFrames) {
  54021. if (deleteFrames === void 0) { deleteFrames = true; }
  54022. var range = this._ranges[name];
  54023. if (!range) {
  54024. return;
  54025. }
  54026. if (deleteFrames) {
  54027. var from = range.from;
  54028. var to = range.to;
  54029. // this loop MUST go high to low for multiple splices to work
  54030. for (var key = this._keys.length - 1; key >= 0; key--) {
  54031. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  54032. this._keys.splice(key, 1);
  54033. }
  54034. }
  54035. }
  54036. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  54037. };
  54038. /**
  54039. * Gets the animation range by name, or null if not defined
  54040. * @param name Name of the animation range
  54041. * @returns Nullable animation range
  54042. */
  54043. Animation.prototype.getRange = function (name) {
  54044. return this._ranges[name];
  54045. };
  54046. /**
  54047. * Gets the key frames from the animation
  54048. * @returns The key frames of the animation
  54049. */
  54050. Animation.prototype.getKeys = function () {
  54051. return this._keys;
  54052. };
  54053. /**
  54054. * Gets the highest frame rate of the animation
  54055. * @returns Highest frame rate of the animation
  54056. */
  54057. Animation.prototype.getHighestFrame = function () {
  54058. var ret = 0;
  54059. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  54060. if (ret < this._keys[key].frame) {
  54061. ret = this._keys[key].frame;
  54062. }
  54063. }
  54064. return ret;
  54065. };
  54066. /**
  54067. * Gets the easing function of the animation
  54068. * @returns Easing function of the animation
  54069. */
  54070. Animation.prototype.getEasingFunction = function () {
  54071. return this._easingFunction;
  54072. };
  54073. /**
  54074. * Sets the easing function of the animation
  54075. * @param easingFunction A custom mathematical formula for animation
  54076. */
  54077. Animation.prototype.setEasingFunction = function (easingFunction) {
  54078. this._easingFunction = easingFunction;
  54079. };
  54080. /**
  54081. * Interpolates a scalar linearly
  54082. * @param startValue Start value of the animation curve
  54083. * @param endValue End value of the animation curve
  54084. * @param gradient Scalar amount to interpolate
  54085. * @returns Interpolated scalar value
  54086. */
  54087. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  54088. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  54089. };
  54090. /**
  54091. * Interpolates a scalar cubically
  54092. * @param startValue Start value of the animation curve
  54093. * @param outTangent End tangent of the animation
  54094. * @param endValue End value of the animation curve
  54095. * @param inTangent Start tangent of the animation curve
  54096. * @param gradient Scalar amount to interpolate
  54097. * @returns Interpolated scalar value
  54098. */
  54099. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  54100. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  54101. };
  54102. /**
  54103. * Interpolates a quaternion using a spherical linear interpolation
  54104. * @param startValue Start value of the animation curve
  54105. * @param endValue End value of the animation curve
  54106. * @param gradient Scalar amount to interpolate
  54107. * @returns Interpolated quaternion value
  54108. */
  54109. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  54110. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  54111. };
  54112. /**
  54113. * Interpolates a quaternion cubically
  54114. * @param startValue Start value of the animation curve
  54115. * @param outTangent End tangent of the animation curve
  54116. * @param endValue End value of the animation curve
  54117. * @param inTangent Start tangent of the animation curve
  54118. * @param gradient Scalar amount to interpolate
  54119. * @returns Interpolated quaternion value
  54120. */
  54121. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  54122. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  54123. };
  54124. /**
  54125. * Interpolates a Vector3 linearl
  54126. * @param startValue Start value of the animation curve
  54127. * @param endValue End value of the animation curve
  54128. * @param gradient Scalar amount to interpolate
  54129. * @returns Interpolated scalar value
  54130. */
  54131. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  54132. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  54133. };
  54134. /**
  54135. * Interpolates a Vector3 cubically
  54136. * @param startValue Start value of the animation curve
  54137. * @param outTangent End tangent of the animation
  54138. * @param endValue End value of the animation curve
  54139. * @param inTangent Start tangent of the animation curve
  54140. * @param gradient Scalar amount to interpolate
  54141. * @returns InterpolatedVector3 value
  54142. */
  54143. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  54144. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  54145. };
  54146. /**
  54147. * Interpolates a Vector2 linearly
  54148. * @param startValue Start value of the animation curve
  54149. * @param endValue End value of the animation curve
  54150. * @param gradient Scalar amount to interpolate
  54151. * @returns Interpolated Vector2 value
  54152. */
  54153. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  54154. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  54155. };
  54156. /**
  54157. * Interpolates a Vector2 cubically
  54158. * @param startValue Start value of the animation curve
  54159. * @param outTangent End tangent of the animation
  54160. * @param endValue End value of the animation curve
  54161. * @param inTangent Start tangent of the animation curve
  54162. * @param gradient Scalar amount to interpolate
  54163. * @returns Interpolated Vector2 value
  54164. */
  54165. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  54166. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  54167. };
  54168. /**
  54169. * Interpolates a size linearly
  54170. * @param startValue Start value of the animation curve
  54171. * @param endValue End value of the animation curve
  54172. * @param gradient Scalar amount to interpolate
  54173. * @returns Interpolated Size value
  54174. */
  54175. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  54176. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  54177. };
  54178. /**
  54179. * Interpolates a Color3 linearly
  54180. * @param startValue Start value of the animation curve
  54181. * @param endValue End value of the animation curve
  54182. * @param gradient Scalar amount to interpolate
  54183. * @returns Interpolated Color3 value
  54184. */
  54185. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  54186. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  54187. };
  54188. /**
  54189. * @hidden Internal use only
  54190. */
  54191. Animation.prototype._getKeyValue = function (value) {
  54192. if (typeof value === "function") {
  54193. return value();
  54194. }
  54195. return value;
  54196. };
  54197. /**
  54198. * @hidden Internal use only
  54199. */
  54200. Animation.prototype._interpolate = function (currentFrame, repeatCount, workValue, loopMode, offsetValue, highLimitValue) {
  54201. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  54202. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  54203. }
  54204. var keys = this.getKeys();
  54205. // Try to get a hash to find the right key
  54206. 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));
  54207. if (keys[startKeyIndex].frame >= currentFrame) {
  54208. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  54209. startKeyIndex--;
  54210. }
  54211. }
  54212. for (var key = startKeyIndex; key < keys.length; key++) {
  54213. var endKey = keys[key + 1];
  54214. if (endKey.frame >= currentFrame) {
  54215. var startKey = keys[key];
  54216. var startValue = this._getKeyValue(startKey.value);
  54217. if (startKey.interpolation === AnimationKeyInterpolation.STEP) {
  54218. return startValue;
  54219. }
  54220. var endValue = this._getKeyValue(endKey.value);
  54221. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  54222. var frameDelta = endKey.frame - startKey.frame;
  54223. // gradient : percent of currentFrame between the frame inf and the frame sup
  54224. var gradient = (currentFrame - startKey.frame) / frameDelta;
  54225. // check for easingFunction and correction of gradient
  54226. var easingFunction = this.getEasingFunction();
  54227. if (easingFunction != null) {
  54228. gradient = easingFunction.ease(gradient);
  54229. }
  54230. switch (this.dataType) {
  54231. // Float
  54232. case Animation.ANIMATIONTYPE_FLOAT:
  54233. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  54234. switch (loopMode) {
  54235. case Animation.ANIMATIONLOOPMODE_CYCLE:
  54236. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  54237. return floatValue;
  54238. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  54239. return offsetValue * repeatCount + floatValue;
  54240. }
  54241. break;
  54242. // Quaternion
  54243. case Animation.ANIMATIONTYPE_QUATERNION:
  54244. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  54245. switch (loopMode) {
  54246. case Animation.ANIMATIONLOOPMODE_CYCLE:
  54247. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  54248. return quatValue;
  54249. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  54250. return quatValue.addInPlace(offsetValue.scale(repeatCount));
  54251. }
  54252. return quatValue;
  54253. // Vector3
  54254. case Animation.ANIMATIONTYPE_VECTOR3:
  54255. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  54256. switch (loopMode) {
  54257. case Animation.ANIMATIONLOOPMODE_CYCLE:
  54258. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  54259. return vec3Value;
  54260. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  54261. return vec3Value.add(offsetValue.scale(repeatCount));
  54262. }
  54263. // Vector2
  54264. case Animation.ANIMATIONTYPE_VECTOR2:
  54265. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  54266. switch (loopMode) {
  54267. case Animation.ANIMATIONLOOPMODE_CYCLE:
  54268. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  54269. return vec2Value;
  54270. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  54271. return vec2Value.add(offsetValue.scale(repeatCount));
  54272. }
  54273. // Size
  54274. case Animation.ANIMATIONTYPE_SIZE:
  54275. switch (loopMode) {
  54276. case Animation.ANIMATIONLOOPMODE_CYCLE:
  54277. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  54278. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  54279. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  54280. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  54281. }
  54282. // Color3
  54283. case Animation.ANIMATIONTYPE_COLOR3:
  54284. switch (loopMode) {
  54285. case Animation.ANIMATIONLOOPMODE_CYCLE:
  54286. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  54287. return this.color3InterpolateFunction(startValue, endValue, gradient);
  54288. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  54289. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  54290. }
  54291. // Matrix
  54292. case Animation.ANIMATIONTYPE_MATRIX:
  54293. switch (loopMode) {
  54294. case Animation.ANIMATIONLOOPMODE_CYCLE:
  54295. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  54296. if (Animation.AllowMatricesInterpolation) {
  54297. return this.matrixInterpolateFunction(startValue, endValue, gradient, workValue);
  54298. }
  54299. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  54300. return startValue;
  54301. }
  54302. default:
  54303. break;
  54304. }
  54305. break;
  54306. }
  54307. }
  54308. return this._getKeyValue(keys[keys.length - 1].value);
  54309. };
  54310. /**
  54311. * Defines the function to use to interpolate matrices
  54312. * @param startValue defines the start matrix
  54313. * @param endValue defines the end matrix
  54314. * @param gradient defines the gradient between both matrices
  54315. * @param result defines an optional target matrix where to store the interpolation
  54316. * @returns the interpolated matrix
  54317. */
  54318. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {
  54319. if (Animation.AllowMatrixDecomposeForInterpolation) {
  54320. if (result) {
  54321. BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  54322. return result;
  54323. }
  54324. return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
  54325. }
  54326. if (result) {
  54327. BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);
  54328. return result;
  54329. }
  54330. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  54331. };
  54332. /**
  54333. * Makes a copy of the animation
  54334. * @returns Cloned animation
  54335. */
  54336. Animation.prototype.clone = function () {
  54337. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  54338. clone.enableBlending = this.enableBlending;
  54339. clone.blendingSpeed = this.blendingSpeed;
  54340. if (this._keys) {
  54341. clone.setKeys(this._keys);
  54342. }
  54343. if (this._ranges) {
  54344. clone._ranges = {};
  54345. for (var name in this._ranges) {
  54346. var range = this._ranges[name];
  54347. if (!range) {
  54348. continue;
  54349. }
  54350. clone._ranges[name] = range.clone();
  54351. }
  54352. }
  54353. return clone;
  54354. };
  54355. /**
  54356. * Sets the key frames of the animation
  54357. * @param values The animation key frames to set
  54358. */
  54359. Animation.prototype.setKeys = function (values) {
  54360. this._keys = values.slice(0);
  54361. };
  54362. /**
  54363. * Serializes the animation to an object
  54364. * @returns Serialized object
  54365. */
  54366. Animation.prototype.serialize = function () {
  54367. var serializationObject = {};
  54368. serializationObject.name = this.name;
  54369. serializationObject.property = this.targetProperty;
  54370. serializationObject.framePerSecond = this.framePerSecond;
  54371. serializationObject.dataType = this.dataType;
  54372. serializationObject.loopBehavior = this.loopMode;
  54373. serializationObject.enableBlending = this.enableBlending;
  54374. serializationObject.blendingSpeed = this.blendingSpeed;
  54375. var dataType = this.dataType;
  54376. serializationObject.keys = [];
  54377. var keys = this.getKeys();
  54378. for (var index = 0; index < keys.length; index++) {
  54379. var animationKey = keys[index];
  54380. var key = {};
  54381. key.frame = animationKey.frame;
  54382. switch (dataType) {
  54383. case Animation.ANIMATIONTYPE_FLOAT:
  54384. key.values = [animationKey.value];
  54385. break;
  54386. case Animation.ANIMATIONTYPE_QUATERNION:
  54387. case Animation.ANIMATIONTYPE_MATRIX:
  54388. case Animation.ANIMATIONTYPE_VECTOR3:
  54389. case Animation.ANIMATIONTYPE_COLOR3:
  54390. key.values = animationKey.value.asArray();
  54391. break;
  54392. }
  54393. serializationObject.keys.push(key);
  54394. }
  54395. serializationObject.ranges = [];
  54396. for (var name in this._ranges) {
  54397. var source = this._ranges[name];
  54398. if (!source) {
  54399. continue;
  54400. }
  54401. var range = {};
  54402. range.name = name;
  54403. range.from = source.from;
  54404. range.to = source.to;
  54405. serializationObject.ranges.push(range);
  54406. }
  54407. return serializationObject;
  54408. };
  54409. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  54410. /**
  54411. * Get the float animation type
  54412. */
  54413. get: function () {
  54414. return Animation._ANIMATIONTYPE_FLOAT;
  54415. },
  54416. enumerable: true,
  54417. configurable: true
  54418. });
  54419. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  54420. /**
  54421. * Get the Vector3 animation type
  54422. */
  54423. get: function () {
  54424. return Animation._ANIMATIONTYPE_VECTOR3;
  54425. },
  54426. enumerable: true,
  54427. configurable: true
  54428. });
  54429. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  54430. /**
  54431. * Get the Vector2 animation type
  54432. */
  54433. get: function () {
  54434. return Animation._ANIMATIONTYPE_VECTOR2;
  54435. },
  54436. enumerable: true,
  54437. configurable: true
  54438. });
  54439. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  54440. /**
  54441. * Get the Size animation type
  54442. */
  54443. get: function () {
  54444. return Animation._ANIMATIONTYPE_SIZE;
  54445. },
  54446. enumerable: true,
  54447. configurable: true
  54448. });
  54449. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  54450. /**
  54451. * Get the Quaternion animation type
  54452. */
  54453. get: function () {
  54454. return Animation._ANIMATIONTYPE_QUATERNION;
  54455. },
  54456. enumerable: true,
  54457. configurable: true
  54458. });
  54459. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  54460. /**
  54461. * Get the Matrix animation type
  54462. */
  54463. get: function () {
  54464. return Animation._ANIMATIONTYPE_MATRIX;
  54465. },
  54466. enumerable: true,
  54467. configurable: true
  54468. });
  54469. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  54470. /**
  54471. * Get the Color3 animation type
  54472. */
  54473. get: function () {
  54474. return Animation._ANIMATIONTYPE_COLOR3;
  54475. },
  54476. enumerable: true,
  54477. configurable: true
  54478. });
  54479. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  54480. /**
  54481. * Get the Relative Loop Mode
  54482. */
  54483. get: function () {
  54484. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  54485. },
  54486. enumerable: true,
  54487. configurable: true
  54488. });
  54489. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  54490. /**
  54491. * Get the Cycle Loop Mode
  54492. */
  54493. get: function () {
  54494. return Animation._ANIMATIONLOOPMODE_CYCLE;
  54495. },
  54496. enumerable: true,
  54497. configurable: true
  54498. });
  54499. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  54500. /**
  54501. * Get the Constant Loop Mode
  54502. */
  54503. get: function () {
  54504. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  54505. },
  54506. enumerable: true,
  54507. configurable: true
  54508. });
  54509. /** @hidden */
  54510. Animation._UniversalLerp = function (left, right, amount) {
  54511. var constructor = left.constructor;
  54512. if (constructor.Lerp) { // Lerp supported
  54513. return constructor.Lerp(left, right, amount);
  54514. }
  54515. else if (constructor.Slerp) { // Slerp supported
  54516. return constructor.Slerp(left, right, amount);
  54517. }
  54518. else if (left.toFixed) { // Number
  54519. return left * (1.0 - amount) + amount * right;
  54520. }
  54521. else { // Blending not supported
  54522. return right;
  54523. }
  54524. };
  54525. /**
  54526. * Parses an animation object and creates an animation
  54527. * @param parsedAnimation Parsed animation object
  54528. * @returns Animation object
  54529. */
  54530. Animation.Parse = function (parsedAnimation) {
  54531. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  54532. var dataType = parsedAnimation.dataType;
  54533. var keys = [];
  54534. var data;
  54535. var index;
  54536. if (parsedAnimation.enableBlending) {
  54537. animation.enableBlending = parsedAnimation.enableBlending;
  54538. }
  54539. if (parsedAnimation.blendingSpeed) {
  54540. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  54541. }
  54542. for (index = 0; index < parsedAnimation.keys.length; index++) {
  54543. var key = parsedAnimation.keys[index];
  54544. var inTangent;
  54545. var outTangent;
  54546. switch (dataType) {
  54547. case Animation.ANIMATIONTYPE_FLOAT:
  54548. data = key.values[0];
  54549. if (key.values.length >= 1) {
  54550. inTangent = key.values[1];
  54551. }
  54552. if (key.values.length >= 2) {
  54553. outTangent = key.values[2];
  54554. }
  54555. break;
  54556. case Animation.ANIMATIONTYPE_QUATERNION:
  54557. data = BABYLON.Quaternion.FromArray(key.values);
  54558. if (key.values.length >= 8) {
  54559. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  54560. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  54561. inTangent = _inTangent;
  54562. }
  54563. }
  54564. if (key.values.length >= 12) {
  54565. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  54566. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  54567. outTangent = _outTangent;
  54568. }
  54569. }
  54570. break;
  54571. case Animation.ANIMATIONTYPE_MATRIX:
  54572. data = BABYLON.Matrix.FromArray(key.values);
  54573. break;
  54574. case Animation.ANIMATIONTYPE_COLOR3:
  54575. data = BABYLON.Color3.FromArray(key.values);
  54576. break;
  54577. case Animation.ANIMATIONTYPE_VECTOR3:
  54578. default:
  54579. data = BABYLON.Vector3.FromArray(key.values);
  54580. break;
  54581. }
  54582. var keyData = {};
  54583. keyData.frame = key.frame;
  54584. keyData.value = data;
  54585. if (inTangent != undefined) {
  54586. keyData.inTangent = inTangent;
  54587. }
  54588. if (outTangent != undefined) {
  54589. keyData.outTangent = outTangent;
  54590. }
  54591. keys.push(keyData);
  54592. }
  54593. animation.setKeys(keys);
  54594. if (parsedAnimation.ranges) {
  54595. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  54596. data = parsedAnimation.ranges[index];
  54597. animation.createRange(data.name, data.from, data.to);
  54598. }
  54599. }
  54600. return animation;
  54601. };
  54602. /**
  54603. * Appends the serialized animations from the source animations
  54604. * @param source Source containing the animations
  54605. * @param destination Target to store the animations
  54606. */
  54607. Animation.AppendSerializedAnimations = function (source, destination) {
  54608. if (source.animations) {
  54609. destination.animations = [];
  54610. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  54611. var animation = source.animations[animationIndex];
  54612. destination.animations.push(animation.serialize());
  54613. }
  54614. }
  54615. };
  54616. /**
  54617. * Use matrix interpolation instead of using direct key value when animating matrices
  54618. */
  54619. Animation.AllowMatricesInterpolation = false;
  54620. /**
  54621. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  54622. */
  54623. Animation.AllowMatrixDecomposeForInterpolation = true;
  54624. // Statics
  54625. /**
  54626. * Float animation type
  54627. */
  54628. Animation._ANIMATIONTYPE_FLOAT = 0;
  54629. /**
  54630. * Vector3 animation type
  54631. */
  54632. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  54633. /**
  54634. * Quaternion animation type
  54635. */
  54636. Animation._ANIMATIONTYPE_QUATERNION = 2;
  54637. /**
  54638. * Matrix animation type
  54639. */
  54640. Animation._ANIMATIONTYPE_MATRIX = 3;
  54641. /**
  54642. * Color3 animation type
  54643. */
  54644. Animation._ANIMATIONTYPE_COLOR3 = 4;
  54645. /**
  54646. * Vector2 animation type
  54647. */
  54648. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  54649. /**
  54650. * Size animation type
  54651. */
  54652. Animation._ANIMATIONTYPE_SIZE = 6;
  54653. /**
  54654. * Relative Loop Mode
  54655. */
  54656. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  54657. /**
  54658. * Cycle Loop Mode
  54659. */
  54660. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  54661. /**
  54662. * Constant Loop Mode
  54663. */
  54664. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  54665. return Animation;
  54666. }());
  54667. BABYLON.Animation = Animation;
  54668. })(BABYLON || (BABYLON = {}));
  54669. //# sourceMappingURL=babylon.animation.js.map
  54670. var BABYLON;
  54671. (function (BABYLON) {
  54672. /**
  54673. * This class defines the direct association between an animation and a target
  54674. */
  54675. var TargetedAnimation = /** @class */ (function () {
  54676. function TargetedAnimation() {
  54677. }
  54678. return TargetedAnimation;
  54679. }());
  54680. BABYLON.TargetedAnimation = TargetedAnimation;
  54681. /**
  54682. * Use this class to create coordinated animations on multiple targets
  54683. */
  54684. var AnimationGroup = /** @class */ (function () {
  54685. /**
  54686. * Instantiates a new Animation Group.
  54687. * This helps managing several animations at once.
  54688. * @see http://doc.babylonjs.com/how_to/group
  54689. * @param name Defines the name of the group
  54690. * @param scene Defines the scene the group belongs to
  54691. */
  54692. function AnimationGroup(
  54693. /** The name of the animation group */
  54694. name, scene) {
  54695. if (scene === void 0) { scene = null; }
  54696. this.name = name;
  54697. this._targetedAnimations = new Array();
  54698. this._animatables = new Array();
  54699. this._from = Number.MAX_VALUE;
  54700. this._to = -Number.MAX_VALUE;
  54701. this._speedRatio = 1;
  54702. /**
  54703. * This observable will notify when one animation have ended.
  54704. */
  54705. this.onAnimationEndObservable = new BABYLON.Observable();
  54706. /**
  54707. * This observable will notify when all animations have ended.
  54708. */
  54709. this.onAnimationGroupEndObservable = new BABYLON.Observable();
  54710. /**
  54711. * This observable will notify when all animations have paused.
  54712. */
  54713. this.onAnimationGroupPauseObservable = new BABYLON.Observable();
  54714. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  54715. this._scene.animationGroups.push(this);
  54716. }
  54717. Object.defineProperty(AnimationGroup.prototype, "from", {
  54718. /**
  54719. * Gets the first frame
  54720. */
  54721. get: function () {
  54722. return this._from;
  54723. },
  54724. enumerable: true,
  54725. configurable: true
  54726. });
  54727. Object.defineProperty(AnimationGroup.prototype, "to", {
  54728. /**
  54729. * Gets the last frame
  54730. */
  54731. get: function () {
  54732. return this._to;
  54733. },
  54734. enumerable: true,
  54735. configurable: true
  54736. });
  54737. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  54738. /**
  54739. * Define if the animations are started
  54740. */
  54741. get: function () {
  54742. return this._isStarted;
  54743. },
  54744. enumerable: true,
  54745. configurable: true
  54746. });
  54747. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  54748. /**
  54749. * Gets or sets the speed ratio to use for all animations
  54750. */
  54751. get: function () {
  54752. return this._speedRatio;
  54753. },
  54754. /**
  54755. * Gets or sets the speed ratio to use for all animations
  54756. */
  54757. set: function (value) {
  54758. if (this._speedRatio === value) {
  54759. return;
  54760. }
  54761. this._speedRatio = value;
  54762. for (var index = 0; index < this._animatables.length; index++) {
  54763. var animatable = this._animatables[index];
  54764. animatable.speedRatio = this._speedRatio;
  54765. }
  54766. },
  54767. enumerable: true,
  54768. configurable: true
  54769. });
  54770. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  54771. /**
  54772. * Gets the targeted animations for this animation group
  54773. */
  54774. get: function () {
  54775. return this._targetedAnimations;
  54776. },
  54777. enumerable: true,
  54778. configurable: true
  54779. });
  54780. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  54781. /**
  54782. * returning the list of animatables controlled by this animation group.
  54783. */
  54784. get: function () {
  54785. return this._animatables;
  54786. },
  54787. enumerable: true,
  54788. configurable: true
  54789. });
  54790. /**
  54791. * Add an animation (with its target) in the group
  54792. * @param animation defines the animation we want to add
  54793. * @param target defines the target of the animation
  54794. * @returns the TargetedAnimation object
  54795. */
  54796. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  54797. var targetedAnimation = {
  54798. animation: animation,
  54799. target: target
  54800. };
  54801. var keys = animation.getKeys();
  54802. if (this._from > keys[0].frame) {
  54803. this._from = keys[0].frame;
  54804. }
  54805. if (this._to < keys[keys.length - 1].frame) {
  54806. this._to = keys[keys.length - 1].frame;
  54807. }
  54808. this._targetedAnimations.push(targetedAnimation);
  54809. return targetedAnimation;
  54810. };
  54811. /**
  54812. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  54813. * It can add constant keys at begin or end
  54814. * @param beginFrame defines the new begin frame for all animations or the smallest begin frame of all animations if null (defaults to null)
  54815. * @param endFrame defines the new end frame for all animations or the largest end frame of all animations if null (defaults to null)
  54816. * @returns the animation group
  54817. */
  54818. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  54819. if (beginFrame === void 0) { beginFrame = null; }
  54820. if (endFrame === void 0) { endFrame = null; }
  54821. if (beginFrame == null) {
  54822. beginFrame = this._from;
  54823. }
  54824. if (endFrame == null) {
  54825. endFrame = this._to;
  54826. }
  54827. for (var index = 0; index < this._targetedAnimations.length; index++) {
  54828. var targetedAnimation = this._targetedAnimations[index];
  54829. var keys = targetedAnimation.animation.getKeys();
  54830. var startKey = keys[0];
  54831. var endKey = keys[keys.length - 1];
  54832. if (startKey.frame > beginFrame) {
  54833. var newKey = {
  54834. frame: beginFrame,
  54835. value: startKey.value,
  54836. inTangent: startKey.inTangent,
  54837. outTangent: startKey.outTangent,
  54838. interpolation: startKey.interpolation
  54839. };
  54840. keys.splice(0, 0, newKey);
  54841. }
  54842. if (endKey.frame < endFrame) {
  54843. var newKey = {
  54844. frame: endFrame,
  54845. value: endKey.value,
  54846. inTangent: endKey.outTangent,
  54847. outTangent: endKey.outTangent,
  54848. interpolation: endKey.interpolation
  54849. };
  54850. keys.push(newKey);
  54851. }
  54852. }
  54853. this._from = beginFrame;
  54854. this._to = endFrame;
  54855. return this;
  54856. };
  54857. /**
  54858. * Start all animations on given targets
  54859. * @param loop defines if animations must loop
  54860. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  54861. * @param from defines the from key (optional)
  54862. * @param to defines the to key (optional)
  54863. * @returns the current animation group
  54864. */
  54865. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  54866. var _this = this;
  54867. if (loop === void 0) { loop = false; }
  54868. if (speedRatio === void 0) { speedRatio = 1; }
  54869. if (this._isStarted || this._targetedAnimations.length === 0) {
  54870. return this;
  54871. }
  54872. var _loop_1 = function (targetedAnimation) {
  54873. var animatable = this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this_1._from, to !== undefined ? to : this_1._to, loop, speedRatio);
  54874. animatable.onAnimationEnd = function () {
  54875. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  54876. _this._checkAnimationGroupEnded(animatable);
  54877. };
  54878. this_1._animatables.push(animatable);
  54879. };
  54880. var this_1 = this;
  54881. for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) {
  54882. var targetedAnimation = _a[_i];
  54883. _loop_1(targetedAnimation);
  54884. }
  54885. this._speedRatio = speedRatio;
  54886. if (from !== undefined && to !== undefined && from > to && this._speedRatio > 0) {
  54887. this._speedRatio = -speedRatio;
  54888. }
  54889. this._isStarted = true;
  54890. return this;
  54891. };
  54892. /**
  54893. * Pause all animations
  54894. * @returns the animation group
  54895. */
  54896. AnimationGroup.prototype.pause = function () {
  54897. if (!this._isStarted) {
  54898. return this;
  54899. }
  54900. for (var index = 0; index < this._animatables.length; index++) {
  54901. var animatable = this._animatables[index];
  54902. animatable.pause();
  54903. }
  54904. this.onAnimationGroupPauseObservable.notifyObservers(this);
  54905. return this;
  54906. };
  54907. /**
  54908. * Play all animations to initial state
  54909. * This function will start() the animations if they were not started or will restart() them if they were paused
  54910. * @param loop defines if animations must loop
  54911. * @returns the animation group
  54912. */
  54913. AnimationGroup.prototype.play = function (loop) {
  54914. // only if all animatables are ready and exist
  54915. if (this.isStarted && this._animatables.length === this._targetedAnimations.length) {
  54916. if (loop !== undefined) {
  54917. for (var index = 0; index < this._animatables.length; index++) {
  54918. var animatable = this._animatables[index];
  54919. animatable.loopAnimation = loop;
  54920. }
  54921. }
  54922. this.restart();
  54923. }
  54924. else {
  54925. this.stop();
  54926. this.start(loop, this._speedRatio);
  54927. }
  54928. return this;
  54929. };
  54930. /**
  54931. * Reset all animations to initial state
  54932. * @returns the animation group
  54933. */
  54934. AnimationGroup.prototype.reset = function () {
  54935. if (!this._isStarted) {
  54936. return this;
  54937. }
  54938. for (var index = 0; index < this._animatables.length; index++) {
  54939. var animatable = this._animatables[index];
  54940. animatable.reset();
  54941. }
  54942. return this;
  54943. };
  54944. /**
  54945. * Restart animations from key 0
  54946. * @returns the animation group
  54947. */
  54948. AnimationGroup.prototype.restart = function () {
  54949. if (!this._isStarted) {
  54950. return this;
  54951. }
  54952. for (var index = 0; index < this._animatables.length; index++) {
  54953. var animatable = this._animatables[index];
  54954. animatable.restart();
  54955. }
  54956. return this;
  54957. };
  54958. /**
  54959. * Stop all animations
  54960. * @returns the animation group
  54961. */
  54962. AnimationGroup.prototype.stop = function () {
  54963. if (!this._isStarted) {
  54964. return this;
  54965. }
  54966. var list = this._animatables.slice();
  54967. for (var index = 0; index < list.length; index++) {
  54968. list[index].stop();
  54969. }
  54970. this._isStarted = false;
  54971. return this;
  54972. };
  54973. /**
  54974. * Set animation weight for all animatables
  54975. * @param weight defines the weight to use
  54976. * @return the animationGroup
  54977. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  54978. */
  54979. AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) {
  54980. for (var index = 0; index < this._animatables.length; index++) {
  54981. var animatable = this._animatables[index];
  54982. animatable.weight = weight;
  54983. }
  54984. return this;
  54985. };
  54986. /**
  54987. * Synchronize and normalize all animatables with a source animatable
  54988. * @param root defines the root animatable to synchronize with
  54989. * @return the animationGroup
  54990. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  54991. */
  54992. AnimationGroup.prototype.syncAllAnimationsWith = function (root) {
  54993. for (var index = 0; index < this._animatables.length; index++) {
  54994. var animatable = this._animatables[index];
  54995. animatable.syncWith(root);
  54996. }
  54997. return this;
  54998. };
  54999. /**
  55000. * Goes to a specific frame in this animation group
  55001. * @param frame the frame number to go to
  55002. * @return the animationGroup
  55003. */
  55004. AnimationGroup.prototype.goToFrame = function (frame) {
  55005. if (!this._isStarted) {
  55006. return this;
  55007. }
  55008. for (var index = 0; index < this._animatables.length; index++) {
  55009. var animatable = this._animatables[index];
  55010. animatable.goToFrame(frame);
  55011. }
  55012. return this;
  55013. };
  55014. /**
  55015. * Dispose all associated resources
  55016. */
  55017. AnimationGroup.prototype.dispose = function () {
  55018. this._targetedAnimations = [];
  55019. this._animatables = [];
  55020. var index = this._scene.animationGroups.indexOf(this);
  55021. if (index > -1) {
  55022. this._scene.animationGroups.splice(index, 1);
  55023. }
  55024. };
  55025. AnimationGroup.prototype._checkAnimationGroupEnded = function (animatable) {
  55026. // animatable should be taken out of the array
  55027. var idx = this._animatables.indexOf(animatable);
  55028. if (idx > -1) {
  55029. this._animatables.splice(idx, 1);
  55030. }
  55031. // all animatables were removed? animation group ended!
  55032. if (this._animatables.length === 0) {
  55033. this._isStarted = false;
  55034. this.onAnimationGroupEndObservable.notifyObservers(this);
  55035. }
  55036. };
  55037. // Statics
  55038. /**
  55039. * Returns a new AnimationGroup object parsed from the source provided.
  55040. * @param parsedAnimationGroup defines the source
  55041. * @param scene defines the scene that will receive the animationGroup
  55042. * @returns a new AnimationGroup
  55043. */
  55044. AnimationGroup.Parse = function (parsedAnimationGroup, scene) {
  55045. var animationGroup = new BABYLON.AnimationGroup(parsedAnimationGroup.name, scene);
  55046. for (var i = 0; i < parsedAnimationGroup.targetedAnimations.length; i++) {
  55047. var targetedAnimation = parsedAnimationGroup.targetedAnimations[i];
  55048. var animation = BABYLON.Animation.Parse(targetedAnimation.animation);
  55049. var id = targetedAnimation.targetId;
  55050. if (targetedAnimation.animation.property === "influence") { // morph target animation
  55051. var morphTarget = scene.getMorphTargetById(id);
  55052. if (morphTarget) {
  55053. animationGroup.addTargetedAnimation(animation, morphTarget);
  55054. }
  55055. }
  55056. else {
  55057. var targetNode = scene.getNodeByID(id);
  55058. if (targetNode != null) {
  55059. animationGroup.addTargetedAnimation(animation, targetNode);
  55060. }
  55061. }
  55062. }
  55063. if (parsedAnimationGroup.from !== null && parsedAnimationGroup.from !== null) {
  55064. animationGroup.normalize(parsedAnimationGroup.from, parsedAnimationGroup.to);
  55065. }
  55066. return animationGroup;
  55067. };
  55068. /**
  55069. * Returns the string "AnimationGroup"
  55070. * @returns "AnimationGroup"
  55071. */
  55072. AnimationGroup.prototype.getClassName = function () {
  55073. return "AnimationGroup";
  55074. };
  55075. /**
  55076. * Creates a detailled string about the object
  55077. * @param fullDetails defines if the output string will support multiple levels of logging within scene loading
  55078. * @returns a string representing the object
  55079. */
  55080. AnimationGroup.prototype.toString = function (fullDetails) {
  55081. var ret = "Name: " + this.name;
  55082. ret += ", type: " + this.getClassName();
  55083. if (fullDetails) {
  55084. ret += ", from: " + this._from;
  55085. ret += ", to: " + this._to;
  55086. ret += ", isStarted: " + this._isStarted;
  55087. ret += ", speedRatio: " + this._speedRatio;
  55088. ret += ", targetedAnimations length: " + this._targetedAnimations.length;
  55089. ret += ", animatables length: " + this._animatables;
  55090. }
  55091. return ret;
  55092. };
  55093. return AnimationGroup;
  55094. }());
  55095. BABYLON.AnimationGroup = AnimationGroup;
  55096. })(BABYLON || (BABYLON = {}));
  55097. //# sourceMappingURL=babylon.animationGroup.js.map
  55098. var BABYLON;
  55099. (function (BABYLON) {
  55100. // Static values to help the garbage collector
  55101. // Quaternion
  55102. var _staticOffsetValueQuaternion = Object.freeze(new BABYLON.Quaternion(0, 0, 0, 0));
  55103. // Vector3
  55104. var _staticOffsetValueVector3 = Object.freeze(BABYLON.Vector3.Zero());
  55105. // Vector2
  55106. var _staticOffsetValueVector2 = Object.freeze(BABYLON.Vector2.Zero());
  55107. // Size
  55108. var _staticOffsetValueSize = Object.freeze(BABYLON.Size.Zero());
  55109. // Color3
  55110. var _staticOffsetValueColor3 = Object.freeze(BABYLON.Color3.Black());
  55111. /**
  55112. * Defines a runtime animation
  55113. */
  55114. var RuntimeAnimation = /** @class */ (function () {
  55115. /**
  55116. * Create a new RuntimeAnimation object
  55117. * @param target defines the target of the animation
  55118. * @param animation defines the source animation object
  55119. * @param scene defines the hosting scene
  55120. * @param host defines the initiating Animatable
  55121. */
  55122. function RuntimeAnimation(target, animation, scene, host) {
  55123. var _this = this;
  55124. this._events = new Array();
  55125. /**
  55126. * The current frame of the runtime animation
  55127. */
  55128. this._currentFrame = 0;
  55129. /**
  55130. * The original value of the runtime animation
  55131. */
  55132. this._originalValue = new Array();
  55133. /**
  55134. * The offsets cache of the runtime animation
  55135. */
  55136. this._offsetsCache = {};
  55137. /**
  55138. * The high limits cache of the runtime animation
  55139. */
  55140. this._highLimitsCache = {};
  55141. /**
  55142. * Specifies if the runtime animation has been stopped
  55143. */
  55144. this._stopped = false;
  55145. /**
  55146. * The blending factor of the runtime animation
  55147. */
  55148. this._blendingFactor = 0;
  55149. /**
  55150. * The target path of the runtime animation
  55151. */
  55152. this._targetPath = "";
  55153. /**
  55154. * The weight of the runtime animation
  55155. */
  55156. this._weight = 1.0;
  55157. /**
  55158. * The ratio offset of the runtime animation
  55159. */
  55160. this._ratioOffset = 0;
  55161. /**
  55162. * The previous delay of the runtime animation
  55163. */
  55164. this._previousDelay = 0;
  55165. /**
  55166. * The previous ratio of the runtime animation
  55167. */
  55168. this._previousRatio = 0;
  55169. this._animation = animation;
  55170. this._target = target;
  55171. this._scene = scene;
  55172. this._host = host;
  55173. animation._runtimeAnimations.push(this);
  55174. // Cloning events locally
  55175. var events = animation.getEvents();
  55176. if (events && events.length > 0) {
  55177. events.forEach(function (e) {
  55178. _this._events.push(e._clone());
  55179. });
  55180. }
  55181. }
  55182. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  55183. /**
  55184. * Gets the current frame of the runtime animation
  55185. */
  55186. get: function () {
  55187. return this._currentFrame;
  55188. },
  55189. enumerable: true,
  55190. configurable: true
  55191. });
  55192. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  55193. /**
  55194. * Gets the weight of the runtime animation
  55195. */
  55196. get: function () {
  55197. return this._weight;
  55198. },
  55199. enumerable: true,
  55200. configurable: true
  55201. });
  55202. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  55203. /**
  55204. * Gets the current value of the runtime animation
  55205. */
  55206. get: function () {
  55207. return this._currentValue;
  55208. },
  55209. enumerable: true,
  55210. configurable: true
  55211. });
  55212. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  55213. /**
  55214. * Gets the target path of the runtime animation
  55215. */
  55216. get: function () {
  55217. return this._targetPath;
  55218. },
  55219. enumerable: true,
  55220. configurable: true
  55221. });
  55222. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  55223. /**
  55224. * Gets the actual target of the runtime animation
  55225. */
  55226. get: function () {
  55227. return this._activeTarget;
  55228. },
  55229. enumerable: true,
  55230. configurable: true
  55231. });
  55232. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  55233. /**
  55234. * Gets the animation from the runtime animation
  55235. */
  55236. get: function () {
  55237. return this._animation;
  55238. },
  55239. enumerable: true,
  55240. configurable: true
  55241. });
  55242. /**
  55243. * Resets the runtime animation to the beginning
  55244. * @param restoreOriginal defines whether to restore the target property to the original value
  55245. */
  55246. RuntimeAnimation.prototype.reset = function (restoreOriginal) {
  55247. if (restoreOriginal === void 0) { restoreOriginal = false; }
  55248. if (restoreOriginal) {
  55249. if (this._target instanceof Array) {
  55250. var index = 0;
  55251. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  55252. var target = _a[_i];
  55253. if (this._originalValue[index] !== undefined) {
  55254. this._setValue(target, this._originalValue[index], -1);
  55255. }
  55256. index++;
  55257. }
  55258. }
  55259. else {
  55260. if (this._originalValue[0] !== undefined) {
  55261. this._setValue(this._target, this._originalValue[0], -1);
  55262. }
  55263. }
  55264. }
  55265. this._offsetsCache = {};
  55266. this._highLimitsCache = {};
  55267. this._currentFrame = 0;
  55268. this._blendingFactor = 0;
  55269. this._originalValue = new Array();
  55270. // Events
  55271. for (var index = 0; index < this._events.length; index++) {
  55272. this._events[index].isDone = false;
  55273. }
  55274. };
  55275. /**
  55276. * Specifies if the runtime animation is stopped
  55277. * @returns Boolean specifying if the runtime animation is stopped
  55278. */
  55279. RuntimeAnimation.prototype.isStopped = function () {
  55280. return this._stopped;
  55281. };
  55282. /**
  55283. * Disposes of the runtime animation
  55284. */
  55285. RuntimeAnimation.prototype.dispose = function () {
  55286. var index = this._animation.runtimeAnimations.indexOf(this);
  55287. if (index > -1) {
  55288. this._animation.runtimeAnimations.splice(index, 1);
  55289. }
  55290. };
  55291. /**
  55292. * Interpolates the animation from the current frame
  55293. * @param currentFrame The frame to interpolate the animation to
  55294. * @param repeatCount The number of times that the animation should loop
  55295. * @param loopMode The type of looping mode to use
  55296. * @param offsetValue Animation offset value
  55297. * @param highLimitValue The high limit value
  55298. * @returns The interpolated value
  55299. */
  55300. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  55301. this._currentFrame = currentFrame;
  55302. if (this._animation.dataType === BABYLON.Animation.ANIMATIONTYPE_MATRIX && !this._workValue) {
  55303. this._workValue = BABYLON.Matrix.Zero();
  55304. }
  55305. return this._animation._interpolate(currentFrame, repeatCount, this._workValue, loopMode, offsetValue, highLimitValue);
  55306. };
  55307. /**
  55308. * Apply the interpolated value to the target
  55309. * @param currentValue defines the value computed by the animation
  55310. * @param weight defines the weight to apply to this value (Defaults to 1.0)
  55311. */
  55312. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  55313. if (weight === void 0) { weight = 1.0; }
  55314. if (this._target instanceof Array) {
  55315. var index = 0;
  55316. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  55317. var target = _a[_i];
  55318. this._setValue(target, currentValue, weight, index);
  55319. index++;
  55320. }
  55321. }
  55322. else {
  55323. this._setValue(this._target, currentValue, weight);
  55324. }
  55325. };
  55326. RuntimeAnimation.prototype._setValue = function (target, currentValue, weight, targetIndex) {
  55327. if (targetIndex === void 0) { targetIndex = 0; }
  55328. // Set value
  55329. var path;
  55330. var destination;
  55331. var targetPropertyPath = this._animation.targetPropertyPath;
  55332. if (targetPropertyPath.length > 1) {
  55333. var property = target[targetPropertyPath[0]];
  55334. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  55335. property = property[targetPropertyPath[index]];
  55336. }
  55337. path = targetPropertyPath[targetPropertyPath.length - 1];
  55338. destination = property;
  55339. }
  55340. else {
  55341. path = targetPropertyPath[0];
  55342. destination = target;
  55343. }
  55344. this._targetPath = path;
  55345. this._activeTarget = destination;
  55346. this._weight = weight;
  55347. if (this._originalValue[targetIndex] === undefined) {
  55348. var originalValue = void 0;
  55349. if (destination.getRestPose && path === "_matrix") { // For bones
  55350. originalValue = destination.getRestPose();
  55351. }
  55352. else {
  55353. originalValue = destination[path];
  55354. }
  55355. if (originalValue && originalValue.clone) {
  55356. this._originalValue[targetIndex] = originalValue.clone();
  55357. }
  55358. else {
  55359. this._originalValue[targetIndex] = originalValue;
  55360. }
  55361. }
  55362. // Blending
  55363. var enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  55364. if (enableBlending && this._blendingFactor <= 1.0) {
  55365. if (!this._originalBlendValue) {
  55366. var originalValue = destination[path];
  55367. if (originalValue.clone) {
  55368. this._originalBlendValue = originalValue.clone();
  55369. }
  55370. else {
  55371. this._originalBlendValue = originalValue;
  55372. }
  55373. }
  55374. if (this._originalBlendValue.m) { // Matrix
  55375. if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
  55376. if (this._currentValue) {
  55377. BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  55378. }
  55379. else {
  55380. this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  55381. }
  55382. }
  55383. else {
  55384. if (this._currentValue) {
  55385. BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  55386. }
  55387. else {
  55388. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  55389. }
  55390. }
  55391. }
  55392. else {
  55393. this._currentValue = BABYLON.Animation._UniversalLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  55394. }
  55395. var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  55396. this._blendingFactor += blendingSpeed;
  55397. }
  55398. else {
  55399. this._currentValue = currentValue;
  55400. }
  55401. if (weight !== -1.0) {
  55402. this._scene._registerTargetForLateAnimationBinding(this, this._originalValue[targetIndex]);
  55403. }
  55404. else {
  55405. destination[path] = this._currentValue;
  55406. }
  55407. if (target.markAsDirty) {
  55408. target.markAsDirty(this._animation.targetProperty);
  55409. }
  55410. };
  55411. /**
  55412. * Gets the loop pmode of the runtime animation
  55413. * @returns Loop Mode
  55414. */
  55415. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  55416. if (this._target && this._target.animationPropertiesOverride) {
  55417. return this._target.animationPropertiesOverride.loopMode;
  55418. }
  55419. return this._animation.loopMode;
  55420. };
  55421. /**
  55422. * Move the current animation to a given frame
  55423. * @param frame defines the frame to move to
  55424. */
  55425. RuntimeAnimation.prototype.goToFrame = function (frame) {
  55426. var keys = this._animation.getKeys();
  55427. if (frame < keys[0].frame) {
  55428. frame = keys[0].frame;
  55429. }
  55430. else if (frame > keys[keys.length - 1].frame) {
  55431. frame = keys[keys.length - 1].frame;
  55432. }
  55433. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  55434. this.setValue(currentValue, -1);
  55435. };
  55436. /**
  55437. * @hidden Internal use only
  55438. */
  55439. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  55440. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  55441. this._ratioOffset = this._previousRatio - newRatio;
  55442. };
  55443. /**
  55444. * Execute the current animation
  55445. * @param delay defines the delay to add to the current frame
  55446. * @param from defines the lower bound of the animation range
  55447. * @param to defines the upper bound of the animation range
  55448. * @param loop defines if the current animation must loop
  55449. * @param speedRatio defines the current speed ratio
  55450. * @param weight defines the weight of the animation (default is -1 so no weight)
  55451. * @returns a boolean indicating if the animation is running
  55452. */
  55453. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  55454. if (weight === void 0) { weight = -1.0; }
  55455. var targetPropertyPath = this._animation.targetPropertyPath;
  55456. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  55457. this._stopped = true;
  55458. return false;
  55459. }
  55460. var returnValue = true;
  55461. var keys = this._animation.getKeys();
  55462. // Adding a start key at frame 0 if missing
  55463. if (keys[0].frame !== 0) {
  55464. var newKey = { frame: 0, value: keys[0].value };
  55465. keys.splice(0, 0, newKey);
  55466. }
  55467. // Adding a duplicate key when there is only one key at frame zero
  55468. else if (keys.length === 1) {
  55469. var newKey = { frame: 0.001, value: keys[0].value };
  55470. keys.push(newKey);
  55471. }
  55472. // Check limits
  55473. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  55474. from = keys[0].frame;
  55475. }
  55476. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  55477. to = keys[keys.length - 1].frame;
  55478. }
  55479. //to and from cannot be the same key
  55480. if (from === to) {
  55481. if (from > keys[0].frame) {
  55482. from--;
  55483. }
  55484. else if (to < keys[keys.length - 1].frame) {
  55485. to++;
  55486. }
  55487. }
  55488. // Compute ratio
  55489. var range = to - from;
  55490. var offsetValue;
  55491. // ratio represents the frame delta between from and to
  55492. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  55493. var highLimitValue = 0;
  55494. this._previousDelay = delay;
  55495. this._previousRatio = ratio;
  55496. if (((to > from && ratio >= range) || (from > to && ratio <= range)) && !loop) { // If we are out of range and not looping get back to caller
  55497. returnValue = false;
  55498. highLimitValue = this._animation._getKeyValue(keys[keys.length - 1].value);
  55499. }
  55500. else {
  55501. // Get max value if required
  55502. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  55503. var keyOffset = to.toString() + from.toString();
  55504. if (!this._offsetsCache[keyOffset]) {
  55505. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  55506. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  55507. switch (this._animation.dataType) {
  55508. // Float
  55509. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  55510. this._offsetsCache[keyOffset] = toValue - fromValue;
  55511. break;
  55512. // Quaternion
  55513. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  55514. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  55515. break;
  55516. // Vector3
  55517. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  55518. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  55519. // Vector2
  55520. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  55521. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  55522. // Size
  55523. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  55524. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  55525. // Color3
  55526. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  55527. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  55528. default:
  55529. break;
  55530. }
  55531. this._highLimitsCache[keyOffset] = toValue;
  55532. }
  55533. highLimitValue = this._highLimitsCache[keyOffset];
  55534. offsetValue = this._offsetsCache[keyOffset];
  55535. }
  55536. }
  55537. if (offsetValue === undefined) {
  55538. switch (this._animation.dataType) {
  55539. // Float
  55540. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  55541. offsetValue = 0;
  55542. break;
  55543. // Quaternion
  55544. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  55545. offsetValue = _staticOffsetValueQuaternion;
  55546. break;
  55547. // Vector3
  55548. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  55549. offsetValue = _staticOffsetValueVector3;
  55550. break;
  55551. // Vector2
  55552. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  55553. offsetValue = _staticOffsetValueVector2;
  55554. break;
  55555. // Size
  55556. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  55557. offsetValue = _staticOffsetValueSize;
  55558. break;
  55559. // Color3
  55560. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  55561. offsetValue = _staticOffsetValueColor3;
  55562. }
  55563. }
  55564. // Compute value
  55565. var repeatCount = (ratio / range) >> 0;
  55566. var currentFrame = returnValue ? from + ratio % range : to;
  55567. // Need to normalize?
  55568. if (this._host && this._host.syncRoot) {
  55569. var syncRoot = this._host.syncRoot;
  55570. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  55571. currentFrame = from + (to - from) * hostNormalizedFrame;
  55572. }
  55573. // Reset events if looping
  55574. var events = this._events;
  55575. if (range > 0 && this.currentFrame > currentFrame ||
  55576. range < 0 && this.currentFrame < currentFrame) {
  55577. // Need to reset animation events
  55578. for (var index = 0; index < events.length; index++) {
  55579. if (!events[index].onlyOnce) {
  55580. // reset event, the animation is looping
  55581. events[index].isDone = false;
  55582. }
  55583. }
  55584. }
  55585. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  55586. // Set value
  55587. this.setValue(currentValue, weight);
  55588. // Check events
  55589. for (var index = 0; index < events.length; index++) {
  55590. // Make sure current frame has passed event frame and that event frame is within the current range
  55591. // Also, handle both forward and reverse animations
  55592. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  55593. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  55594. var event = events[index];
  55595. if (!event.isDone) {
  55596. // If event should be done only once, remove it.
  55597. if (event.onlyOnce) {
  55598. events.splice(index, 1);
  55599. index--;
  55600. }
  55601. event.isDone = true;
  55602. event.action(currentFrame);
  55603. } // Don't do anything if the event has already be done.
  55604. }
  55605. }
  55606. if (!returnValue) {
  55607. this._stopped = true;
  55608. }
  55609. return returnValue;
  55610. };
  55611. return RuntimeAnimation;
  55612. }());
  55613. BABYLON.RuntimeAnimation = RuntimeAnimation;
  55614. })(BABYLON || (BABYLON = {}));
  55615. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  55616. var BABYLON;
  55617. (function (BABYLON) {
  55618. /**
  55619. * Class used to store an actual running animation
  55620. */
  55621. var Animatable = /** @class */ (function () {
  55622. /**
  55623. * Creates a new Animatable
  55624. * @param scene defines the hosting scene
  55625. * @param target defines the target object
  55626. * @param fromFrame defines the starting frame number (default is 0)
  55627. * @param toFrame defines the ending frame number (default is 100)
  55628. * @param loopAnimation defines if the animation must loop (default is false)
  55629. * @param speedRatio defines the factor to apply to animation speed (default is 1)
  55630. * @param onAnimationEnd defines a callback to call when animation ends if it is not looping
  55631. * @param animations defines a group of animation to add to the new Animatable
  55632. */
  55633. function Animatable(scene,
  55634. /** defines the target object */
  55635. target,
  55636. /** defines the starting frame number (default is 0) */
  55637. fromFrame,
  55638. /** defines the ending frame number (default is 100) */
  55639. toFrame,
  55640. /** defines if the animation must loop (default is false) */
  55641. loopAnimation, speedRatio,
  55642. /** defines a callback to call when animation ends if it is not looping */
  55643. onAnimationEnd, animations) {
  55644. if (fromFrame === void 0) { fromFrame = 0; }
  55645. if (toFrame === void 0) { toFrame = 100; }
  55646. if (loopAnimation === void 0) { loopAnimation = false; }
  55647. if (speedRatio === void 0) { speedRatio = 1.0; }
  55648. this.target = target;
  55649. this.fromFrame = fromFrame;
  55650. this.toFrame = toFrame;
  55651. this.loopAnimation = loopAnimation;
  55652. this.onAnimationEnd = onAnimationEnd;
  55653. this._localDelayOffset = null;
  55654. this._pausedDelay = null;
  55655. this._runtimeAnimations = new Array();
  55656. this._paused = false;
  55657. this._speedRatio = 1;
  55658. this._weight = -1.0;
  55659. /**
  55660. * Gets or sets a boolean indicating if the animatable must be disposed and removed at the end of the animation.
  55661. * This will only apply for non looping animation (default is true)
  55662. */
  55663. this.disposeOnEnd = true;
  55664. /**
  55665. * Gets a boolean indicating if the animation has started
  55666. */
  55667. this.animationStarted = false;
  55668. /**
  55669. * Observer raised when the animation ends
  55670. */
  55671. this.onAnimationEndObservable = new BABYLON.Observable();
  55672. this._scene = scene;
  55673. if (animations) {
  55674. this.appendAnimations(target, animations);
  55675. }
  55676. this._speedRatio = speedRatio;
  55677. scene._activeAnimatables.push(this);
  55678. }
  55679. Object.defineProperty(Animatable.prototype, "syncRoot", {
  55680. /**
  55681. * Gets the root Animatable used to synchronize and normalize animations
  55682. */
  55683. get: function () {
  55684. return this._syncRoot;
  55685. },
  55686. enumerable: true,
  55687. configurable: true
  55688. });
  55689. Object.defineProperty(Animatable.prototype, "masterFrame", {
  55690. /**
  55691. * Gets the current frame of the first RuntimeAnimation
  55692. * Used to synchronize Animatables
  55693. */
  55694. get: function () {
  55695. if (this._runtimeAnimations.length === 0) {
  55696. return 0;
  55697. }
  55698. return this._runtimeAnimations[0].currentFrame;
  55699. },
  55700. enumerable: true,
  55701. configurable: true
  55702. });
  55703. Object.defineProperty(Animatable.prototype, "weight", {
  55704. /**
  55705. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  55706. */
  55707. get: function () {
  55708. return this._weight;
  55709. },
  55710. set: function (value) {
  55711. if (value === -1) { // -1 is ok and means no weight
  55712. this._weight = -1;
  55713. return;
  55714. }
  55715. // Else weight must be in [0, 1] range
  55716. this._weight = Math.min(Math.max(value, 0), 1.0);
  55717. },
  55718. enumerable: true,
  55719. configurable: true
  55720. });
  55721. Object.defineProperty(Animatable.prototype, "speedRatio", {
  55722. /**
  55723. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  55724. */
  55725. get: function () {
  55726. return this._speedRatio;
  55727. },
  55728. set: function (value) {
  55729. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  55730. var animation = this._runtimeAnimations[index];
  55731. animation._prepareForSpeedRatioChange(value);
  55732. }
  55733. this._speedRatio = value;
  55734. },
  55735. enumerable: true,
  55736. configurable: true
  55737. });
  55738. // Methods
  55739. /**
  55740. * Synchronize and normalize current Animatable with a source Animatable
  55741. * This is useful when using animation weights and when animations are not of the same length
  55742. * @param root defines the root Animatable to synchronize with
  55743. * @returns the current Animatable
  55744. */
  55745. Animatable.prototype.syncWith = function (root) {
  55746. this._syncRoot = root;
  55747. if (root) {
  55748. // Make sure this animatable will animate after the root
  55749. var index = this._scene._activeAnimatables.indexOf(this);
  55750. if (index > -1) {
  55751. this._scene._activeAnimatables.splice(index, 1);
  55752. this._scene._activeAnimatables.push(this);
  55753. }
  55754. }
  55755. return this;
  55756. };
  55757. /**
  55758. * Gets the list of runtime animations
  55759. * @returns an array of RuntimeAnimation
  55760. */
  55761. Animatable.prototype.getAnimations = function () {
  55762. return this._runtimeAnimations;
  55763. };
  55764. /**
  55765. * Adds more animations to the current animatable
  55766. * @param target defines the target of the animations
  55767. * @param animations defines the new animations to add
  55768. */
  55769. Animatable.prototype.appendAnimations = function (target, animations) {
  55770. for (var index = 0; index < animations.length; index++) {
  55771. var animation = animations[index];
  55772. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  55773. }
  55774. };
  55775. /**
  55776. * Gets the source animation for a specific property
  55777. * @param property defines the propertyu to look for
  55778. * @returns null or the source animation for the given property
  55779. */
  55780. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  55781. var runtimeAnimations = this._runtimeAnimations;
  55782. for (var index = 0; index < runtimeAnimations.length; index++) {
  55783. if (runtimeAnimations[index].animation.targetProperty === property) {
  55784. return runtimeAnimations[index].animation;
  55785. }
  55786. }
  55787. return null;
  55788. };
  55789. /**
  55790. * Gets the runtime animation for a specific property
  55791. * @param property defines the propertyu to look for
  55792. * @returns null or the runtime animation for the given property
  55793. */
  55794. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  55795. var runtimeAnimations = this._runtimeAnimations;
  55796. for (var index = 0; index < runtimeAnimations.length; index++) {
  55797. if (runtimeAnimations[index].animation.targetProperty === property) {
  55798. return runtimeAnimations[index];
  55799. }
  55800. }
  55801. return null;
  55802. };
  55803. /**
  55804. * Resets the animatable to its original state
  55805. */
  55806. Animatable.prototype.reset = function () {
  55807. var runtimeAnimations = this._runtimeAnimations;
  55808. for (var index = 0; index < runtimeAnimations.length; index++) {
  55809. runtimeAnimations[index].reset(true);
  55810. }
  55811. this._localDelayOffset = null;
  55812. this._pausedDelay = null;
  55813. };
  55814. /**
  55815. * Allows the animatable to blend with current running animations
  55816. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  55817. * @param blendingSpeed defines the blending speed to use
  55818. */
  55819. Animatable.prototype.enableBlending = function (blendingSpeed) {
  55820. var runtimeAnimations = this._runtimeAnimations;
  55821. for (var index = 0; index < runtimeAnimations.length; index++) {
  55822. runtimeAnimations[index].animation.enableBlending = true;
  55823. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  55824. }
  55825. };
  55826. /**
  55827. * Disable animation blending
  55828. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  55829. */
  55830. Animatable.prototype.disableBlending = function () {
  55831. var runtimeAnimations = this._runtimeAnimations;
  55832. for (var index = 0; index < runtimeAnimations.length; index++) {
  55833. runtimeAnimations[index].animation.enableBlending = false;
  55834. }
  55835. };
  55836. /**
  55837. * Jump directly to a given frame
  55838. * @param frame defines the frame to jump to
  55839. */
  55840. Animatable.prototype.goToFrame = function (frame) {
  55841. var runtimeAnimations = this._runtimeAnimations;
  55842. if (runtimeAnimations[0]) {
  55843. var fps = runtimeAnimations[0].animation.framePerSecond;
  55844. var currentFrame = runtimeAnimations[0].currentFrame;
  55845. var adjustTime = frame - currentFrame;
  55846. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  55847. if (this._localDelayOffset === null) {
  55848. this._localDelayOffset = 0;
  55849. }
  55850. this._localDelayOffset -= delay;
  55851. }
  55852. for (var index = 0; index < runtimeAnimations.length; index++) {
  55853. runtimeAnimations[index].goToFrame(frame);
  55854. }
  55855. };
  55856. /**
  55857. * Pause the animation
  55858. */
  55859. Animatable.prototype.pause = function () {
  55860. if (this._paused) {
  55861. return;
  55862. }
  55863. this._paused = true;
  55864. };
  55865. /**
  55866. * Restart the animation
  55867. */
  55868. Animatable.prototype.restart = function () {
  55869. this._paused = false;
  55870. };
  55871. Animatable.prototype._raiseOnAnimationEnd = function () {
  55872. if (this.onAnimationEnd) {
  55873. this.onAnimationEnd();
  55874. }
  55875. this.onAnimationEndObservable.notifyObservers(this);
  55876. };
  55877. /**
  55878. * Stop and delete the current animation
  55879. * @param animationName defines a string used to only stop some of the runtime animations instead of all
  55880. * @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)
  55881. */
  55882. Animatable.prototype.stop = function (animationName, targetMask) {
  55883. if (animationName || targetMask) {
  55884. var idx = this._scene._activeAnimatables.indexOf(this);
  55885. if (idx > -1) {
  55886. var runtimeAnimations = this._runtimeAnimations;
  55887. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  55888. var runtimeAnimation = runtimeAnimations[index];
  55889. if (animationName && runtimeAnimation.animation.name != animationName) {
  55890. continue;
  55891. }
  55892. if (targetMask && !targetMask(runtimeAnimation.target)) {
  55893. continue;
  55894. }
  55895. runtimeAnimation.dispose();
  55896. runtimeAnimations.splice(index, 1);
  55897. }
  55898. if (runtimeAnimations.length == 0) {
  55899. this._scene._activeAnimatables.splice(idx, 1);
  55900. this._raiseOnAnimationEnd();
  55901. }
  55902. }
  55903. }
  55904. else {
  55905. var index = this._scene._activeAnimatables.indexOf(this);
  55906. if (index > -1) {
  55907. this._scene._activeAnimatables.splice(index, 1);
  55908. var runtimeAnimations = this._runtimeAnimations;
  55909. for (var index = 0; index < runtimeAnimations.length; index++) {
  55910. runtimeAnimations[index].dispose();
  55911. }
  55912. this._raiseOnAnimationEnd();
  55913. }
  55914. }
  55915. };
  55916. /**
  55917. * Wait asynchronously for the animation to end
  55918. * @returns a promise which will be fullfilled when the animation ends
  55919. */
  55920. Animatable.prototype.waitAsync = function () {
  55921. var _this = this;
  55922. return new Promise(function (resolve, reject) {
  55923. _this.onAnimationEndObservable.add(function () {
  55924. resolve(_this);
  55925. }, undefined, undefined, _this, true);
  55926. });
  55927. };
  55928. /** @hidden */
  55929. Animatable.prototype._animate = function (delay) {
  55930. if (this._paused) {
  55931. this.animationStarted = false;
  55932. if (this._pausedDelay === null) {
  55933. this._pausedDelay = delay;
  55934. }
  55935. return true;
  55936. }
  55937. if (this._localDelayOffset === null) {
  55938. this._localDelayOffset = delay;
  55939. this._pausedDelay = null;
  55940. }
  55941. else if (this._pausedDelay !== null) {
  55942. this._localDelayOffset += delay - this._pausedDelay;
  55943. this._pausedDelay = null;
  55944. }
  55945. if (this._weight === 0) { // We consider that an animation with a weight === 0 is "actively" paused
  55946. return true;
  55947. }
  55948. // Animating
  55949. var running = false;
  55950. var runtimeAnimations = this._runtimeAnimations;
  55951. var index;
  55952. for (index = 0; index < runtimeAnimations.length; index++) {
  55953. var animation = runtimeAnimations[index];
  55954. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  55955. running = running || isRunning;
  55956. }
  55957. this.animationStarted = running;
  55958. if (!running) {
  55959. if (this.disposeOnEnd) {
  55960. // Remove from active animatables
  55961. index = this._scene._activeAnimatables.indexOf(this);
  55962. this._scene._activeAnimatables.splice(index, 1);
  55963. // Dispose all runtime animations
  55964. for (index = 0; index < runtimeAnimations.length; index++) {
  55965. runtimeAnimations[index].dispose();
  55966. }
  55967. }
  55968. this._raiseOnAnimationEnd();
  55969. if (this.disposeOnEnd) {
  55970. this.onAnimationEnd = null;
  55971. this.onAnimationEndObservable.clear();
  55972. }
  55973. }
  55974. return running;
  55975. };
  55976. return Animatable;
  55977. }());
  55978. BABYLON.Animatable = Animatable;
  55979. })(BABYLON || (BABYLON = {}));
  55980. //# sourceMappingURL=babylon.animatable.js.map
  55981. var BABYLON;
  55982. (function (BABYLON) {
  55983. /**
  55984. * Base class used for every default easing function.
  55985. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  55986. */
  55987. var EasingFunction = /** @class */ (function () {
  55988. function EasingFunction() {
  55989. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  55990. }
  55991. /**
  55992. * Sets the easing mode of the current function.
  55993. * @param easingMode Defines the willing mode (EASINGMODE_EASEIN, EASINGMODE_EASEOUT or EASINGMODE_EASEINOUT)
  55994. */
  55995. EasingFunction.prototype.setEasingMode = function (easingMode) {
  55996. var n = Math.min(Math.max(easingMode, 0), 2);
  55997. this._easingMode = n;
  55998. };
  55999. /**
  56000. * Gets the current easing mode.
  56001. * @returns the easing mode
  56002. */
  56003. EasingFunction.prototype.getEasingMode = function () {
  56004. return this._easingMode;
  56005. };
  56006. /**
  56007. * @hidden
  56008. */
  56009. EasingFunction.prototype.easeInCore = function (gradient) {
  56010. throw new Error('You must implement this method');
  56011. };
  56012. /**
  56013. * Given an input gradient between 0 and 1, this returns the corrseponding value
  56014. * of the easing function.
  56015. * @param gradient Defines the value between 0 and 1 we want the easing value for
  56016. * @returns the corresponding value on the curve defined by the easing function
  56017. */
  56018. EasingFunction.prototype.ease = function (gradient) {
  56019. switch (this._easingMode) {
  56020. case EasingFunction.EASINGMODE_EASEIN:
  56021. return this.easeInCore(gradient);
  56022. case EasingFunction.EASINGMODE_EASEOUT:
  56023. return (1 - this.easeInCore(1 - gradient));
  56024. }
  56025. if (gradient >= 0.5) {
  56026. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  56027. }
  56028. return (this.easeInCore(gradient * 2) * 0.5);
  56029. };
  56030. /**
  56031. * Interpolation follows the mathematical formula associated with the easing function.
  56032. */
  56033. EasingFunction.EASINGMODE_EASEIN = 0;
  56034. /**
  56035. * Interpolation follows 100% interpolation minus the output of the formula associated with the easing function.
  56036. */
  56037. EasingFunction.EASINGMODE_EASEOUT = 1;
  56038. /**
  56039. * Interpolation uses EaseIn for the first half of the animation and EaseOut for the second half.
  56040. */
  56041. EasingFunction.EASINGMODE_EASEINOUT = 2;
  56042. return EasingFunction;
  56043. }());
  56044. BABYLON.EasingFunction = EasingFunction;
  56045. /**
  56046. * Easing function with a circle shape (see link below).
  56047. * @see https://easings.net/#easeInCirc
  56048. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  56049. */
  56050. var CircleEase = /** @class */ (function (_super) {
  56051. __extends(CircleEase, _super);
  56052. function CircleEase() {
  56053. return _super !== null && _super.apply(this, arguments) || this;
  56054. }
  56055. /** @hidden */
  56056. CircleEase.prototype.easeInCore = function (gradient) {
  56057. gradient = Math.max(0, Math.min(1, gradient));
  56058. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  56059. };
  56060. return CircleEase;
  56061. }(EasingFunction));
  56062. BABYLON.CircleEase = CircleEase;
  56063. /**
  56064. * Easing function with a ease back shape (see link below).
  56065. * @see https://easings.net/#easeInBack
  56066. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  56067. */
  56068. var BackEase = /** @class */ (function (_super) {
  56069. __extends(BackEase, _super);
  56070. /**
  56071. * Instantiates a back ease easing
  56072. * @see https://easings.net/#easeInBack
  56073. * @param amplitude Defines the amplitude of the function
  56074. */
  56075. function BackEase(
  56076. /** Defines the amplitude of the function */
  56077. amplitude) {
  56078. if (amplitude === void 0) { amplitude = 1; }
  56079. var _this = _super.call(this) || this;
  56080. _this.amplitude = amplitude;
  56081. return _this;
  56082. }
  56083. /** @hidden */
  56084. BackEase.prototype.easeInCore = function (gradient) {
  56085. var num = Math.max(0, this.amplitude);
  56086. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  56087. };
  56088. return BackEase;
  56089. }(EasingFunction));
  56090. BABYLON.BackEase = BackEase;
  56091. /**
  56092. * Easing function with a bouncing shape (see link below).
  56093. * @see https://easings.net/#easeInBounce
  56094. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  56095. */
  56096. var BounceEase = /** @class */ (function (_super) {
  56097. __extends(BounceEase, _super);
  56098. /**
  56099. * Instantiates a bounce easing
  56100. * @see https://easings.net/#easeInBounce
  56101. * @param bounces Defines the number of bounces
  56102. * @param bounciness Defines the amplitude of the bounce
  56103. */
  56104. function BounceEase(
  56105. /** Defines the number of bounces */
  56106. bounces,
  56107. /** Defines the amplitude of the bounce */
  56108. bounciness) {
  56109. if (bounces === void 0) { bounces = 3; }
  56110. if (bounciness === void 0) { bounciness = 2; }
  56111. var _this = _super.call(this) || this;
  56112. _this.bounces = bounces;
  56113. _this.bounciness = bounciness;
  56114. return _this;
  56115. }
  56116. /** @hidden */
  56117. BounceEase.prototype.easeInCore = function (gradient) {
  56118. var y = Math.max(0.0, this.bounces);
  56119. var bounciness = this.bounciness;
  56120. if (bounciness <= 1.0) {
  56121. bounciness = 1.001;
  56122. }
  56123. var num9 = Math.pow(bounciness, y);
  56124. var num5 = 1.0 - bounciness;
  56125. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  56126. var num15 = gradient * num4;
  56127. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  56128. var num3 = Math.floor(num65);
  56129. var num13 = num3 + 1.0;
  56130. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  56131. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  56132. var num7 = (num8 + num12) * 0.5;
  56133. var num6 = gradient - num7;
  56134. var num2 = num7 - num8;
  56135. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  56136. };
  56137. return BounceEase;
  56138. }(EasingFunction));
  56139. BABYLON.BounceEase = BounceEase;
  56140. /**
  56141. * Easing function with a power of 3 shape (see link below).
  56142. * @see https://easings.net/#easeInCubic
  56143. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  56144. */
  56145. var CubicEase = /** @class */ (function (_super) {
  56146. __extends(CubicEase, _super);
  56147. function CubicEase() {
  56148. return _super !== null && _super.apply(this, arguments) || this;
  56149. }
  56150. /** @hidden */
  56151. CubicEase.prototype.easeInCore = function (gradient) {
  56152. return (gradient * gradient * gradient);
  56153. };
  56154. return CubicEase;
  56155. }(EasingFunction));
  56156. BABYLON.CubicEase = CubicEase;
  56157. /**
  56158. * Easing function with an elastic shape (see link below).
  56159. * @see https://easings.net/#easeInElastic
  56160. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  56161. */
  56162. var ElasticEase = /** @class */ (function (_super) {
  56163. __extends(ElasticEase, _super);
  56164. /**
  56165. * Instantiates an elastic easing function
  56166. * @see https://easings.net/#easeInElastic
  56167. * @param oscillations Defines the number of oscillations
  56168. * @param springiness Defines the amplitude of the oscillations
  56169. */
  56170. function ElasticEase(
  56171. /** Defines the number of oscillations*/
  56172. oscillations,
  56173. /** Defines the amplitude of the oscillations*/
  56174. springiness) {
  56175. if (oscillations === void 0) { oscillations = 3; }
  56176. if (springiness === void 0) { springiness = 3; }
  56177. var _this = _super.call(this) || this;
  56178. _this.oscillations = oscillations;
  56179. _this.springiness = springiness;
  56180. return _this;
  56181. }
  56182. /** @hidden */
  56183. ElasticEase.prototype.easeInCore = function (gradient) {
  56184. var num2;
  56185. var num3 = Math.max(0.0, this.oscillations);
  56186. var num = Math.max(0.0, this.springiness);
  56187. if (num == 0) {
  56188. num2 = gradient;
  56189. }
  56190. else {
  56191. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  56192. }
  56193. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  56194. };
  56195. return ElasticEase;
  56196. }(EasingFunction));
  56197. BABYLON.ElasticEase = ElasticEase;
  56198. /**
  56199. * Easing function with an exponential shape (see link below).
  56200. * @see https://easings.net/#easeInExpo
  56201. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  56202. */
  56203. var ExponentialEase = /** @class */ (function (_super) {
  56204. __extends(ExponentialEase, _super);
  56205. /**
  56206. * Instantiates an exponential easing function
  56207. * @see https://easings.net/#easeInExpo
  56208. * @param exponent Defines the exponent of the function
  56209. */
  56210. function ExponentialEase(
  56211. /** Defines the exponent of the function */
  56212. exponent) {
  56213. if (exponent === void 0) { exponent = 2; }
  56214. var _this = _super.call(this) || this;
  56215. _this.exponent = exponent;
  56216. return _this;
  56217. }
  56218. /** @hidden */
  56219. ExponentialEase.prototype.easeInCore = function (gradient) {
  56220. if (this.exponent <= 0) {
  56221. return gradient;
  56222. }
  56223. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  56224. };
  56225. return ExponentialEase;
  56226. }(EasingFunction));
  56227. BABYLON.ExponentialEase = ExponentialEase;
  56228. /**
  56229. * Easing function with a power shape (see link below).
  56230. * @see https://easings.net/#easeInQuad
  56231. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  56232. */
  56233. var PowerEase = /** @class */ (function (_super) {
  56234. __extends(PowerEase, _super);
  56235. /**
  56236. * Instantiates an power base easing function
  56237. * @see https://easings.net/#easeInQuad
  56238. * @param power Defines the power of the function
  56239. */
  56240. function PowerEase(
  56241. /** Defines the power of the function */
  56242. power) {
  56243. if (power === void 0) { power = 2; }
  56244. var _this = _super.call(this) || this;
  56245. _this.power = power;
  56246. return _this;
  56247. }
  56248. /** @hidden */
  56249. PowerEase.prototype.easeInCore = function (gradient) {
  56250. var y = Math.max(0.0, this.power);
  56251. return Math.pow(gradient, y);
  56252. };
  56253. return PowerEase;
  56254. }(EasingFunction));
  56255. BABYLON.PowerEase = PowerEase;
  56256. /**
  56257. * Easing function with a power of 2 shape (see link below).
  56258. * @see https://easings.net/#easeInQuad
  56259. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  56260. */
  56261. var QuadraticEase = /** @class */ (function (_super) {
  56262. __extends(QuadraticEase, _super);
  56263. function QuadraticEase() {
  56264. return _super !== null && _super.apply(this, arguments) || this;
  56265. }
  56266. /** @hidden */
  56267. QuadraticEase.prototype.easeInCore = function (gradient) {
  56268. return (gradient * gradient);
  56269. };
  56270. return QuadraticEase;
  56271. }(EasingFunction));
  56272. BABYLON.QuadraticEase = QuadraticEase;
  56273. /**
  56274. * Easing function with a power of 4 shape (see link below).
  56275. * @see https://easings.net/#easeInQuart
  56276. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  56277. */
  56278. var QuarticEase = /** @class */ (function (_super) {
  56279. __extends(QuarticEase, _super);
  56280. function QuarticEase() {
  56281. return _super !== null && _super.apply(this, arguments) || this;
  56282. }
  56283. /** @hidden */
  56284. QuarticEase.prototype.easeInCore = function (gradient) {
  56285. return (gradient * gradient * gradient * gradient);
  56286. };
  56287. return QuarticEase;
  56288. }(EasingFunction));
  56289. BABYLON.QuarticEase = QuarticEase;
  56290. /**
  56291. * Easing function with a power of 5 shape (see link below).
  56292. * @see https://easings.net/#easeInQuint
  56293. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  56294. */
  56295. var QuinticEase = /** @class */ (function (_super) {
  56296. __extends(QuinticEase, _super);
  56297. function QuinticEase() {
  56298. return _super !== null && _super.apply(this, arguments) || this;
  56299. }
  56300. /** @hidden */
  56301. QuinticEase.prototype.easeInCore = function (gradient) {
  56302. return (gradient * gradient * gradient * gradient * gradient);
  56303. };
  56304. return QuinticEase;
  56305. }(EasingFunction));
  56306. BABYLON.QuinticEase = QuinticEase;
  56307. /**
  56308. * Easing function with a sin shape (see link below).
  56309. * @see https://easings.net/#easeInSine
  56310. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  56311. */
  56312. var SineEase = /** @class */ (function (_super) {
  56313. __extends(SineEase, _super);
  56314. function SineEase() {
  56315. return _super !== null && _super.apply(this, arguments) || this;
  56316. }
  56317. /** @hidden */
  56318. SineEase.prototype.easeInCore = function (gradient) {
  56319. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  56320. };
  56321. return SineEase;
  56322. }(EasingFunction));
  56323. BABYLON.SineEase = SineEase;
  56324. /**
  56325. * Easing function with a bezier shape (see link below).
  56326. * @see http://cubic-bezier.com/#.17,.67,.83,.67
  56327. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  56328. */
  56329. var BezierCurveEase = /** @class */ (function (_super) {
  56330. __extends(BezierCurveEase, _super);
  56331. /**
  56332. * Instantiates a bezier function
  56333. * @see http://cubic-bezier.com/#.17,.67,.83,.67
  56334. * @param x1 Defines the x component of the start tangent in the bezier curve
  56335. * @param y1 Defines the y component of the start tangent in the bezier curve
  56336. * @param x2 Defines the x component of the end tangent in the bezier curve
  56337. * @param y2 Defines the y component of the end tangent in the bezier curve
  56338. */
  56339. function BezierCurveEase(
  56340. /** Defines the x component of the start tangent in the bezier curve */
  56341. x1,
  56342. /** Defines the y component of the start tangent in the bezier curve */
  56343. y1,
  56344. /** Defines the x component of the end tangent in the bezier curve */
  56345. x2,
  56346. /** Defines the y component of the end tangent in the bezier curve */
  56347. y2) {
  56348. if (x1 === void 0) { x1 = 0; }
  56349. if (y1 === void 0) { y1 = 0; }
  56350. if (x2 === void 0) { x2 = 1; }
  56351. if (y2 === void 0) { y2 = 1; }
  56352. var _this = _super.call(this) || this;
  56353. _this.x1 = x1;
  56354. _this.y1 = y1;
  56355. _this.x2 = x2;
  56356. _this.y2 = y2;
  56357. return _this;
  56358. }
  56359. /** @hidden */
  56360. BezierCurveEase.prototype.easeInCore = function (gradient) {
  56361. return BABYLON.BezierCurve.Interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  56362. };
  56363. return BezierCurveEase;
  56364. }(EasingFunction));
  56365. BABYLON.BezierCurveEase = BezierCurveEase;
  56366. })(BABYLON || (BABYLON = {}));
  56367. //# sourceMappingURL=babylon.easing.js.map
  56368. var BABYLON;
  56369. (function (BABYLON) {
  56370. /**
  56371. * A Condition applied to an Action
  56372. */
  56373. var Condition = /** @class */ (function () {
  56374. /**
  56375. * Creates a new Condition
  56376. * @param actionManager the manager of the action the condition is applied to
  56377. */
  56378. function Condition(actionManager) {
  56379. this._actionManager = actionManager;
  56380. }
  56381. /**
  56382. * Check if the current condition is valid
  56383. * @returns a boolean
  56384. */
  56385. Condition.prototype.isValid = function () {
  56386. return true;
  56387. };
  56388. /**
  56389. * Internal only
  56390. * @hidden
  56391. */
  56392. Condition.prototype._getProperty = function (propertyPath) {
  56393. return this._actionManager._getProperty(propertyPath);
  56394. };
  56395. /**
  56396. * Internal only
  56397. * @hidden
  56398. */
  56399. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  56400. return this._actionManager._getEffectiveTarget(target, propertyPath);
  56401. };
  56402. /**
  56403. * Serialize placeholder for child classes
  56404. * @returns the serialized object
  56405. */
  56406. Condition.prototype.serialize = function () {
  56407. };
  56408. /**
  56409. * Internal only
  56410. * @hidden
  56411. */
  56412. Condition.prototype._serialize = function (serializedCondition) {
  56413. return {
  56414. type: 2,
  56415. children: [],
  56416. name: serializedCondition.name,
  56417. properties: serializedCondition.properties
  56418. };
  56419. };
  56420. return Condition;
  56421. }());
  56422. BABYLON.Condition = Condition;
  56423. /**
  56424. * Defines specific conditional operators as extensions of Condition
  56425. */
  56426. var ValueCondition = /** @class */ (function (_super) {
  56427. __extends(ValueCondition, _super);
  56428. /**
  56429. * Creates a new ValueCondition
  56430. * @param actionManager manager for the action the condition applies to
  56431. * @param target for the action
  56432. * @param propertyPath path to specify the property of the target the conditional operator uses
  56433. * @param value the value compared by the conditional operator against the current value of the property
  56434. * @param operator the conditional operator, default ValueCondition.IsEqual
  56435. */
  56436. function ValueCondition(actionManager, target,
  56437. /** path to specify the property of the target the conditional operator uses */
  56438. propertyPath,
  56439. /** the value compared by the conditional operator against the current value of the property */
  56440. value,
  56441. /** the conditional operator, default ValueCondition.IsEqual */
  56442. operator) {
  56443. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  56444. var _this = _super.call(this, actionManager) || this;
  56445. _this.propertyPath = propertyPath;
  56446. _this.value = value;
  56447. _this.operator = operator;
  56448. _this._target = target;
  56449. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  56450. _this._property = _this._getProperty(_this.propertyPath);
  56451. return _this;
  56452. }
  56453. Object.defineProperty(ValueCondition, "IsEqual", {
  56454. /**
  56455. * returns the number for IsEqual
  56456. */
  56457. get: function () {
  56458. return ValueCondition._IsEqual;
  56459. },
  56460. enumerable: true,
  56461. configurable: true
  56462. });
  56463. Object.defineProperty(ValueCondition, "IsDifferent", {
  56464. /**
  56465. * Returns the number for IsDifferent
  56466. */
  56467. get: function () {
  56468. return ValueCondition._IsDifferent;
  56469. },
  56470. enumerable: true,
  56471. configurable: true
  56472. });
  56473. Object.defineProperty(ValueCondition, "IsGreater", {
  56474. /**
  56475. * Returns the number for IsGreater
  56476. */
  56477. get: function () {
  56478. return ValueCondition._IsGreater;
  56479. },
  56480. enumerable: true,
  56481. configurable: true
  56482. });
  56483. Object.defineProperty(ValueCondition, "IsLesser", {
  56484. /**
  56485. * Returns the number for IsLesser
  56486. */
  56487. get: function () {
  56488. return ValueCondition._IsLesser;
  56489. },
  56490. enumerable: true,
  56491. configurable: true
  56492. });
  56493. /**
  56494. * Compares the given value with the property value for the specified conditional operator
  56495. * @returns the result of the comparison
  56496. */
  56497. ValueCondition.prototype.isValid = function () {
  56498. switch (this.operator) {
  56499. case ValueCondition.IsGreater:
  56500. return this._effectiveTarget[this._property] > this.value;
  56501. case ValueCondition.IsLesser:
  56502. return this._effectiveTarget[this._property] < this.value;
  56503. case ValueCondition.IsEqual:
  56504. case ValueCondition.IsDifferent:
  56505. var check;
  56506. if (this.value.equals) {
  56507. check = this.value.equals(this._effectiveTarget[this._property]);
  56508. }
  56509. else {
  56510. check = this.value === this._effectiveTarget[this._property];
  56511. }
  56512. return this.operator === ValueCondition.IsEqual ? check : !check;
  56513. }
  56514. return false;
  56515. };
  56516. /**
  56517. * Serialize the ValueCondition into a JSON compatible object
  56518. * @returns serialization object
  56519. */
  56520. ValueCondition.prototype.serialize = function () {
  56521. return this._serialize({
  56522. name: "ValueCondition",
  56523. properties: [
  56524. BABYLON.Action._GetTargetProperty(this._target),
  56525. { name: "propertyPath", value: this.propertyPath },
  56526. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  56527. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  56528. ]
  56529. });
  56530. };
  56531. /**
  56532. * Gets the name of the conditional operator for the ValueCondition
  56533. * @param operator the conditional operator
  56534. * @returns the name
  56535. */
  56536. ValueCondition.GetOperatorName = function (operator) {
  56537. switch (operator) {
  56538. case ValueCondition._IsEqual: return "IsEqual";
  56539. case ValueCondition._IsDifferent: return "IsDifferent";
  56540. case ValueCondition._IsGreater: return "IsGreater";
  56541. case ValueCondition._IsLesser: return "IsLesser";
  56542. default: return "";
  56543. }
  56544. };
  56545. /**
  56546. * Internal only
  56547. * @hidden
  56548. */
  56549. ValueCondition._IsEqual = 0;
  56550. /**
  56551. * Internal only
  56552. * @hidden
  56553. */
  56554. ValueCondition._IsDifferent = 1;
  56555. /**
  56556. * Internal only
  56557. * @hidden
  56558. */
  56559. ValueCondition._IsGreater = 2;
  56560. /**
  56561. * Internal only
  56562. * @hidden
  56563. */
  56564. ValueCondition._IsLesser = 3;
  56565. return ValueCondition;
  56566. }(Condition));
  56567. BABYLON.ValueCondition = ValueCondition;
  56568. /**
  56569. * Defines a predicate condition as an extension of Condition
  56570. */
  56571. var PredicateCondition = /** @class */ (function (_super) {
  56572. __extends(PredicateCondition, _super);
  56573. /**
  56574. * Creates a new PredicateCondition
  56575. * @param actionManager manager for the action the condition applies to
  56576. * @param predicate defines the predicate function used to validate the condition
  56577. */
  56578. function PredicateCondition(actionManager,
  56579. /** defines the predicate function used to validate the condition */
  56580. predicate) {
  56581. var _this = _super.call(this, actionManager) || this;
  56582. _this.predicate = predicate;
  56583. return _this;
  56584. }
  56585. /**
  56586. * @returns the validity of the predicate condition
  56587. */
  56588. PredicateCondition.prototype.isValid = function () {
  56589. return this.predicate();
  56590. };
  56591. return PredicateCondition;
  56592. }(Condition));
  56593. BABYLON.PredicateCondition = PredicateCondition;
  56594. /**
  56595. * Defines a state condition as an extension of Condition
  56596. */
  56597. var StateCondition = /** @class */ (function (_super) {
  56598. __extends(StateCondition, _super);
  56599. /**
  56600. * Creates a new StateCondition
  56601. * @param actionManager manager for the action the condition applies to
  56602. * @param target of the condition
  56603. * @param value to compare with target state
  56604. */
  56605. function StateCondition(actionManager, target,
  56606. /** Value to compare with target state */
  56607. value) {
  56608. var _this = _super.call(this, actionManager) || this;
  56609. _this.value = value;
  56610. _this._target = target;
  56611. return _this;
  56612. }
  56613. /**
  56614. * Gets a boolean indicating if the current condition is met
  56615. * @returns the validity of the state
  56616. */
  56617. StateCondition.prototype.isValid = function () {
  56618. return this._target.state === this.value;
  56619. };
  56620. /**
  56621. * Serialize the StateCondition into a JSON compatible object
  56622. * @returns serialization object
  56623. */
  56624. StateCondition.prototype.serialize = function () {
  56625. return this._serialize({
  56626. name: "StateCondition",
  56627. properties: [
  56628. BABYLON.Action._GetTargetProperty(this._target),
  56629. { name: "value", value: this.value }
  56630. ]
  56631. });
  56632. };
  56633. return StateCondition;
  56634. }(Condition));
  56635. BABYLON.StateCondition = StateCondition;
  56636. })(BABYLON || (BABYLON = {}));
  56637. //# sourceMappingURL=babylon.condition.js.map
  56638. var BABYLON;
  56639. (function (BABYLON) {
  56640. /**
  56641. * The action to be carried out following a trigger
  56642. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  56643. */
  56644. var Action = /** @class */ (function () {
  56645. /**
  56646. * Creates a new Action
  56647. * @param triggerOptions the trigger, with or without parameters, for the action
  56648. * @param condition an optional determinant of action
  56649. */
  56650. function Action(
  56651. /** the trigger, with or without parameters, for the action */
  56652. triggerOptions, condition) {
  56653. this.triggerOptions = triggerOptions;
  56654. /**
  56655. * An event triggered prior to action being executed.
  56656. */
  56657. this.onBeforeExecuteObservable = new BABYLON.Observable();
  56658. if (triggerOptions.parameter) {
  56659. this.trigger = triggerOptions.trigger;
  56660. this._triggerParameter = triggerOptions.parameter;
  56661. }
  56662. else if (triggerOptions.trigger) {
  56663. this.trigger = triggerOptions.trigger;
  56664. }
  56665. else {
  56666. this.trigger = triggerOptions;
  56667. }
  56668. this._nextActiveAction = this;
  56669. this._condition = condition;
  56670. }
  56671. /**
  56672. * Internal only
  56673. * @hidden
  56674. */
  56675. Action.prototype._prepare = function () {
  56676. };
  56677. /**
  56678. * Gets the trigger parameters
  56679. * @returns the trigger parameters
  56680. */
  56681. Action.prototype.getTriggerParameter = function () {
  56682. return this._triggerParameter;
  56683. };
  56684. /**
  56685. * Internal only - executes current action event
  56686. * @hidden
  56687. */
  56688. Action.prototype._executeCurrent = function (evt) {
  56689. if (this._nextActiveAction._condition) {
  56690. var condition = this._nextActiveAction._condition;
  56691. var currentRenderId = this._actionManager.getScene().getRenderId();
  56692. // We cache the current evaluation for the current frame
  56693. if (condition._evaluationId === currentRenderId) {
  56694. if (!condition._currentResult) {
  56695. return;
  56696. }
  56697. }
  56698. else {
  56699. condition._evaluationId = currentRenderId;
  56700. if (!condition.isValid()) {
  56701. condition._currentResult = false;
  56702. return;
  56703. }
  56704. condition._currentResult = true;
  56705. }
  56706. }
  56707. this.onBeforeExecuteObservable.notifyObservers(this);
  56708. this._nextActiveAction.execute(evt);
  56709. this.skipToNextActiveAction();
  56710. };
  56711. /**
  56712. * Execute placeholder for child classes
  56713. * @param evt optional action event
  56714. */
  56715. Action.prototype.execute = function (evt) {
  56716. };
  56717. /**
  56718. * Skips to next active action
  56719. */
  56720. Action.prototype.skipToNextActiveAction = function () {
  56721. if (this._nextActiveAction._child) {
  56722. if (!this._nextActiveAction._child._actionManager) {
  56723. this._nextActiveAction._child._actionManager = this._actionManager;
  56724. }
  56725. this._nextActiveAction = this._nextActiveAction._child;
  56726. }
  56727. else {
  56728. this._nextActiveAction = this;
  56729. }
  56730. };
  56731. /**
  56732. * Adds action to chain of actions, may be a DoNothingAction
  56733. * @param action defines the next action to execute
  56734. * @returns The action passed in
  56735. * @see https://www.babylonjs-playground.com/#1T30HR#0
  56736. */
  56737. Action.prototype.then = function (action) {
  56738. this._child = action;
  56739. action._actionManager = this._actionManager;
  56740. action._prepare();
  56741. return action;
  56742. };
  56743. /**
  56744. * Internal only
  56745. * @hidden
  56746. */
  56747. Action.prototype._getProperty = function (propertyPath) {
  56748. return this._actionManager._getProperty(propertyPath);
  56749. };
  56750. /**
  56751. * Internal only
  56752. * @hidden
  56753. */
  56754. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  56755. return this._actionManager._getEffectiveTarget(target, propertyPath);
  56756. };
  56757. /**
  56758. * Serialize placeholder for child classes
  56759. * @param parent of child
  56760. * @returns the serialized object
  56761. */
  56762. Action.prototype.serialize = function (parent) {
  56763. };
  56764. /**
  56765. * Internal only called by serialize
  56766. * @hidden
  56767. */
  56768. Action.prototype._serialize = function (serializedAction, parent) {
  56769. var serializationObject = {
  56770. type: 1,
  56771. children: [],
  56772. name: serializedAction.name,
  56773. properties: serializedAction.properties || []
  56774. };
  56775. // Serialize child
  56776. if (this._child) {
  56777. this._child.serialize(serializationObject);
  56778. }
  56779. // Check if "this" has a condition
  56780. if (this._condition) {
  56781. var serializedCondition = this._condition.serialize();
  56782. serializedCondition.children.push(serializationObject);
  56783. if (parent) {
  56784. parent.children.push(serializedCondition);
  56785. }
  56786. return serializedCondition;
  56787. }
  56788. if (parent) {
  56789. parent.children.push(serializationObject);
  56790. }
  56791. return serializationObject;
  56792. };
  56793. /**
  56794. * Internal only
  56795. * @hidden
  56796. */
  56797. Action._SerializeValueAsString = function (value) {
  56798. if (typeof value === "number") {
  56799. return value.toString();
  56800. }
  56801. if (typeof value === "boolean") {
  56802. return value ? "true" : "false";
  56803. }
  56804. if (value instanceof BABYLON.Vector2) {
  56805. return value.x + ", " + value.y;
  56806. }
  56807. if (value instanceof BABYLON.Vector3) {
  56808. return value.x + ", " + value.y + ", " + value.z;
  56809. }
  56810. if (value instanceof BABYLON.Color3) {
  56811. return value.r + ", " + value.g + ", " + value.b;
  56812. }
  56813. if (value instanceof BABYLON.Color4) {
  56814. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  56815. }
  56816. return value; // string
  56817. };
  56818. /**
  56819. * Internal only
  56820. * @hidden
  56821. */
  56822. Action._GetTargetProperty = function (target) {
  56823. return {
  56824. name: "target",
  56825. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  56826. : target instanceof BABYLON.Light ? "LightProperties"
  56827. : target instanceof BABYLON.Camera ? "CameraProperties"
  56828. : "SceneProperties",
  56829. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  56830. };
  56831. };
  56832. return Action;
  56833. }());
  56834. BABYLON.Action = Action;
  56835. })(BABYLON || (BABYLON = {}));
  56836. //# sourceMappingURL=babylon.action.js.map
  56837. var BABYLON;
  56838. (function (BABYLON) {
  56839. /**
  56840. * ActionEvent is the event being sent when an action is triggered.
  56841. */
  56842. var ActionEvent = /** @class */ (function () {
  56843. /**
  56844. * Creates a new ActionEvent
  56845. * @param source The mesh or sprite that triggered the action
  56846. * @param pointerX The X mouse cursor position at the time of the event
  56847. * @param pointerY The Y mouse cursor position at the time of the event
  56848. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  56849. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  56850. * @param additionalData additional data for the event
  56851. */
  56852. function ActionEvent(
  56853. /** The mesh or sprite that triggered the action */
  56854. source,
  56855. /** The X mouse cursor position at the time of the event */
  56856. pointerX,
  56857. /** The Y mouse cursor position at the time of the event */
  56858. pointerY,
  56859. /** The mesh that is currently pointed at (can be null) */
  56860. meshUnderPointer,
  56861. /** the original (browser) event that triggered the ActionEvent */
  56862. sourceEvent,
  56863. /** additional data for the event */
  56864. additionalData) {
  56865. this.source = source;
  56866. this.pointerX = pointerX;
  56867. this.pointerY = pointerY;
  56868. this.meshUnderPointer = meshUnderPointer;
  56869. this.sourceEvent = sourceEvent;
  56870. this.additionalData = additionalData;
  56871. }
  56872. /**
  56873. * Helper function to auto-create an ActionEvent from a source mesh.
  56874. * @param source The source mesh that triggered the event
  56875. * @param evt The original (browser) event
  56876. * @param additionalData additional data for the event
  56877. * @returns the new ActionEvent
  56878. */
  56879. ActionEvent.CreateNew = function (source, evt, additionalData) {
  56880. var scene = source.getScene();
  56881. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  56882. };
  56883. /**
  56884. * Helper function to auto-create an ActionEvent from a source sprite
  56885. * @param source The source sprite that triggered the event
  56886. * @param scene Scene associated with the sprite
  56887. * @param evt The original (browser) event
  56888. * @param additionalData additional data for the event
  56889. * @returns the new ActionEvent
  56890. */
  56891. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  56892. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  56893. };
  56894. /**
  56895. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  56896. * @param scene the scene where the event occurred
  56897. * @param evt The original (browser) event
  56898. * @returns the new ActionEvent
  56899. */
  56900. ActionEvent.CreateNewFromScene = function (scene, evt) {
  56901. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  56902. };
  56903. /**
  56904. * Helper function to auto-create an ActionEvent from a primitive
  56905. * @param prim defines the target primitive
  56906. * @param pointerPos defines the pointer position
  56907. * @param evt The original (browser) event
  56908. * @param additionalData additional data for the event
  56909. * @returns the new ActionEvent
  56910. */
  56911. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  56912. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  56913. };
  56914. return ActionEvent;
  56915. }());
  56916. BABYLON.ActionEvent = ActionEvent;
  56917. /**
  56918. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  56919. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  56920. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  56921. */
  56922. var ActionManager = /** @class */ (function () {
  56923. /**
  56924. * Creates a new action manager
  56925. * @param scene defines the hosting scene
  56926. */
  56927. function ActionManager(scene) {
  56928. // Members
  56929. /** Gets the list of actions */
  56930. this.actions = new Array();
  56931. /** Gets the cursor to use when hovering items */
  56932. this.hoverCursor = '';
  56933. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  56934. scene.actionManagers.push(this);
  56935. }
  56936. // Methods
  56937. /**
  56938. * Releases all associated resources
  56939. */
  56940. ActionManager.prototype.dispose = function () {
  56941. var index = this._scene.actionManagers.indexOf(this);
  56942. for (var i = 0; i < this.actions.length; i++) {
  56943. var action = this.actions[i];
  56944. ActionManager.Triggers[action.trigger]--;
  56945. if (ActionManager.Triggers[action.trigger] === 0) {
  56946. delete ActionManager.Triggers[action.trigger];
  56947. }
  56948. }
  56949. if (index > -1) {
  56950. this._scene.actionManagers.splice(index, 1);
  56951. }
  56952. };
  56953. /**
  56954. * Gets hosting scene
  56955. * @returns the hosting scene
  56956. */
  56957. ActionManager.prototype.getScene = function () {
  56958. return this._scene;
  56959. };
  56960. /**
  56961. * Does this action manager handles actions of any of the given triggers
  56962. * @param triggers defines the triggers to be tested
  56963. * @return a boolean indicating whether one (or more) of the triggers is handled
  56964. */
  56965. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  56966. for (var index = 0; index < this.actions.length; index++) {
  56967. var action = this.actions[index];
  56968. if (triggers.indexOf(action.trigger) > -1) {
  56969. return true;
  56970. }
  56971. }
  56972. return false;
  56973. };
  56974. /**
  56975. * Does this action manager handles actions of any of the given triggers. This function takes two arguments for
  56976. * speed.
  56977. * @param triggerA defines the trigger to be tested
  56978. * @param triggerB defines the trigger to be tested
  56979. * @return a boolean indicating whether one (or more) of the triggers is handled
  56980. */
  56981. ActionManager.prototype.hasSpecificTriggers2 = function (triggerA, triggerB) {
  56982. for (var index = 0; index < this.actions.length; index++) {
  56983. var action = this.actions[index];
  56984. if (triggerA == action.trigger || triggerB == action.trigger) {
  56985. return true;
  56986. }
  56987. }
  56988. return false;
  56989. };
  56990. /**
  56991. * Does this action manager handles actions of a given trigger
  56992. * @param trigger defines the trigger to be tested
  56993. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  56994. * @return whether the trigger is handled
  56995. */
  56996. ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
  56997. for (var index = 0; index < this.actions.length; index++) {
  56998. var action = this.actions[index];
  56999. if (action.trigger === trigger) {
  57000. if (parameterPredicate) {
  57001. if (parameterPredicate(action.getTriggerParameter())) {
  57002. return true;
  57003. }
  57004. }
  57005. else {
  57006. return true;
  57007. }
  57008. }
  57009. }
  57010. return false;
  57011. };
  57012. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  57013. /**
  57014. * Does this action manager has pointer triggers
  57015. */
  57016. get: function () {
  57017. for (var index = 0; index < this.actions.length; index++) {
  57018. var action = this.actions[index];
  57019. if (action.trigger >= ActionManager.OnPickTrigger && action.trigger <= ActionManager.OnPointerOutTrigger) {
  57020. return true;
  57021. }
  57022. }
  57023. return false;
  57024. },
  57025. enumerable: true,
  57026. configurable: true
  57027. });
  57028. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  57029. /**
  57030. * Does this action manager has pick triggers
  57031. */
  57032. get: function () {
  57033. for (var index = 0; index < this.actions.length; index++) {
  57034. var action = this.actions[index];
  57035. if (action.trigger >= ActionManager.OnPickTrigger && action.trigger <= ActionManager.OnPickUpTrigger) {
  57036. return true;
  57037. }
  57038. }
  57039. return false;
  57040. },
  57041. enumerable: true,
  57042. configurable: true
  57043. });
  57044. Object.defineProperty(ActionManager, "HasTriggers", {
  57045. /**
  57046. * Does exist one action manager with at least one trigger
  57047. **/
  57048. get: function () {
  57049. for (var t in ActionManager.Triggers) {
  57050. if (ActionManager.Triggers.hasOwnProperty(t)) {
  57051. return true;
  57052. }
  57053. }
  57054. return false;
  57055. },
  57056. enumerable: true,
  57057. configurable: true
  57058. });
  57059. Object.defineProperty(ActionManager, "HasPickTriggers", {
  57060. /**
  57061. * Does exist one action manager with at least one pick trigger
  57062. **/
  57063. get: function () {
  57064. for (var t in ActionManager.Triggers) {
  57065. if (ActionManager.Triggers.hasOwnProperty(t)) {
  57066. var t_int = parseInt(t);
  57067. if (t_int >= ActionManager.OnPickTrigger && t_int <= ActionManager.OnPickUpTrigger) {
  57068. return true;
  57069. }
  57070. }
  57071. }
  57072. return false;
  57073. },
  57074. enumerable: true,
  57075. configurable: true
  57076. });
  57077. /**
  57078. * Does exist one action manager that handles actions of a given trigger
  57079. * @param trigger defines the trigger to be tested
  57080. * @return a boolean indicating whether the trigger is handeled by at least one action manager
  57081. **/
  57082. ActionManager.HasSpecificTrigger = function (trigger) {
  57083. for (var t in ActionManager.Triggers) {
  57084. if (ActionManager.Triggers.hasOwnProperty(t)) {
  57085. var t_int = parseInt(t);
  57086. if (t_int === trigger) {
  57087. return true;
  57088. }
  57089. }
  57090. }
  57091. return false;
  57092. };
  57093. /**
  57094. * Registers an action to this action manager
  57095. * @param action defines the action to be registered
  57096. * @return the action amended (prepared) after registration
  57097. */
  57098. ActionManager.prototype.registerAction = function (action) {
  57099. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  57100. if (this.getScene().actionManager !== this) {
  57101. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  57102. return null;
  57103. }
  57104. }
  57105. this.actions.push(action);
  57106. if (ActionManager.Triggers[action.trigger]) {
  57107. ActionManager.Triggers[action.trigger]++;
  57108. }
  57109. else {
  57110. ActionManager.Triggers[action.trigger] = 1;
  57111. }
  57112. action._actionManager = this;
  57113. action._prepare();
  57114. return action;
  57115. };
  57116. /**
  57117. * Unregisters an action to this action manager
  57118. * @param action defines the action to be unregistered
  57119. * @return a boolean indicating whether the action has been unregistered
  57120. */
  57121. ActionManager.prototype.unregisterAction = function (action) {
  57122. var index = this.actions.indexOf(action);
  57123. if (index !== -1) {
  57124. this.actions.splice(index, 1);
  57125. ActionManager.Triggers[action.trigger] -= 1;
  57126. if (ActionManager.Triggers[action.trigger] === 0) {
  57127. delete ActionManager.Triggers[action.trigger];
  57128. }
  57129. delete action._actionManager;
  57130. return true;
  57131. }
  57132. return false;
  57133. };
  57134. /**
  57135. * Process a specific trigger
  57136. * @param trigger defines the trigger to process
  57137. * @param evt defines the event details to be processed
  57138. */
  57139. ActionManager.prototype.processTrigger = function (trigger, evt) {
  57140. for (var index = 0; index < this.actions.length; index++) {
  57141. var action = this.actions[index];
  57142. if (action.trigger === trigger) {
  57143. if (evt) {
  57144. if (trigger === ActionManager.OnKeyUpTrigger
  57145. || trigger === ActionManager.OnKeyDownTrigger) {
  57146. var parameter = action.getTriggerParameter();
  57147. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  57148. if (!parameter.toLowerCase) {
  57149. continue;
  57150. }
  57151. var lowerCase = parameter.toLowerCase();
  57152. if (lowerCase !== evt.sourceEvent.key) {
  57153. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  57154. var actualkey = String.fromCharCode(unicode).toLowerCase();
  57155. if (actualkey !== lowerCase) {
  57156. continue;
  57157. }
  57158. }
  57159. }
  57160. }
  57161. }
  57162. action._executeCurrent(evt);
  57163. }
  57164. }
  57165. };
  57166. /** @hidden */
  57167. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  57168. var properties = propertyPath.split(".");
  57169. for (var index = 0; index < properties.length - 1; index++) {
  57170. target = target[properties[index]];
  57171. }
  57172. return target;
  57173. };
  57174. /** @hidden */
  57175. ActionManager.prototype._getProperty = function (propertyPath) {
  57176. var properties = propertyPath.split(".");
  57177. return properties[properties.length - 1];
  57178. };
  57179. /**
  57180. * Serialize this manager to a JSON object
  57181. * @param name defines the property name to store this manager
  57182. * @returns a JSON representation of this manager
  57183. */
  57184. ActionManager.prototype.serialize = function (name) {
  57185. var root = {
  57186. children: new Array(),
  57187. name: name,
  57188. type: 3,
  57189. properties: new Array() // Empty for root but required
  57190. };
  57191. for (var i = 0; i < this.actions.length; i++) {
  57192. var triggerObject = {
  57193. type: 0,
  57194. children: new Array(),
  57195. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  57196. properties: new Array()
  57197. };
  57198. var triggerOptions = this.actions[i].triggerOptions;
  57199. if (triggerOptions && typeof triggerOptions !== "number") {
  57200. if (triggerOptions.parameter instanceof BABYLON.Node) {
  57201. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  57202. }
  57203. else {
  57204. var parameter = {};
  57205. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  57206. if (triggerOptions.parameter && triggerOptions.parameter.mesh) {
  57207. parameter._meshId = triggerOptions.parameter.mesh.id;
  57208. }
  57209. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  57210. }
  57211. }
  57212. // Serialize child action, recursively
  57213. this.actions[i].serialize(triggerObject);
  57214. // Add serialized trigger
  57215. root.children.push(triggerObject);
  57216. }
  57217. return root;
  57218. };
  57219. /**
  57220. * Creates a new ActionManager from a JSON data
  57221. * @param parsedActions defines the JSON data to read from
  57222. * @param object defines the hosting mesh
  57223. * @param scene defines the hosting scene
  57224. */
  57225. ActionManager.Parse = function (parsedActions, object, scene) {
  57226. var actionManager = new ActionManager(scene);
  57227. if (object === null) {
  57228. scene.actionManager = actionManager;
  57229. }
  57230. else {
  57231. object.actionManager = actionManager;
  57232. }
  57233. // instanciate a new object
  57234. var instanciate = function (name, params) {
  57235. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  57236. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  57237. newInstance.constructor.apply(newInstance, params);
  57238. return newInstance;
  57239. };
  57240. var parseParameter = function (name, value, target, propertyPath) {
  57241. if (propertyPath === null) {
  57242. // String, boolean or float
  57243. var floatValue = parseFloat(value);
  57244. if (value === "true" || value === "false") {
  57245. return value === "true";
  57246. }
  57247. else {
  57248. return isNaN(floatValue) ? value : floatValue;
  57249. }
  57250. }
  57251. var effectiveTarget = propertyPath.split(".");
  57252. var values = value.split(",");
  57253. // Get effective Target
  57254. for (var i = 0; i < effectiveTarget.length; i++) {
  57255. target = target[effectiveTarget[i]];
  57256. }
  57257. // Return appropriate value with its type
  57258. if (typeof (target) === "boolean") {
  57259. return values[0] === "true";
  57260. }
  57261. if (typeof (target) === "string") {
  57262. return values[0];
  57263. }
  57264. // Parameters with multiple values such as Vector3 etc.
  57265. var split = new Array();
  57266. for (var i = 0; i < values.length; i++) {
  57267. split.push(parseFloat(values[i]));
  57268. }
  57269. if (target instanceof BABYLON.Vector3) {
  57270. return BABYLON.Vector3.FromArray(split);
  57271. }
  57272. if (target instanceof BABYLON.Vector4) {
  57273. return BABYLON.Vector4.FromArray(split);
  57274. }
  57275. if (target instanceof BABYLON.Color3) {
  57276. return BABYLON.Color3.FromArray(split);
  57277. }
  57278. if (target instanceof BABYLON.Color4) {
  57279. return BABYLON.Color4.FromArray(split);
  57280. }
  57281. return parseFloat(values[0]);
  57282. };
  57283. // traverse graph per trigger
  57284. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  57285. if (combineArray === void 0) { combineArray = null; }
  57286. if (parsedAction.detached) {
  57287. return;
  57288. }
  57289. var parameters = new Array();
  57290. var target = null;
  57291. var propertyPath = null;
  57292. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  57293. // Parameters
  57294. if (parsedAction.type === 2) {
  57295. parameters.push(actionManager);
  57296. }
  57297. else {
  57298. parameters.push(trigger);
  57299. }
  57300. if (combine) {
  57301. var actions = new Array();
  57302. for (var j = 0; j < parsedAction.combine.length; j++) {
  57303. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  57304. }
  57305. parameters.push(actions);
  57306. }
  57307. else {
  57308. for (var i = 0; i < parsedAction.properties.length; i++) {
  57309. var value = parsedAction.properties[i].value;
  57310. var name = parsedAction.properties[i].name;
  57311. var targetType = parsedAction.properties[i].targetType;
  57312. if (name === "target") {
  57313. if (targetType !== null && targetType === "SceneProperties") {
  57314. value = target = scene;
  57315. }
  57316. else {
  57317. value = target = scene.getNodeByName(value);
  57318. }
  57319. }
  57320. else if (name === "parent") {
  57321. value = scene.getNodeByName(value);
  57322. }
  57323. else if (name === "sound") {
  57324. // Can not externalize to component, so only checks for the presence off the API.
  57325. if (scene.getSoundByName) {
  57326. value = scene.getSoundByName(value);
  57327. }
  57328. }
  57329. else if (name !== "propertyPath") {
  57330. if (parsedAction.type === 2 && name === "operator") {
  57331. value = BABYLON.ValueCondition[value];
  57332. }
  57333. else {
  57334. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  57335. }
  57336. }
  57337. else {
  57338. propertyPath = value;
  57339. }
  57340. parameters.push(value);
  57341. }
  57342. }
  57343. if (combineArray === null) {
  57344. parameters.push(condition);
  57345. }
  57346. else {
  57347. parameters.push(null);
  57348. }
  57349. // If interpolate value action
  57350. if (parsedAction.name === "InterpolateValueAction") {
  57351. var param = parameters[parameters.length - 2];
  57352. parameters[parameters.length - 1] = param;
  57353. parameters[parameters.length - 2] = condition;
  57354. }
  57355. // Action or condition(s) and not CombineAction
  57356. var newAction = instanciate(parsedAction.name, parameters);
  57357. if (newAction instanceof BABYLON.Condition && condition !== null) {
  57358. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  57359. if (action) {
  57360. action.then(nothing);
  57361. }
  57362. else {
  57363. actionManager.registerAction(nothing);
  57364. }
  57365. action = nothing;
  57366. }
  57367. if (combineArray === null) {
  57368. if (newAction instanceof BABYLON.Condition) {
  57369. condition = newAction;
  57370. newAction = action;
  57371. }
  57372. else {
  57373. condition = null;
  57374. if (action) {
  57375. action.then(newAction);
  57376. }
  57377. else {
  57378. actionManager.registerAction(newAction);
  57379. }
  57380. }
  57381. }
  57382. else {
  57383. combineArray.push(newAction);
  57384. }
  57385. for (var i = 0; i < parsedAction.children.length; i++) {
  57386. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  57387. }
  57388. };
  57389. // triggers
  57390. for (var i = 0; i < parsedActions.children.length; i++) {
  57391. var triggerParams;
  57392. var trigger = parsedActions.children[i];
  57393. if (trigger.properties.length > 0) {
  57394. var param = trigger.properties[0].value;
  57395. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  57396. if (value._meshId) {
  57397. value.mesh = scene.getMeshByID(value._meshId);
  57398. }
  57399. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  57400. }
  57401. else {
  57402. triggerParams = ActionManager[trigger.name];
  57403. }
  57404. for (var j = 0; j < trigger.children.length; j++) {
  57405. if (!trigger.detached) {
  57406. traverse(trigger.children[j], triggerParams, null, null);
  57407. }
  57408. }
  57409. }
  57410. };
  57411. /**
  57412. * Get a trigger name by index
  57413. * @param trigger defines the trigger index
  57414. * @returns a trigger name
  57415. */
  57416. ActionManager.GetTriggerName = function (trigger) {
  57417. switch (trigger) {
  57418. case 0: return "NothingTrigger";
  57419. case 1: return "OnPickTrigger";
  57420. case 2: return "OnLeftPickTrigger";
  57421. case 3: return "OnRightPickTrigger";
  57422. case 4: return "OnCenterPickTrigger";
  57423. case 5: return "OnPickDownTrigger";
  57424. case 6: return "OnPickUpTrigger";
  57425. case 7: return "OnLongPressTrigger";
  57426. case 8: return "OnPointerOverTrigger";
  57427. case 9: return "OnPointerOutTrigger";
  57428. case 10: return "OnEveryFrameTrigger";
  57429. case 11: return "OnIntersectionEnterTrigger";
  57430. case 12: return "OnIntersectionExitTrigger";
  57431. case 13: return "OnKeyDownTrigger";
  57432. case 14: return "OnKeyUpTrigger";
  57433. case 15: return "OnPickOutTrigger";
  57434. default: return "";
  57435. }
  57436. };
  57437. /**
  57438. * Nothing
  57439. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  57440. */
  57441. ActionManager.NothingTrigger = 0;
  57442. /**
  57443. * On pick
  57444. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  57445. */
  57446. ActionManager.OnPickTrigger = 1;
  57447. /**
  57448. * On left pick
  57449. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  57450. */
  57451. ActionManager.OnLeftPickTrigger = 2;
  57452. /**
  57453. * On right pick
  57454. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  57455. */
  57456. ActionManager.OnRightPickTrigger = 3;
  57457. /**
  57458. * On center pick
  57459. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  57460. */
  57461. ActionManager.OnCenterPickTrigger = 4;
  57462. /**
  57463. * On pick down
  57464. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  57465. */
  57466. ActionManager.OnPickDownTrigger = 5;
  57467. /**
  57468. * On double pick
  57469. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  57470. */
  57471. ActionManager.OnDoublePickTrigger = 6;
  57472. /**
  57473. * On pick up
  57474. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  57475. */
  57476. ActionManager.OnPickUpTrigger = 7;
  57477. /**
  57478. * On pick out.
  57479. * This trigger will only be raised if you also declared a OnPickDown
  57480. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  57481. */
  57482. ActionManager.OnPickOutTrigger = 16;
  57483. /**
  57484. * On long press
  57485. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  57486. */
  57487. ActionManager.OnLongPressTrigger = 8;
  57488. /**
  57489. * On pointer over
  57490. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  57491. */
  57492. ActionManager.OnPointerOverTrigger = 9;
  57493. /**
  57494. * On pointer out
  57495. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  57496. */
  57497. ActionManager.OnPointerOutTrigger = 10;
  57498. /**
  57499. * On every frame
  57500. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  57501. */
  57502. ActionManager.OnEveryFrameTrigger = 11;
  57503. /**
  57504. * On intersection enter
  57505. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  57506. */
  57507. ActionManager.OnIntersectionEnterTrigger = 12;
  57508. /**
  57509. * On intersection exit
  57510. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  57511. */
  57512. ActionManager.OnIntersectionExitTrigger = 13;
  57513. /**
  57514. * On key down
  57515. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  57516. */
  57517. ActionManager.OnKeyDownTrigger = 14;
  57518. /**
  57519. * On key up
  57520. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  57521. */
  57522. ActionManager.OnKeyUpTrigger = 15;
  57523. /** Gets the list of active triggers */
  57524. ActionManager.Triggers = {};
  57525. return ActionManager;
  57526. }());
  57527. BABYLON.ActionManager = ActionManager;
  57528. })(BABYLON || (BABYLON = {}));
  57529. //# sourceMappingURL=babylon.actionManager.js.map
  57530. var BABYLON;
  57531. (function (BABYLON) {
  57532. /**
  57533. * This defines an action responsible to change the value of a property
  57534. * by interpolating between its current value and the newly set one once triggered.
  57535. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  57536. */
  57537. var InterpolateValueAction = /** @class */ (function (_super) {
  57538. __extends(InterpolateValueAction, _super);
  57539. /**
  57540. * Instantiate the action
  57541. * @param triggerOptions defines the trigger options
  57542. * @param target defines the object containing the value to interpolate
  57543. * @param propertyPath defines the path to the property in the target object
  57544. * @param value defines the target value at the end of the interpolation
  57545. * @param duration deines the time it will take for the property to interpolate to the value.
  57546. * @param condition defines the trigger related conditions
  57547. * @param stopOtherAnimations defines if the other scene animations should be stopped when the action has been triggered
  57548. * @param onInterpolationDone defines a callback raised once the interpolation animation has been done
  57549. */
  57550. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  57551. if (duration === void 0) { duration = 1000; }
  57552. var _this = _super.call(this, triggerOptions, condition) || this;
  57553. /**
  57554. * Defines the time it will take for the property to interpolate to the value.
  57555. */
  57556. _this.duration = 1000;
  57557. /**
  57558. * Observable triggered once the interpolation animation has been done.
  57559. */
  57560. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  57561. _this.propertyPath = propertyPath;
  57562. _this.value = value;
  57563. _this.duration = duration;
  57564. _this.stopOtherAnimations = stopOtherAnimations;
  57565. _this.onInterpolationDone = onInterpolationDone;
  57566. _this._target = _this._effectiveTarget = target;
  57567. return _this;
  57568. }
  57569. /** @hidden */
  57570. InterpolateValueAction.prototype._prepare = function () {
  57571. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  57572. this._property = this._getProperty(this.propertyPath);
  57573. };
  57574. /**
  57575. * Execute the action starts the value interpolation.
  57576. */
  57577. InterpolateValueAction.prototype.execute = function () {
  57578. var _this = this;
  57579. var scene = this._actionManager.getScene();
  57580. var keys = [
  57581. {
  57582. frame: 0,
  57583. value: this._effectiveTarget[this._property]
  57584. }, {
  57585. frame: 100,
  57586. value: this.value
  57587. }
  57588. ];
  57589. var dataType;
  57590. if (typeof this.value === "number") {
  57591. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  57592. }
  57593. else if (this.value instanceof BABYLON.Color3) {
  57594. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  57595. }
  57596. else if (this.value instanceof BABYLON.Vector3) {
  57597. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  57598. }
  57599. else if (this.value instanceof BABYLON.Matrix) {
  57600. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  57601. }
  57602. else if (this.value instanceof BABYLON.Quaternion) {
  57603. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  57604. }
  57605. else {
  57606. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  57607. return;
  57608. }
  57609. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  57610. animation.setKeys(keys);
  57611. if (this.stopOtherAnimations) {
  57612. scene.stopAnimation(this._effectiveTarget);
  57613. }
  57614. var wrapper = function () {
  57615. _this.onInterpolationDoneObservable.notifyObservers(_this);
  57616. if (_this.onInterpolationDone) {
  57617. _this.onInterpolationDone();
  57618. }
  57619. };
  57620. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  57621. };
  57622. /**
  57623. * Serializes the actions and its related information.
  57624. * @param parent defines the object to serialize in
  57625. * @returns the serialized object
  57626. */
  57627. InterpolateValueAction.prototype.serialize = function (parent) {
  57628. return _super.prototype._serialize.call(this, {
  57629. name: "InterpolateValueAction",
  57630. properties: [
  57631. BABYLON.Action._GetTargetProperty(this._target),
  57632. { name: "propertyPath", value: this.propertyPath },
  57633. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  57634. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  57635. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  57636. ]
  57637. }, parent);
  57638. };
  57639. return InterpolateValueAction;
  57640. }(BABYLON.Action));
  57641. BABYLON.InterpolateValueAction = InterpolateValueAction;
  57642. })(BABYLON || (BABYLON = {}));
  57643. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  57644. var BABYLON;
  57645. (function (BABYLON) {
  57646. /**
  57647. * This defines an action responsible to toggle a boolean once triggered.
  57648. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  57649. */
  57650. var SwitchBooleanAction = /** @class */ (function (_super) {
  57651. __extends(SwitchBooleanAction, _super);
  57652. /**
  57653. * Instantiate the action
  57654. * @param triggerOptions defines the trigger options
  57655. * @param target defines the object containing the boolean
  57656. * @param propertyPath defines the path to the boolean property in the target object
  57657. * @param condition defines the trigger related conditions
  57658. */
  57659. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  57660. var _this = _super.call(this, triggerOptions, condition) || this;
  57661. _this.propertyPath = propertyPath;
  57662. _this._target = _this._effectiveTarget = target;
  57663. return _this;
  57664. }
  57665. /** @hidden */
  57666. SwitchBooleanAction.prototype._prepare = function () {
  57667. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  57668. this._property = this._getProperty(this.propertyPath);
  57669. };
  57670. /**
  57671. * Execute the action toggle the boolean value.
  57672. */
  57673. SwitchBooleanAction.prototype.execute = function () {
  57674. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  57675. };
  57676. /**
  57677. * Serializes the actions and its related information.
  57678. * @param parent defines the object to serialize in
  57679. * @returns the serialized object
  57680. */
  57681. SwitchBooleanAction.prototype.serialize = function (parent) {
  57682. return _super.prototype._serialize.call(this, {
  57683. name: "SwitchBooleanAction",
  57684. properties: [
  57685. BABYLON.Action._GetTargetProperty(this._target),
  57686. { name: "propertyPath", value: this.propertyPath }
  57687. ]
  57688. }, parent);
  57689. };
  57690. return SwitchBooleanAction;
  57691. }(BABYLON.Action));
  57692. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  57693. /**
  57694. * This defines an action responsible to set a the state field of the target
  57695. * to a desired value once triggered.
  57696. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  57697. */
  57698. var SetStateAction = /** @class */ (function (_super) {
  57699. __extends(SetStateAction, _super);
  57700. /**
  57701. * Instantiate the action
  57702. * @param triggerOptions defines the trigger options
  57703. * @param target defines the object containing the state property
  57704. * @param value defines the value to store in the state field
  57705. * @param condition defines the trigger related conditions
  57706. */
  57707. function SetStateAction(triggerOptions, target, value, condition) {
  57708. var _this = _super.call(this, triggerOptions, condition) || this;
  57709. _this.value = value;
  57710. _this._target = target;
  57711. return _this;
  57712. }
  57713. /**
  57714. * Execute the action and store the value on the target state property.
  57715. */
  57716. SetStateAction.prototype.execute = function () {
  57717. this._target.state = this.value;
  57718. };
  57719. /**
  57720. * Serializes the actions and its related information.
  57721. * @param parent defines the object to serialize in
  57722. * @returns the serialized object
  57723. */
  57724. SetStateAction.prototype.serialize = function (parent) {
  57725. return _super.prototype._serialize.call(this, {
  57726. name: "SetStateAction",
  57727. properties: [
  57728. BABYLON.Action._GetTargetProperty(this._target),
  57729. { name: "value", value: this.value }
  57730. ]
  57731. }, parent);
  57732. };
  57733. return SetStateAction;
  57734. }(BABYLON.Action));
  57735. BABYLON.SetStateAction = SetStateAction;
  57736. /**
  57737. * This defines an action responsible to set a property of the target
  57738. * to a desired value once triggered.
  57739. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  57740. */
  57741. var SetValueAction = /** @class */ (function (_super) {
  57742. __extends(SetValueAction, _super);
  57743. /**
  57744. * Instantiate the action
  57745. * @param triggerOptions defines the trigger options
  57746. * @param target defines the object containing the property
  57747. * @param propertyPath defines the path of the property to set in the target
  57748. * @param value defines the value to set in the property
  57749. * @param condition defines the trigger related conditions
  57750. */
  57751. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  57752. var _this = _super.call(this, triggerOptions, condition) || this;
  57753. _this.propertyPath = propertyPath;
  57754. _this.value = value;
  57755. _this._target = _this._effectiveTarget = target;
  57756. return _this;
  57757. }
  57758. /** @hidden */
  57759. SetValueAction.prototype._prepare = function () {
  57760. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  57761. this._property = this._getProperty(this.propertyPath);
  57762. };
  57763. /**
  57764. * Execute the action and set the targetted property to the desired value.
  57765. */
  57766. SetValueAction.prototype.execute = function () {
  57767. this._effectiveTarget[this._property] = this.value;
  57768. if (this._target.markAsDirty) {
  57769. this._target.markAsDirty(this._property);
  57770. }
  57771. };
  57772. /**
  57773. * Serializes the actions and its related information.
  57774. * @param parent defines the object to serialize in
  57775. * @returns the serialized object
  57776. */
  57777. SetValueAction.prototype.serialize = function (parent) {
  57778. return _super.prototype._serialize.call(this, {
  57779. name: "SetValueAction",
  57780. properties: [
  57781. BABYLON.Action._GetTargetProperty(this._target),
  57782. { name: "propertyPath", value: this.propertyPath },
  57783. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  57784. ]
  57785. }, parent);
  57786. };
  57787. return SetValueAction;
  57788. }(BABYLON.Action));
  57789. BABYLON.SetValueAction = SetValueAction;
  57790. /**
  57791. * This defines an action responsible to increment the target value
  57792. * to a desired value once triggered.
  57793. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  57794. */
  57795. var IncrementValueAction = /** @class */ (function (_super) {
  57796. __extends(IncrementValueAction, _super);
  57797. /**
  57798. * Instantiate the action
  57799. * @param triggerOptions defines the trigger options
  57800. * @param target defines the object containing the property
  57801. * @param propertyPath defines the path of the property to increment in the target
  57802. * @param value defines the value value we should increment the property by
  57803. * @param condition defines the trigger related conditions
  57804. */
  57805. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  57806. var _this = _super.call(this, triggerOptions, condition) || this;
  57807. _this.propertyPath = propertyPath;
  57808. _this.value = value;
  57809. _this._target = _this._effectiveTarget = target;
  57810. return _this;
  57811. }
  57812. /** @hidden */
  57813. IncrementValueAction.prototype._prepare = function () {
  57814. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  57815. this._property = this._getProperty(this.propertyPath);
  57816. if (typeof this._effectiveTarget[this._property] !== "number") {
  57817. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  57818. }
  57819. };
  57820. /**
  57821. * Execute the action and increment the target of the value amount.
  57822. */
  57823. IncrementValueAction.prototype.execute = function () {
  57824. this._effectiveTarget[this._property] += this.value;
  57825. if (this._target.markAsDirty) {
  57826. this._target.markAsDirty(this._property);
  57827. }
  57828. };
  57829. /**
  57830. * Serializes the actions and its related information.
  57831. * @param parent defines the object to serialize in
  57832. * @returns the serialized object
  57833. */
  57834. IncrementValueAction.prototype.serialize = function (parent) {
  57835. return _super.prototype._serialize.call(this, {
  57836. name: "IncrementValueAction",
  57837. properties: [
  57838. BABYLON.Action._GetTargetProperty(this._target),
  57839. { name: "propertyPath", value: this.propertyPath },
  57840. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  57841. ]
  57842. }, parent);
  57843. };
  57844. return IncrementValueAction;
  57845. }(BABYLON.Action));
  57846. BABYLON.IncrementValueAction = IncrementValueAction;
  57847. /**
  57848. * This defines an action responsible to start an animation once triggered.
  57849. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  57850. */
  57851. var PlayAnimationAction = /** @class */ (function (_super) {
  57852. __extends(PlayAnimationAction, _super);
  57853. /**
  57854. * Instantiate the action
  57855. * @param triggerOptions defines the trigger options
  57856. * @param target defines the target animation or animation name
  57857. * @param from defines from where the animation should start (animation frame)
  57858. * @param end defines where the animation should stop (animation frame)
  57859. * @param loop defines if the animation should loop or stop after the first play
  57860. * @param condition defines the trigger related conditions
  57861. */
  57862. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  57863. var _this = _super.call(this, triggerOptions, condition) || this;
  57864. _this.from = from;
  57865. _this.to = to;
  57866. _this.loop = loop;
  57867. _this._target = target;
  57868. return _this;
  57869. }
  57870. /** @hidden */
  57871. PlayAnimationAction.prototype._prepare = function () {
  57872. };
  57873. /**
  57874. * Execute the action and play the animation.
  57875. */
  57876. PlayAnimationAction.prototype.execute = function () {
  57877. var scene = this._actionManager.getScene();
  57878. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  57879. };
  57880. /**
  57881. * Serializes the actions and its related information.
  57882. * @param parent defines the object to serialize in
  57883. * @returns the serialized object
  57884. */
  57885. PlayAnimationAction.prototype.serialize = function (parent) {
  57886. return _super.prototype._serialize.call(this, {
  57887. name: "PlayAnimationAction",
  57888. properties: [
  57889. BABYLON.Action._GetTargetProperty(this._target),
  57890. { name: "from", value: String(this.from) },
  57891. { name: "to", value: String(this.to) },
  57892. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  57893. ]
  57894. }, parent);
  57895. };
  57896. return PlayAnimationAction;
  57897. }(BABYLON.Action));
  57898. BABYLON.PlayAnimationAction = PlayAnimationAction;
  57899. /**
  57900. * This defines an action responsible to stop an animation once triggered.
  57901. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  57902. */
  57903. var StopAnimationAction = /** @class */ (function (_super) {
  57904. __extends(StopAnimationAction, _super);
  57905. /**
  57906. * Instantiate the action
  57907. * @param triggerOptions defines the trigger options
  57908. * @param target defines the target animation or animation name
  57909. * @param condition defines the trigger related conditions
  57910. */
  57911. function StopAnimationAction(triggerOptions, target, condition) {
  57912. var _this = _super.call(this, triggerOptions, condition) || this;
  57913. _this._target = target;
  57914. return _this;
  57915. }
  57916. /** @hidden */
  57917. StopAnimationAction.prototype._prepare = function () {
  57918. };
  57919. /**
  57920. * Execute the action and stop the animation.
  57921. */
  57922. StopAnimationAction.prototype.execute = function () {
  57923. var scene = this._actionManager.getScene();
  57924. scene.stopAnimation(this._target);
  57925. };
  57926. /**
  57927. * Serializes the actions and its related information.
  57928. * @param parent defines the object to serialize in
  57929. * @returns the serialized object
  57930. */
  57931. StopAnimationAction.prototype.serialize = function (parent) {
  57932. return _super.prototype._serialize.call(this, {
  57933. name: "StopAnimationAction",
  57934. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  57935. }, parent);
  57936. };
  57937. return StopAnimationAction;
  57938. }(BABYLON.Action));
  57939. BABYLON.StopAnimationAction = StopAnimationAction;
  57940. /**
  57941. * This defines an action responsible that does nothing once triggered.
  57942. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  57943. */
  57944. var DoNothingAction = /** @class */ (function (_super) {
  57945. __extends(DoNothingAction, _super);
  57946. /**
  57947. * Instantiate the action
  57948. * @param triggerOptions defines the trigger options
  57949. * @param condition defines the trigger related conditions
  57950. */
  57951. function DoNothingAction(triggerOptions, condition) {
  57952. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  57953. return _super.call(this, triggerOptions, condition) || this;
  57954. }
  57955. /**
  57956. * Execute the action and do nothing.
  57957. */
  57958. DoNothingAction.prototype.execute = function () {
  57959. };
  57960. /**
  57961. * Serializes the actions and its related information.
  57962. * @param parent defines the object to serialize in
  57963. * @returns the serialized object
  57964. */
  57965. DoNothingAction.prototype.serialize = function (parent) {
  57966. return _super.prototype._serialize.call(this, {
  57967. name: "DoNothingAction",
  57968. properties: []
  57969. }, parent);
  57970. };
  57971. return DoNothingAction;
  57972. }(BABYLON.Action));
  57973. BABYLON.DoNothingAction = DoNothingAction;
  57974. /**
  57975. * This defines an action responsible to trigger several actions once triggered.
  57976. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  57977. */
  57978. var CombineAction = /** @class */ (function (_super) {
  57979. __extends(CombineAction, _super);
  57980. /**
  57981. * Instantiate the action
  57982. * @param triggerOptions defines the trigger options
  57983. * @param children defines the list of aggregated animations to run
  57984. * @param condition defines the trigger related conditions
  57985. */
  57986. function CombineAction(triggerOptions, children, condition) {
  57987. var _this = _super.call(this, triggerOptions, condition) || this;
  57988. _this.children = children;
  57989. return _this;
  57990. }
  57991. /** @hidden */
  57992. CombineAction.prototype._prepare = function () {
  57993. for (var index = 0; index < this.children.length; index++) {
  57994. this.children[index]._actionManager = this._actionManager;
  57995. this.children[index]._prepare();
  57996. }
  57997. };
  57998. /**
  57999. * Execute the action and executes all the aggregated actions.
  58000. */
  58001. CombineAction.prototype.execute = function (evt) {
  58002. for (var index = 0; index < this.children.length; index++) {
  58003. this.children[index].execute(evt);
  58004. }
  58005. };
  58006. /**
  58007. * Serializes the actions and its related information.
  58008. * @param parent defines the object to serialize in
  58009. * @returns the serialized object
  58010. */
  58011. CombineAction.prototype.serialize = function (parent) {
  58012. var serializationObject = _super.prototype._serialize.call(this, {
  58013. name: "CombineAction",
  58014. properties: [],
  58015. combine: []
  58016. }, parent);
  58017. for (var i = 0; i < this.children.length; i++) {
  58018. serializationObject.combine.push(this.children[i].serialize(null));
  58019. }
  58020. return serializationObject;
  58021. };
  58022. return CombineAction;
  58023. }(BABYLON.Action));
  58024. BABYLON.CombineAction = CombineAction;
  58025. /**
  58026. * This defines an action responsible to run code (external event) once triggered.
  58027. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  58028. */
  58029. var ExecuteCodeAction = /** @class */ (function (_super) {
  58030. __extends(ExecuteCodeAction, _super);
  58031. /**
  58032. * Instantiate the action
  58033. * @param triggerOptions defines the trigger options
  58034. * @param func defines the callback function to run
  58035. * @param condition defines the trigger related conditions
  58036. */
  58037. function ExecuteCodeAction(triggerOptions, func, condition) {
  58038. var _this = _super.call(this, triggerOptions, condition) || this;
  58039. _this.func = func;
  58040. return _this;
  58041. }
  58042. /**
  58043. * Execute the action and run the attached code.
  58044. */
  58045. ExecuteCodeAction.prototype.execute = function (evt) {
  58046. this.func(evt);
  58047. };
  58048. return ExecuteCodeAction;
  58049. }(BABYLON.Action));
  58050. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  58051. /**
  58052. * This defines an action responsible to set the parent property of the target once triggered.
  58053. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  58054. */
  58055. var SetParentAction = /** @class */ (function (_super) {
  58056. __extends(SetParentAction, _super);
  58057. /**
  58058. * Instantiate the action
  58059. * @param triggerOptions defines the trigger options
  58060. * @param target defines the target containing the parent property
  58061. * @param parent defines from where the animation should start (animation frame)
  58062. * @param condition defines the trigger related conditions
  58063. */
  58064. function SetParentAction(triggerOptions, target, parent, condition) {
  58065. var _this = _super.call(this, triggerOptions, condition) || this;
  58066. _this._target = target;
  58067. _this._parent = parent;
  58068. return _this;
  58069. }
  58070. /** @hidden */
  58071. SetParentAction.prototype._prepare = function () {
  58072. };
  58073. /**
  58074. * Execute the action and set the parent property.
  58075. */
  58076. SetParentAction.prototype.execute = function () {
  58077. if (this._target.parent === this._parent) {
  58078. return;
  58079. }
  58080. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  58081. invertParentWorldMatrix.invert();
  58082. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  58083. this._target.parent = this._parent;
  58084. };
  58085. /**
  58086. * Serializes the actions and its related information.
  58087. * @param parent defines the object to serialize in
  58088. * @returns the serialized object
  58089. */
  58090. SetParentAction.prototype.serialize = function (parent) {
  58091. return _super.prototype._serialize.call(this, {
  58092. name: "SetParentAction",
  58093. properties: [
  58094. BABYLON.Action._GetTargetProperty(this._target),
  58095. BABYLON.Action._GetTargetProperty(this._parent),
  58096. ]
  58097. }, parent);
  58098. };
  58099. return SetParentAction;
  58100. }(BABYLON.Action));
  58101. BABYLON.SetParentAction = SetParentAction;
  58102. })(BABYLON || (BABYLON = {}));
  58103. //# sourceMappingURL=babylon.directActions.js.map
  58104. var BABYLON;
  58105. (function (BABYLON) {
  58106. /**
  58107. * Class used to manage multiple sprites on the same spritesheet
  58108. * @see http://doc.babylonjs.com/babylon101/sprites
  58109. */
  58110. var SpriteManager = /** @class */ (function () {
  58111. /**
  58112. * Creates a new sprite manager
  58113. * @param name defines the manager's name
  58114. * @param imgUrl defines the sprite sheet url
  58115. * @param capacity defines the maximum allowed number of sprites
  58116. * @param cellSize defines the size of a sprite cell
  58117. * @param scene defines the hosting scene
  58118. * @param epsilon defines the epsilon value to align texture (0.01 by default)
  58119. * @param samplingMode defines the smapling mode to use with spritesheet
  58120. */
  58121. function SpriteManager(
  58122. /** defines the manager's name */
  58123. name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  58124. if (epsilon === void 0) { epsilon = 0.01; }
  58125. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58126. this.name = name;
  58127. /** Gets the list of sprites */
  58128. this.sprites = new Array();
  58129. /** Gets or sets the rendering group id (0 by default) */
  58130. this.renderingGroupId = 0;
  58131. /** Gets or sets camera layer mask */
  58132. this.layerMask = 0x0FFFFFFF;
  58133. /** Gets or sets a boolean indicating if the manager must consider scene fog when rendering */
  58134. this.fogEnabled = true;
  58135. /** Gets or sets a boolean indicating if the sprites are pickable */
  58136. this.isPickable = false;
  58137. /**
  58138. * An event triggered when the manager is disposed.
  58139. */
  58140. this.onDisposeObservable = new BABYLON.Observable();
  58141. this._vertexBuffers = {};
  58142. if (!scene._getComponent(BABYLON.SceneComponentConstants.NAME_SPRITE)) {
  58143. scene._addComponent(new BABYLON.SpriteSceneComponent(scene));
  58144. }
  58145. this._capacity = capacity;
  58146. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  58147. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58148. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58149. if (cellSize.width && cellSize.height) {
  58150. this.cellWidth = cellSize.width;
  58151. this.cellHeight = cellSize.height;
  58152. }
  58153. else if (cellSize !== undefined) {
  58154. this.cellWidth = cellSize;
  58155. this.cellHeight = cellSize;
  58156. }
  58157. else {
  58158. return;
  58159. }
  58160. this._epsilon = epsilon;
  58161. this._scene = scene;
  58162. this._scene.spriteManagers.push(this);
  58163. var indices = [];
  58164. var index = 0;
  58165. for (var count = 0; count < capacity; count++) {
  58166. indices.push(index);
  58167. indices.push(index + 1);
  58168. indices.push(index + 2);
  58169. indices.push(index);
  58170. indices.push(index + 2);
  58171. indices.push(index + 3);
  58172. index += 4;
  58173. }
  58174. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  58175. // VBO
  58176. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  58177. this._vertexData = new Float32Array(capacity * 16 * 4);
  58178. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  58179. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  58180. var options = this._buffer.createVertexBuffer("options", 4, 4);
  58181. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  58182. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  58183. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  58184. this._vertexBuffers["options"] = options;
  58185. this._vertexBuffers["cellInfo"] = cellInfo;
  58186. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  58187. // Effects
  58188. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  58189. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  58190. }
  58191. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  58192. /**
  58193. * Callback called when the manager is disposed
  58194. */
  58195. set: function (callback) {
  58196. if (this._onDisposeObserver) {
  58197. this.onDisposeObservable.remove(this._onDisposeObserver);
  58198. }
  58199. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  58200. },
  58201. enumerable: true,
  58202. configurable: true
  58203. });
  58204. Object.defineProperty(SpriteManager.prototype, "texture", {
  58205. /**
  58206. * Gets or sets the spritesheet texture
  58207. */
  58208. get: function () {
  58209. return this._spriteTexture;
  58210. },
  58211. set: function (value) {
  58212. this._spriteTexture = value;
  58213. },
  58214. enumerable: true,
  58215. configurable: true
  58216. });
  58217. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  58218. var arrayOffset = index * 16;
  58219. if (offsetX === 0) {
  58220. offsetX = this._epsilon;
  58221. }
  58222. else if (offsetX === 1) {
  58223. offsetX = 1 - this._epsilon;
  58224. }
  58225. if (offsetY === 0) {
  58226. offsetY = this._epsilon;
  58227. }
  58228. else if (offsetY === 1) {
  58229. offsetY = 1 - this._epsilon;
  58230. }
  58231. this._vertexData[arrayOffset] = sprite.position.x;
  58232. this._vertexData[arrayOffset + 1] = sprite.position.y;
  58233. this._vertexData[arrayOffset + 2] = sprite.position.z;
  58234. this._vertexData[arrayOffset + 3] = sprite.angle;
  58235. this._vertexData[arrayOffset + 4] = sprite.width;
  58236. this._vertexData[arrayOffset + 5] = sprite.height;
  58237. this._vertexData[arrayOffset + 6] = offsetX;
  58238. this._vertexData[arrayOffset + 7] = offsetY;
  58239. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  58240. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  58241. var offset = (sprite.cellIndex / rowSize) >> 0;
  58242. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  58243. this._vertexData[arrayOffset + 11] = offset;
  58244. // Color
  58245. this._vertexData[arrayOffset + 12] = sprite.color.r;
  58246. this._vertexData[arrayOffset + 13] = sprite.color.g;
  58247. this._vertexData[arrayOffset + 14] = sprite.color.b;
  58248. this._vertexData[arrayOffset + 15] = sprite.color.a;
  58249. };
  58250. /**
  58251. * Intersects the sprites with a ray
  58252. * @param ray defines the ray to intersect with
  58253. * @param camera defines the current active camera
  58254. * @param predicate defines a predicate used to select candidate sprites
  58255. * @param fastCheck defines if a fast check only must be done (the first potential sprite is will be used and not the closer)
  58256. * @returns null if no hit or a PickingInfo
  58257. */
  58258. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  58259. var count = Math.min(this._capacity, this.sprites.length);
  58260. var min = BABYLON.Vector3.Zero();
  58261. var max = BABYLON.Vector3.Zero();
  58262. var distance = Number.MAX_VALUE;
  58263. var currentSprite = null;
  58264. var cameraSpacePosition = BABYLON.Vector3.Zero();
  58265. var cameraView = camera.getViewMatrix();
  58266. for (var index = 0; index < count; index++) {
  58267. var sprite = this.sprites[index];
  58268. if (!sprite) {
  58269. continue;
  58270. }
  58271. if (predicate) {
  58272. if (!predicate(sprite)) {
  58273. continue;
  58274. }
  58275. }
  58276. else if (!sprite.isPickable) {
  58277. continue;
  58278. }
  58279. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  58280. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  58281. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  58282. if (ray.intersectsBoxMinMax(min, max)) {
  58283. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  58284. if (distance > currentDistance) {
  58285. distance = currentDistance;
  58286. currentSprite = sprite;
  58287. if (fastCheck) {
  58288. break;
  58289. }
  58290. }
  58291. }
  58292. }
  58293. if (currentSprite) {
  58294. var result = new BABYLON.PickingInfo();
  58295. result.hit = true;
  58296. result.pickedSprite = currentSprite;
  58297. result.distance = distance;
  58298. return result;
  58299. }
  58300. return null;
  58301. };
  58302. /**
  58303. * Render all child sprites
  58304. */
  58305. SpriteManager.prototype.render = function () {
  58306. // Check
  58307. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady()) {
  58308. return;
  58309. }
  58310. var engine = this._scene.getEngine();
  58311. var baseSize = this._spriteTexture.getBaseSize();
  58312. // Sprites
  58313. var deltaTime = engine.getDeltaTime();
  58314. var max = Math.min(this._capacity, this.sprites.length);
  58315. var rowSize = baseSize.width / this.cellWidth;
  58316. var offset = 0;
  58317. for (var index = 0; index < max; index++) {
  58318. var sprite = this.sprites[index];
  58319. if (!sprite || !sprite.isVisible) {
  58320. continue;
  58321. }
  58322. sprite._animate(deltaTime);
  58323. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  58324. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  58325. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  58326. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  58327. }
  58328. this._buffer.update(this._vertexData);
  58329. // Render
  58330. var effect = this._effectBase;
  58331. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  58332. effect = this._effectFog;
  58333. }
  58334. engine.enableEffect(effect);
  58335. var viewMatrix = this._scene.getViewMatrix();
  58336. effect.setTexture("diffuseSampler", this._spriteTexture);
  58337. effect.setMatrix("view", viewMatrix);
  58338. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  58339. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  58340. // Fog
  58341. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  58342. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  58343. effect.setColor3("vFogColor", this._scene.fogColor);
  58344. }
  58345. // VBOs
  58346. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  58347. // Draw order
  58348. engine.setDepthFunctionToLessOrEqual();
  58349. effect.setBool("alphaTest", true);
  58350. engine.setColorWrite(false);
  58351. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  58352. engine.setColorWrite(true);
  58353. effect.setBool("alphaTest", false);
  58354. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  58355. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  58356. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  58357. };
  58358. /**
  58359. * Release associated resources
  58360. */
  58361. SpriteManager.prototype.dispose = function () {
  58362. if (this._buffer) {
  58363. this._buffer.dispose();
  58364. this._buffer = null;
  58365. }
  58366. if (this._indexBuffer) {
  58367. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  58368. this._indexBuffer = null;
  58369. }
  58370. if (this._spriteTexture) {
  58371. this._spriteTexture.dispose();
  58372. this._spriteTexture = null;
  58373. }
  58374. // Remove from scene
  58375. var index = this._scene.spriteManagers.indexOf(this);
  58376. this._scene.spriteManagers.splice(index, 1);
  58377. // Callback
  58378. this.onDisposeObservable.notifyObservers(this);
  58379. this.onDisposeObservable.clear();
  58380. };
  58381. return SpriteManager;
  58382. }());
  58383. BABYLON.SpriteManager = SpriteManager;
  58384. })(BABYLON || (BABYLON = {}));
  58385. //# sourceMappingURL=babylon.spriteManager.js.map
  58386. var BABYLON;
  58387. (function (BABYLON) {
  58388. /**
  58389. * Class used to represent a sprite
  58390. * @see http://doc.babylonjs.com/babylon101/sprites
  58391. */
  58392. var Sprite = /** @class */ (function () {
  58393. /**
  58394. * Creates a new Sprite
  58395. * @param name defines the name
  58396. * @param manager defines the manager
  58397. */
  58398. function Sprite(
  58399. /** defines the name */
  58400. name, manager) {
  58401. this.name = name;
  58402. /** Gets or sets the main color */
  58403. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  58404. /** Gets or sets the width */
  58405. this.width = 1.0;
  58406. /** Gets or sets the height */
  58407. this.height = 1.0;
  58408. /** Gets or sets rotation angle */
  58409. this.angle = 0;
  58410. /** Gets or sets the cell index in the sprite sheet */
  58411. this.cellIndex = 0;
  58412. /** Gets or sets a boolean indicating if UV coordinates should be inverted in U axis */
  58413. this.invertU = 0;
  58414. /** Gets or sets a boolean indicating if UV coordinates should be inverted in B axis */
  58415. this.invertV = 0;
  58416. /** Gets the list of attached animations */
  58417. this.animations = new Array();
  58418. /** Gets or sets a boolean indicating if the sprite can be picked */
  58419. this.isPickable = false;
  58420. this._animationStarted = false;
  58421. this._loopAnimation = false;
  58422. this._fromIndex = 0;
  58423. this._toIndex = 0;
  58424. this._delay = 0;
  58425. this._direction = 1;
  58426. this._time = 0;
  58427. /**
  58428. * Gets or sets a boolean indicating if the sprite is visible (renderable). Default is true
  58429. */
  58430. this.isVisible = true;
  58431. this._manager = manager;
  58432. this._manager.sprites.push(this);
  58433. this.position = BABYLON.Vector3.Zero();
  58434. }
  58435. Object.defineProperty(Sprite.prototype, "size", {
  58436. /**
  58437. * Gets or sets the sprite size
  58438. */
  58439. get: function () {
  58440. return this.width;
  58441. },
  58442. set: function (value) {
  58443. this.width = value;
  58444. this.height = value;
  58445. },
  58446. enumerable: true,
  58447. configurable: true
  58448. });
  58449. /**
  58450. * Starts an animation
  58451. * @param from defines the initial key
  58452. * @param to defines the end key
  58453. * @param loop defines if the animation must loop
  58454. * @param delay defines the start delay (in ms)
  58455. * @param onAnimationEnd defines a callback to call when animation ends
  58456. */
  58457. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  58458. this._fromIndex = from;
  58459. this._toIndex = to;
  58460. this._loopAnimation = loop;
  58461. this._delay = delay;
  58462. this._animationStarted = true;
  58463. this._direction = from < to ? 1 : -1;
  58464. this.cellIndex = from;
  58465. this._time = 0;
  58466. this._onAnimationEnd = onAnimationEnd;
  58467. };
  58468. /** Stops current animation (if any) */
  58469. Sprite.prototype.stopAnimation = function () {
  58470. this._animationStarted = false;
  58471. };
  58472. /** @hidden */
  58473. Sprite.prototype._animate = function (deltaTime) {
  58474. if (!this._animationStarted) {
  58475. return;
  58476. }
  58477. this._time += deltaTime;
  58478. if (this._time > this._delay) {
  58479. this._time = this._time % this._delay;
  58480. this.cellIndex += this._direction;
  58481. if (this.cellIndex > this._toIndex) {
  58482. if (this._loopAnimation) {
  58483. this.cellIndex = this._fromIndex;
  58484. }
  58485. else {
  58486. this.cellIndex = this._toIndex;
  58487. this._animationStarted = false;
  58488. if (this._onAnimationEnd) {
  58489. this._onAnimationEnd();
  58490. }
  58491. if (this.disposeWhenFinishedAnimating) {
  58492. this.dispose();
  58493. }
  58494. }
  58495. }
  58496. }
  58497. };
  58498. /** Release associated resources */
  58499. Sprite.prototype.dispose = function () {
  58500. for (var i = 0; i < this._manager.sprites.length; i++) {
  58501. if (this._manager.sprites[i] == this) {
  58502. this._manager.sprites.splice(i, 1);
  58503. }
  58504. }
  58505. };
  58506. return Sprite;
  58507. }());
  58508. BABYLON.Sprite = Sprite;
  58509. })(BABYLON || (BABYLON = {}));
  58510. //# sourceMappingURL=babylon.sprite.js.map
  58511. var BABYLON;
  58512. (function (BABYLON) {
  58513. BABYLON.Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  58514. if (!BABYLON.PickingInfo) {
  58515. return null;
  58516. }
  58517. var pickingInfo = null;
  58518. if (!camera) {
  58519. if (!this.activeCamera) {
  58520. return null;
  58521. }
  58522. camera = this.activeCamera;
  58523. }
  58524. if (this.spriteManagers.length > 0) {
  58525. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  58526. var spriteManager = this.spriteManagers[spriteIndex];
  58527. if (!spriteManager.isPickable) {
  58528. continue;
  58529. }
  58530. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  58531. if (!result || !result.hit) {
  58532. continue;
  58533. }
  58534. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance) {
  58535. continue;
  58536. }
  58537. pickingInfo = result;
  58538. if (fastCheck) {
  58539. break;
  58540. }
  58541. }
  58542. }
  58543. return pickingInfo || new BABYLON.PickingInfo();
  58544. };
  58545. BABYLON.Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  58546. this.createPickingRayInCameraSpaceToRef(x, y, this._tempSpritePickingRay, camera);
  58547. return this._internalPickSprites(this._tempSpritePickingRay, predicate, fastCheck, camera);
  58548. };
  58549. BABYLON.Scene.prototype.pickSpriteWithRay = function (ray, predicate, fastCheck, camera) {
  58550. if (!this._tempSpritePickingRay) {
  58551. return null;
  58552. }
  58553. if (!camera) {
  58554. if (!this.activeCamera) {
  58555. return null;
  58556. }
  58557. camera = this.activeCamera;
  58558. }
  58559. BABYLON.Ray.TransformToRef(ray, camera.getViewMatrix(), this._tempSpritePickingRay);
  58560. return this._internalPickSprites(this._tempSpritePickingRay, predicate, fastCheck, camera);
  58561. };
  58562. BABYLON.Scene.prototype.setPointerOverSprite = function (sprite) {
  58563. if (this._pointerOverSprite === sprite) {
  58564. return;
  58565. }
  58566. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  58567. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  58568. }
  58569. this._pointerOverSprite = sprite;
  58570. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  58571. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  58572. }
  58573. };
  58574. BABYLON.Scene.prototype.getPointerOverSprite = function () {
  58575. return this._pointerOverSprite;
  58576. };
  58577. /**
  58578. * Defines the sprite scene component responsible to manage sprites
  58579. * in a given scene.
  58580. */
  58581. var SpriteSceneComponent = /** @class */ (function () {
  58582. /**
  58583. * Creates a new instance of the component for the given scene
  58584. * @param scene Defines the scene to register the component in
  58585. */
  58586. function SpriteSceneComponent(scene) {
  58587. /**
  58588. * The component name helpfull to identify the component in the list of scene components.
  58589. */
  58590. this.name = BABYLON.SceneComponentConstants.NAME_SPRITE;
  58591. this.scene = scene;
  58592. this.scene.spriteManagers = new Array();
  58593. this.scene._tempSpritePickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  58594. this.scene.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  58595. this.scene.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  58596. this._spritePredicate = function (sprite) {
  58597. if (!sprite.actionManager) {
  58598. return false;
  58599. }
  58600. return sprite.isPickable && sprite.actionManager.hasPointerTriggers;
  58601. };
  58602. }
  58603. /**
  58604. * Registers the component in a given scene
  58605. */
  58606. SpriteSceneComponent.prototype.register = function () {
  58607. this.scene._pointerMoveStage.registerStep(BABYLON.SceneComponentConstants.STEP_POINTERMOVE_SPRITE, this, this._pointerMove);
  58608. this.scene._pointerDownStage.registerStep(BABYLON.SceneComponentConstants.STEP_POINTERDOWN_SPRITE, this, this._pointerDown);
  58609. this.scene._pointerUpStage.registerStep(BABYLON.SceneComponentConstants.STEP_POINTERUP_SPRITE, this, this._pointerUp);
  58610. };
  58611. /**
  58612. * Rebuilds the elements related to this component in case of
  58613. * context lost for instance.
  58614. */
  58615. SpriteSceneComponent.prototype.rebuild = function () {
  58616. /** Nothing to do for sprites */
  58617. };
  58618. /**
  58619. * Disposes the component and the associated ressources.
  58620. */
  58621. SpriteSceneComponent.prototype.dispose = function () {
  58622. this.scene.onBeforeSpritesRenderingObservable.clear();
  58623. this.scene.onAfterSpritesRenderingObservable.clear();
  58624. var spriteManagers = this.scene.spriteManagers;
  58625. while (spriteManagers.length) {
  58626. spriteManagers[0].dispose();
  58627. }
  58628. };
  58629. SpriteSceneComponent.prototype._pickSpriteButKeepRay = function (originalPointerInfo, x, y, fastCheck, camera) {
  58630. var result = this.scene.pickSprite(x, y, this._spritePredicate, fastCheck, camera);
  58631. if (result) {
  58632. result.ray = originalPointerInfo ? originalPointerInfo.ray : null;
  58633. }
  58634. return result;
  58635. };
  58636. SpriteSceneComponent.prototype._pointerMove = function (unTranslatedPointerX, unTranslatedPointerY, pickResult, isMeshPicked, canvas) {
  58637. var scene = this.scene;
  58638. if (isMeshPicked) {
  58639. scene.setPointerOverSprite(null);
  58640. }
  58641. else {
  58642. pickResult = this._pickSpriteButKeepRay(pickResult, unTranslatedPointerX, unTranslatedPointerY, false, scene.cameraToUseForPointers || undefined);
  58643. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  58644. scene.setPointerOverSprite(pickResult.pickedSprite);
  58645. if (scene._pointerOverSprite && scene._pointerOverSprite.actionManager && scene._pointerOverSprite.actionManager.hoverCursor) {
  58646. canvas.style.cursor = scene._pointerOverSprite.actionManager.hoverCursor;
  58647. }
  58648. else {
  58649. canvas.style.cursor = scene.hoverCursor;
  58650. }
  58651. }
  58652. else {
  58653. scene.setPointerOverSprite(null);
  58654. }
  58655. }
  58656. return pickResult;
  58657. };
  58658. SpriteSceneComponent.prototype._pointerDown = function (unTranslatedPointerX, unTranslatedPointerY, pickResult, evt) {
  58659. var scene = this.scene;
  58660. scene._pickedDownSprite = null;
  58661. if (scene.spriteManagers.length > 0) {
  58662. pickResult = scene.pickSprite(unTranslatedPointerX, unTranslatedPointerY, this._spritePredicate, false, scene.cameraToUseForPointers || undefined);
  58663. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  58664. if (pickResult.pickedSprite.actionManager) {
  58665. scene._pickedDownSprite = pickResult.pickedSprite;
  58666. switch (evt.button) {
  58667. case 0:
  58668. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  58669. break;
  58670. case 1:
  58671. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  58672. break;
  58673. case 2:
  58674. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  58675. break;
  58676. }
  58677. if (pickResult.pickedSprite.actionManager) {
  58678. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  58679. }
  58680. }
  58681. }
  58682. }
  58683. return pickResult;
  58684. };
  58685. SpriteSceneComponent.prototype._pointerUp = function (unTranslatedPointerX, unTranslatedPointerY, pickResult, evt) {
  58686. var scene = this.scene;
  58687. if (scene.spriteManagers.length > 0) {
  58688. var spritePickResult = scene.pickSprite(unTranslatedPointerX, unTranslatedPointerY, this._spritePredicate, false, scene.cameraToUseForPointers || undefined);
  58689. if (spritePickResult) {
  58690. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  58691. if (spritePickResult.pickedSprite.actionManager) {
  58692. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, scene, evt));
  58693. if (spritePickResult.pickedSprite.actionManager) {
  58694. if (!this.scene._isPointerSwiping()) {
  58695. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, scene, evt));
  58696. }
  58697. }
  58698. }
  58699. }
  58700. if (scene._pickedDownSprite && scene._pickedDownSprite.actionManager && scene._pickedDownSprite !== spritePickResult.pickedSprite) {
  58701. scene._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(scene._pickedDownSprite, scene, evt));
  58702. }
  58703. }
  58704. }
  58705. return pickResult;
  58706. };
  58707. return SpriteSceneComponent;
  58708. }());
  58709. BABYLON.SpriteSceneComponent = SpriteSceneComponent;
  58710. })(BABYLON || (BABYLON = {}));
  58711. //# sourceMappingURL=babylon.spriteSceneComponent.js.map
  58712. var BABYLON;
  58713. (function (BABYLON) {
  58714. /**
  58715. * @hidden
  58716. */
  58717. var IntersectionInfo = /** @class */ (function () {
  58718. function IntersectionInfo(bu, bv, distance) {
  58719. this.bu = bu;
  58720. this.bv = bv;
  58721. this.distance = distance;
  58722. this.faceId = 0;
  58723. this.subMeshId = 0;
  58724. }
  58725. return IntersectionInfo;
  58726. }());
  58727. BABYLON.IntersectionInfo = IntersectionInfo;
  58728. /**
  58729. * Information about the result of picking within a scene
  58730. * @see https://doc.babylonjs.com/babylon101/picking_collisions
  58731. */
  58732. var PickingInfo = /** @class */ (function () {
  58733. function PickingInfo() {
  58734. /**
  58735. * If the pick collided with an object
  58736. */
  58737. this.hit = false;
  58738. /**
  58739. * Distance away where the pick collided
  58740. */
  58741. this.distance = 0;
  58742. /**
  58743. * The location of pick collision
  58744. */
  58745. this.pickedPoint = null;
  58746. /**
  58747. * The mesh corresponding the the pick collision
  58748. */
  58749. this.pickedMesh = null;
  58750. /** (See getTextureCoordinates) The barycentric U coordinate that is used when calulating the texture coordinates of the collision.*/
  58751. this.bu = 0;
  58752. /** (See getTextureCoordinates) The barycentric V coordinate that is used when calulating the texture coordinates of the collision.*/
  58753. this.bv = 0;
  58754. /** The id of the face on the mesh that was picked */
  58755. this.faceId = -1;
  58756. /** Id of the the submesh that was picked */
  58757. this.subMeshId = 0;
  58758. /** If a sprite was picked, this will be the sprite the pick collided with */
  58759. this.pickedSprite = null;
  58760. /**
  58761. * If a mesh was used to do the picking (eg. 6dof controller) this will be populated.
  58762. */
  58763. this.originMesh = null;
  58764. /**
  58765. * The ray that was used to perform the picking.
  58766. */
  58767. this.ray = null;
  58768. }
  58769. /**
  58770. * Gets the normal correspodning to the face the pick collided with
  58771. * @param useWorldCoordinates If the resulting normal should be relative to the world (default: false)
  58772. * @param useVerticesNormals If the vertices normals should be used to calculate the normal instead of the normal map
  58773. * @returns The normal correspodning to the face the pick collided with
  58774. */
  58775. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  58776. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  58777. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  58778. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  58779. return null;
  58780. }
  58781. var indices = this.pickedMesh.getIndices();
  58782. if (!indices) {
  58783. return null;
  58784. }
  58785. var result;
  58786. if (useVerticesNormals) {
  58787. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  58788. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  58789. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  58790. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  58791. normal0 = normal0.scale(this.bu);
  58792. normal1 = normal1.scale(this.bv);
  58793. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  58794. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  58795. }
  58796. else {
  58797. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58798. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  58799. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  58800. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  58801. var p1p2 = vertex1.subtract(vertex2);
  58802. var p3p2 = vertex3.subtract(vertex2);
  58803. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  58804. }
  58805. if (useWorldCoordinates) {
  58806. var wm = this.pickedMesh.getWorldMatrix();
  58807. if (this.pickedMesh.nonUniformScaling) {
  58808. BABYLON.Tmp.Matrix[0].copyFrom(wm);
  58809. wm = BABYLON.Tmp.Matrix[0];
  58810. wm.setTranslationFromFloats(0, 0, 0);
  58811. wm.invert();
  58812. wm.transposeToRef(BABYLON.Tmp.Matrix[1]);
  58813. wm = BABYLON.Tmp.Matrix[1];
  58814. }
  58815. result = BABYLON.Vector3.TransformNormal(result, wm);
  58816. }
  58817. result.normalize();
  58818. return result;
  58819. };
  58820. /**
  58821. * Gets the texture coordinates of where the pick occured
  58822. * @returns the vector containing the coordnates of the texture
  58823. */
  58824. PickingInfo.prototype.getTextureCoordinates = function () {
  58825. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  58826. return null;
  58827. }
  58828. var indices = this.pickedMesh.getIndices();
  58829. if (!indices) {
  58830. return null;
  58831. }
  58832. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  58833. if (!uvs) {
  58834. return null;
  58835. }
  58836. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  58837. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  58838. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  58839. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  58840. uv1 = uv1.scale(this.bu);
  58841. uv2 = uv2.scale(this.bv);
  58842. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  58843. };
  58844. return PickingInfo;
  58845. }());
  58846. BABYLON.PickingInfo = PickingInfo;
  58847. })(BABYLON || (BABYLON = {}));
  58848. //# sourceMappingURL=babylon.pickingInfo.js.map
  58849. var BABYLON;
  58850. (function (BABYLON) {
  58851. /**
  58852. * Class representing a ray with position and direction
  58853. */
  58854. var Ray = /** @class */ (function () {
  58855. /**
  58856. * Creates a new ray
  58857. * @param origin origin point
  58858. * @param direction direction
  58859. * @param length length of the ray
  58860. */
  58861. function Ray(
  58862. /** origin point */
  58863. origin,
  58864. /** direction */
  58865. direction,
  58866. /** length of the ray */
  58867. length) {
  58868. if (length === void 0) { length = Number.MAX_VALUE; }
  58869. this.origin = origin;
  58870. this.direction = direction;
  58871. this.length = length;
  58872. }
  58873. // Methods
  58874. /**
  58875. * Checks if the ray intersects a box
  58876. * @param minimum bound of the box
  58877. * @param maximum bound of the box
  58878. * @param intersectionTreshold extra extend to be added to the box in all direction
  58879. * @returns if the box was hit
  58880. */
  58881. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum, intersectionTreshold) {
  58882. if (intersectionTreshold === void 0) { intersectionTreshold = 0; }
  58883. var newMinimum = Ray.TmpVector3[0].copyFromFloats(minimum.x - intersectionTreshold, minimum.y - intersectionTreshold, minimum.z - intersectionTreshold);
  58884. var newMaximum = Ray.TmpVector3[1].copyFromFloats(maximum.x + intersectionTreshold, maximum.y + intersectionTreshold, maximum.z + intersectionTreshold);
  58885. var d = 0.0;
  58886. var maxValue = Number.MAX_VALUE;
  58887. var inv;
  58888. var min;
  58889. var max;
  58890. var temp;
  58891. if (Math.abs(this.direction.x) < 0.0000001) {
  58892. if (this.origin.x < newMinimum.x || this.origin.x > newMaximum.x) {
  58893. return false;
  58894. }
  58895. }
  58896. else {
  58897. inv = 1.0 / this.direction.x;
  58898. min = (newMinimum.x - this.origin.x) * inv;
  58899. max = (newMaximum.x - this.origin.x) * inv;
  58900. if (max === -Infinity) {
  58901. max = Infinity;
  58902. }
  58903. if (min > max) {
  58904. temp = min;
  58905. min = max;
  58906. max = temp;
  58907. }
  58908. d = Math.max(min, d);
  58909. maxValue = Math.min(max, maxValue);
  58910. if (d > maxValue) {
  58911. return false;
  58912. }
  58913. }
  58914. if (Math.abs(this.direction.y) < 0.0000001) {
  58915. if (this.origin.y < newMinimum.y || this.origin.y > newMaximum.y) {
  58916. return false;
  58917. }
  58918. }
  58919. else {
  58920. inv = 1.0 / this.direction.y;
  58921. min = (newMinimum.y - this.origin.y) * inv;
  58922. max = (newMaximum.y - this.origin.y) * inv;
  58923. if (max === -Infinity) {
  58924. max = Infinity;
  58925. }
  58926. if (min > max) {
  58927. temp = min;
  58928. min = max;
  58929. max = temp;
  58930. }
  58931. d = Math.max(min, d);
  58932. maxValue = Math.min(max, maxValue);
  58933. if (d > maxValue) {
  58934. return false;
  58935. }
  58936. }
  58937. if (Math.abs(this.direction.z) < 0.0000001) {
  58938. if (this.origin.z < newMinimum.z || this.origin.z > newMaximum.z) {
  58939. return false;
  58940. }
  58941. }
  58942. else {
  58943. inv = 1.0 / this.direction.z;
  58944. min = (newMinimum.z - this.origin.z) * inv;
  58945. max = (newMaximum.z - this.origin.z) * inv;
  58946. if (max === -Infinity) {
  58947. max = Infinity;
  58948. }
  58949. if (min > max) {
  58950. temp = min;
  58951. min = max;
  58952. max = temp;
  58953. }
  58954. d = Math.max(min, d);
  58955. maxValue = Math.min(max, maxValue);
  58956. if (d > maxValue) {
  58957. return false;
  58958. }
  58959. }
  58960. return true;
  58961. };
  58962. /**
  58963. * Checks if the ray intersects a box
  58964. * @param box the bounding box to check
  58965. * @param intersectionTreshold extra extend to be added to the BoundingBox in all direction
  58966. * @returns if the box was hit
  58967. */
  58968. Ray.prototype.intersectsBox = function (box, intersectionTreshold) {
  58969. if (intersectionTreshold === void 0) { intersectionTreshold = 0; }
  58970. return this.intersectsBoxMinMax(box.minimum, box.maximum, intersectionTreshold);
  58971. };
  58972. /**
  58973. * If the ray hits a sphere
  58974. * @param sphere the bounding sphere to check
  58975. * @param intersectionTreshold extra extend to be added to the BoundingSphere in all direction
  58976. * @returns true if it hits the sphere
  58977. */
  58978. Ray.prototype.intersectsSphere = function (sphere, intersectionTreshold) {
  58979. if (intersectionTreshold === void 0) { intersectionTreshold = 0; }
  58980. var x = sphere.center.x - this.origin.x;
  58981. var y = sphere.center.y - this.origin.y;
  58982. var z = sphere.center.z - this.origin.z;
  58983. var pyth = (x * x) + (y * y) + (z * z);
  58984. var radius = sphere.radius + intersectionTreshold;
  58985. var rr = radius * radius;
  58986. if (pyth <= rr) {
  58987. return true;
  58988. }
  58989. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  58990. if (dot < 0.0) {
  58991. return false;
  58992. }
  58993. var temp = pyth - (dot * dot);
  58994. return temp <= rr;
  58995. };
  58996. /**
  58997. * If the ray hits a triange
  58998. * @param vertex0 triangle vertex
  58999. * @param vertex1 triangle vertex
  59000. * @param vertex2 triangle vertex
  59001. * @returns intersection information if hit
  59002. */
  59003. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  59004. var edge1 = Ray.TmpVector3[0];
  59005. var edge2 = Ray.TmpVector3[1];
  59006. var pvec = Ray.TmpVector3[2];
  59007. var tvec = Ray.TmpVector3[3];
  59008. var qvec = Ray.TmpVector3[4];
  59009. vertex1.subtractToRef(vertex0, edge1);
  59010. vertex2.subtractToRef(vertex0, edge2);
  59011. BABYLON.Vector3.CrossToRef(this.direction, edge2, pvec);
  59012. var det = BABYLON.Vector3.Dot(edge1, pvec);
  59013. if (det === 0) {
  59014. return null;
  59015. }
  59016. var invdet = 1 / det;
  59017. this.origin.subtractToRef(vertex0, tvec);
  59018. var bu = BABYLON.Vector3.Dot(tvec, pvec) * invdet;
  59019. if (bu < 0 || bu > 1.0) {
  59020. return null;
  59021. }
  59022. BABYLON.Vector3.CrossToRef(tvec, edge1, qvec);
  59023. var bv = BABYLON.Vector3.Dot(this.direction, qvec) * invdet;
  59024. if (bv < 0 || bu + bv > 1.0) {
  59025. return null;
  59026. }
  59027. //check if the distance is longer than the predefined length.
  59028. var distance = BABYLON.Vector3.Dot(edge2, qvec) * invdet;
  59029. if (distance > this.length) {
  59030. return null;
  59031. }
  59032. return new BABYLON.IntersectionInfo(bu, bv, distance);
  59033. };
  59034. /**
  59035. * Checks if ray intersects a plane
  59036. * @param plane the plane to check
  59037. * @returns the distance away it was hit
  59038. */
  59039. Ray.prototype.intersectsPlane = function (plane) {
  59040. var distance;
  59041. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  59042. if (Math.abs(result1) < 9.99999997475243E-07) {
  59043. return null;
  59044. }
  59045. else {
  59046. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  59047. distance = (-plane.d - result2) / result1;
  59048. if (distance < 0.0) {
  59049. if (distance < -9.99999997475243E-07) {
  59050. return null;
  59051. }
  59052. else {
  59053. return 0;
  59054. }
  59055. }
  59056. return distance;
  59057. }
  59058. };
  59059. /**
  59060. * Checks if ray intersects a mesh
  59061. * @param mesh the mesh to check
  59062. * @param fastCheck if only the bounding box should checked
  59063. * @returns picking info of the intersecton
  59064. */
  59065. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  59066. var tm = BABYLON.Tmp.Matrix[0];
  59067. mesh.getWorldMatrix().invertToRef(tm);
  59068. if (this._tmpRay) {
  59069. Ray.TransformToRef(this, tm, this._tmpRay);
  59070. }
  59071. else {
  59072. this._tmpRay = Ray.Transform(this, tm);
  59073. }
  59074. return mesh.intersects(this._tmpRay, fastCheck);
  59075. };
  59076. /**
  59077. * Checks if ray intersects a mesh
  59078. * @param meshes the meshes to check
  59079. * @param fastCheck if only the bounding box should checked
  59080. * @param results array to store result in
  59081. * @returns Array of picking infos
  59082. */
  59083. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  59084. if (results) {
  59085. results.length = 0;
  59086. }
  59087. else {
  59088. results = [];
  59089. }
  59090. for (var i = 0; i < meshes.length; i++) {
  59091. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  59092. if (pickInfo.hit) {
  59093. results.push(pickInfo);
  59094. }
  59095. }
  59096. results.sort(this._comparePickingInfo);
  59097. return results;
  59098. };
  59099. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  59100. if (pickingInfoA.distance < pickingInfoB.distance) {
  59101. return -1;
  59102. }
  59103. else if (pickingInfoA.distance > pickingInfoB.distance) {
  59104. return 1;
  59105. }
  59106. else {
  59107. return 0;
  59108. }
  59109. };
  59110. /**
  59111. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  59112. * @param sega the first point of the segment to test the intersection against
  59113. * @param segb the second point of the segment to test the intersection against
  59114. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  59115. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  59116. */
  59117. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  59118. var o = this.origin;
  59119. var u = BABYLON.Tmp.Vector3[0];
  59120. var rsegb = BABYLON.Tmp.Vector3[1];
  59121. var v = BABYLON.Tmp.Vector3[2];
  59122. var w = BABYLON.Tmp.Vector3[3];
  59123. segb.subtractToRef(sega, u);
  59124. this.direction.scaleToRef(Ray.rayl, v);
  59125. o.addToRef(v, rsegb);
  59126. sega.subtractToRef(o, w);
  59127. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  59128. var b = BABYLON.Vector3.Dot(u, v);
  59129. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  59130. var d = BABYLON.Vector3.Dot(u, w);
  59131. var e = BABYLON.Vector3.Dot(v, w);
  59132. var D = a * c - b * b; // always >= 0
  59133. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  59134. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  59135. // compute the line parameters of the two closest points
  59136. if (D < Ray.smallnum) { // the lines are almost parallel
  59137. sN = 0.0; // force using point P0 on segment S1
  59138. sD = 1.0; // to prevent possible division by 0.0 later
  59139. tN = e;
  59140. tD = c;
  59141. }
  59142. else { // get the closest points on the infinite lines
  59143. sN = (b * e - c * d);
  59144. tN = (a * e - b * d);
  59145. if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
  59146. sN = 0.0;
  59147. tN = e;
  59148. tD = c;
  59149. }
  59150. else if (sN > sD) { // sc > 1 => the s=1 edge is visible
  59151. sN = sD;
  59152. tN = e + b;
  59153. tD = c;
  59154. }
  59155. }
  59156. if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
  59157. tN = 0.0;
  59158. // recompute sc for this edge
  59159. if (-d < 0.0) {
  59160. sN = 0.0;
  59161. }
  59162. else if (-d > a) {
  59163. sN = sD;
  59164. }
  59165. else {
  59166. sN = -d;
  59167. sD = a;
  59168. }
  59169. }
  59170. else if (tN > tD) { // tc > 1 => the t=1 edge is visible
  59171. tN = tD;
  59172. // recompute sc for this edge
  59173. if ((-d + b) < 0.0) {
  59174. sN = 0;
  59175. }
  59176. else if ((-d + b) > a) {
  59177. sN = sD;
  59178. }
  59179. else {
  59180. sN = (-d + b);
  59181. sD = a;
  59182. }
  59183. }
  59184. // finally do the division to get sc and tc
  59185. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  59186. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  59187. // get the difference of the two closest points
  59188. var qtc = BABYLON.Tmp.Vector3[4];
  59189. v.scaleToRef(tc, qtc);
  59190. var qsc = BABYLON.Tmp.Vector3[5];
  59191. u.scaleToRef(sc, qsc);
  59192. qsc.addInPlace(w);
  59193. var dP = BABYLON.Tmp.Vector3[6];
  59194. qsc.subtractToRef(qtc, dP); // = S1(sc) - S2(tc)
  59195. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  59196. if (isIntersected) {
  59197. return qsc.length();
  59198. }
  59199. return -1;
  59200. };
  59201. /**
  59202. * Update the ray from viewport position
  59203. * @param x position
  59204. * @param y y position
  59205. * @param viewportWidth viewport width
  59206. * @param viewportHeight viewport height
  59207. * @param world world matrix
  59208. * @param view view matrix
  59209. * @param projection projection matrix
  59210. * @returns this ray updated
  59211. */
  59212. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  59213. BABYLON.Vector3.UnprojectRayToRef(x, y, viewportWidth, viewportHeight, world, view, projection, this);
  59214. return this;
  59215. };
  59216. // Statics
  59217. /**
  59218. * Creates a ray with origin and direction of 0,0,0
  59219. * @returns the new ray
  59220. */
  59221. Ray.Zero = function () {
  59222. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  59223. };
  59224. /**
  59225. * Creates a new ray from screen space and viewport
  59226. * @param x position
  59227. * @param y y position
  59228. * @param viewportWidth viewport width
  59229. * @param viewportHeight viewport height
  59230. * @param world world matrix
  59231. * @param view view matrix
  59232. * @param projection projection matrix
  59233. * @returns new ray
  59234. */
  59235. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  59236. var result = Ray.Zero();
  59237. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  59238. };
  59239. /**
  59240. * 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
  59241. * transformed to the given world matrix.
  59242. * @param origin The origin point
  59243. * @param end The end point
  59244. * @param world a matrix to transform the ray to. Default is the identity matrix.
  59245. * @returns the new ray
  59246. */
  59247. Ray.CreateNewFromTo = function (origin, end, world) {
  59248. if (world === void 0) { world = BABYLON.Matrix.IdentityReadOnly; }
  59249. var direction = end.subtract(origin);
  59250. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  59251. direction.normalize();
  59252. return Ray.Transform(new Ray(origin, direction, length), world);
  59253. };
  59254. /**
  59255. * Transforms a ray by a matrix
  59256. * @param ray ray to transform
  59257. * @param matrix matrix to apply
  59258. * @returns the resulting new ray
  59259. */
  59260. Ray.Transform = function (ray, matrix) {
  59261. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  59262. Ray.TransformToRef(ray, matrix, result);
  59263. return result;
  59264. };
  59265. /**
  59266. * Transforms a ray by a matrix
  59267. * @param ray ray to transform
  59268. * @param matrix matrix to apply
  59269. * @param result ray to store result in
  59270. */
  59271. Ray.TransformToRef = function (ray, matrix, result) {
  59272. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  59273. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  59274. result.length = ray.length;
  59275. var dir = result.direction;
  59276. var len = dir.length();
  59277. if (!(len === 0 || len === 1)) {
  59278. var num = 1.0 / len;
  59279. dir.x *= num;
  59280. dir.y *= num;
  59281. dir.z *= num;
  59282. result.length *= len;
  59283. }
  59284. };
  59285. Ray.TmpVector3 = BABYLON.Tools.BuildArray(6, BABYLON.Vector3.Zero);
  59286. Ray.smallnum = 0.00000001;
  59287. Ray.rayl = 10e8;
  59288. return Ray;
  59289. }());
  59290. BABYLON.Ray = Ray;
  59291. })(BABYLON || (BABYLON = {}));
  59292. //# sourceMappingURL=babylon.ray.js.map
  59293. var BABYLON;
  59294. (function (BABYLON) {
  59295. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  59296. if (boxMin.x > sphereCenter.x + sphereRadius) {
  59297. return false;
  59298. }
  59299. if (sphereCenter.x - sphereRadius > boxMax.x) {
  59300. return false;
  59301. }
  59302. if (boxMin.y > sphereCenter.y + sphereRadius) {
  59303. return false;
  59304. }
  59305. if (sphereCenter.y - sphereRadius > boxMax.y) {
  59306. return false;
  59307. }
  59308. if (boxMin.z > sphereCenter.z + sphereRadius) {
  59309. return false;
  59310. }
  59311. if (sphereCenter.z - sphereRadius > boxMax.z) {
  59312. return false;
  59313. }
  59314. return true;
  59315. };
  59316. var getLowestRoot = (function () {
  59317. var result = { root: 0, found: false };
  59318. return function (a, b, c, maxR) {
  59319. result.root = 0;
  59320. result.found = false;
  59321. var determinant = b * b - 4.0 * a * c;
  59322. if (determinant < 0) {
  59323. return result;
  59324. }
  59325. var sqrtD = Math.sqrt(determinant);
  59326. var r1 = (-b - sqrtD) / (2.0 * a);
  59327. var r2 = (-b + sqrtD) / (2.0 * a);
  59328. if (r1 > r2) {
  59329. var temp = r2;
  59330. r2 = r1;
  59331. r1 = temp;
  59332. }
  59333. if (r1 > 0 && r1 < maxR) {
  59334. result.root = r1;
  59335. result.found = true;
  59336. return result;
  59337. }
  59338. if (r2 > 0 && r2 < maxR) {
  59339. result.root = r2;
  59340. result.found = true;
  59341. return result;
  59342. }
  59343. return result;
  59344. };
  59345. })();
  59346. /** @hidden */
  59347. var Collider = /** @class */ (function () {
  59348. function Collider() {
  59349. this._collisionPoint = BABYLON.Vector3.Zero();
  59350. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  59351. this._tempVector = BABYLON.Vector3.Zero();
  59352. this._tempVector2 = BABYLON.Vector3.Zero();
  59353. this._tempVector3 = BABYLON.Vector3.Zero();
  59354. this._tempVector4 = BABYLON.Vector3.Zero();
  59355. this._edge = BABYLON.Vector3.Zero();
  59356. this._baseToVertex = BABYLON.Vector3.Zero();
  59357. this._destinationPoint = BABYLON.Vector3.Zero();
  59358. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  59359. this._displacementVector = BABYLON.Vector3.Zero();
  59360. /** @hidden */
  59361. this._radius = BABYLON.Vector3.One();
  59362. /** @hidden */
  59363. this._retry = 0;
  59364. /** @hidden */
  59365. this._basePointWorld = BABYLON.Vector3.Zero();
  59366. this._velocityWorld = BABYLON.Vector3.Zero();
  59367. this._normalizedVelocity = BABYLON.Vector3.Zero();
  59368. this._collisionMask = -1;
  59369. }
  59370. Object.defineProperty(Collider.prototype, "collisionMask", {
  59371. get: function () {
  59372. return this._collisionMask;
  59373. },
  59374. set: function (mask) {
  59375. this._collisionMask = !isNaN(mask) ? mask : -1;
  59376. },
  59377. enumerable: true,
  59378. configurable: true
  59379. });
  59380. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  59381. /**
  59382. * Gets the plane normal used to compute the sliding response (in local space)
  59383. */
  59384. get: function () {
  59385. return this._slidePlaneNormal;
  59386. },
  59387. enumerable: true,
  59388. configurable: true
  59389. });
  59390. // Methods
  59391. /** @hidden */
  59392. Collider.prototype._initialize = function (source, dir, e) {
  59393. this._velocity = dir;
  59394. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  59395. this._basePoint = source;
  59396. source.multiplyToRef(this._radius, this._basePointWorld);
  59397. dir.multiplyToRef(this._radius, this._velocityWorld);
  59398. this._velocityWorldLength = this._velocityWorld.length();
  59399. this._epsilon = e;
  59400. this.collisionFound = false;
  59401. };
  59402. /** @hidden */
  59403. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  59404. pa.subtractToRef(point, this._tempVector);
  59405. pb.subtractToRef(point, this._tempVector2);
  59406. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  59407. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  59408. if (d < 0) {
  59409. return false;
  59410. }
  59411. pc.subtractToRef(point, this._tempVector3);
  59412. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  59413. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  59414. if (d < 0) {
  59415. return false;
  59416. }
  59417. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  59418. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  59419. return d >= 0;
  59420. };
  59421. /** @hidden */
  59422. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  59423. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  59424. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  59425. if (distance > this._velocityWorldLength + max + sphereRadius) {
  59426. return false;
  59427. }
  59428. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max)) {
  59429. return false;
  59430. }
  59431. return true;
  59432. };
  59433. /** @hidden */
  59434. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  59435. var t0;
  59436. var embeddedInPlane = false;
  59437. //defensive programming, actually not needed.
  59438. if (!trianglePlaneArray) {
  59439. trianglePlaneArray = [];
  59440. }
  59441. if (!trianglePlaneArray[faceIndex]) {
  59442. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  59443. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  59444. }
  59445. var trianglePlane = trianglePlaneArray[faceIndex];
  59446. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0)) {
  59447. return;
  59448. }
  59449. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  59450. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  59451. if (normalDotVelocity == 0) {
  59452. if (Math.abs(signedDistToTrianglePlane) >= 1.0) {
  59453. return;
  59454. }
  59455. embeddedInPlane = true;
  59456. t0 = 0;
  59457. }
  59458. else {
  59459. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  59460. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  59461. if (t0 > t1) {
  59462. var temp = t1;
  59463. t1 = t0;
  59464. t0 = temp;
  59465. }
  59466. if (t0 > 1.0 || t1 < 0.0) {
  59467. return;
  59468. }
  59469. if (t0 < 0) {
  59470. t0 = 0;
  59471. }
  59472. if (t0 > 1.0) {
  59473. t0 = 1.0;
  59474. }
  59475. }
  59476. this._collisionPoint.copyFromFloats(0, 0, 0);
  59477. var found = false;
  59478. var t = 1.0;
  59479. if (!embeddedInPlane) {
  59480. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  59481. this._velocity.scaleToRef(t0, this._tempVector);
  59482. this._planeIntersectionPoint.addInPlace(this._tempVector);
  59483. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  59484. found = true;
  59485. t = t0;
  59486. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  59487. }
  59488. }
  59489. if (!found) {
  59490. var velocitySquaredLength = this._velocity.lengthSquared();
  59491. var a = velocitySquaredLength;
  59492. this._basePoint.subtractToRef(p1, this._tempVector);
  59493. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  59494. var c = this._tempVector.lengthSquared() - 1.0;
  59495. var lowestRoot = getLowestRoot(a, b, c, t);
  59496. if (lowestRoot.found) {
  59497. t = lowestRoot.root;
  59498. found = true;
  59499. this._collisionPoint.copyFrom(p1);
  59500. }
  59501. this._basePoint.subtractToRef(p2, this._tempVector);
  59502. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  59503. c = this._tempVector.lengthSquared() - 1.0;
  59504. lowestRoot = getLowestRoot(a, b, c, t);
  59505. if (lowestRoot.found) {
  59506. t = lowestRoot.root;
  59507. found = true;
  59508. this._collisionPoint.copyFrom(p2);
  59509. }
  59510. this._basePoint.subtractToRef(p3, this._tempVector);
  59511. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  59512. c = this._tempVector.lengthSquared() - 1.0;
  59513. lowestRoot = getLowestRoot(a, b, c, t);
  59514. if (lowestRoot.found) {
  59515. t = lowestRoot.root;
  59516. found = true;
  59517. this._collisionPoint.copyFrom(p3);
  59518. }
  59519. p2.subtractToRef(p1, this._edge);
  59520. p1.subtractToRef(this._basePoint, this._baseToVertex);
  59521. var edgeSquaredLength = this._edge.lengthSquared();
  59522. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  59523. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  59524. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  59525. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  59526. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  59527. lowestRoot = getLowestRoot(a, b, c, t);
  59528. if (lowestRoot.found) {
  59529. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  59530. if (f >= 0.0 && f <= 1.0) {
  59531. t = lowestRoot.root;
  59532. found = true;
  59533. this._edge.scaleInPlace(f);
  59534. p1.addToRef(this._edge, this._collisionPoint);
  59535. }
  59536. }
  59537. p3.subtractToRef(p2, this._edge);
  59538. p2.subtractToRef(this._basePoint, this._baseToVertex);
  59539. edgeSquaredLength = this._edge.lengthSquared();
  59540. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  59541. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  59542. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  59543. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  59544. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  59545. lowestRoot = getLowestRoot(a, b, c, t);
  59546. if (lowestRoot.found) {
  59547. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  59548. if (f >= 0.0 && f <= 1.0) {
  59549. t = lowestRoot.root;
  59550. found = true;
  59551. this._edge.scaleInPlace(f);
  59552. p2.addToRef(this._edge, this._collisionPoint);
  59553. }
  59554. }
  59555. p1.subtractToRef(p3, this._edge);
  59556. p3.subtractToRef(this._basePoint, this._baseToVertex);
  59557. edgeSquaredLength = this._edge.lengthSquared();
  59558. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  59559. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  59560. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  59561. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  59562. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  59563. lowestRoot = getLowestRoot(a, b, c, t);
  59564. if (lowestRoot.found) {
  59565. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  59566. if (f >= 0.0 && f <= 1.0) {
  59567. t = lowestRoot.root;
  59568. found = true;
  59569. this._edge.scaleInPlace(f);
  59570. p3.addToRef(this._edge, this._collisionPoint);
  59571. }
  59572. }
  59573. }
  59574. if (found) {
  59575. var distToCollision = t * this._velocity.length();
  59576. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  59577. if (!this.intersectionPoint) {
  59578. this.intersectionPoint = this._collisionPoint.clone();
  59579. }
  59580. else {
  59581. this.intersectionPoint.copyFrom(this._collisionPoint);
  59582. }
  59583. this._nearestDistance = distToCollision;
  59584. this.collisionFound = true;
  59585. }
  59586. }
  59587. };
  59588. /** @hidden */
  59589. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  59590. for (var i = indexStart; i < indexEnd; i += 3) {
  59591. var p1 = pts[indices[i] - decal];
  59592. var p2 = pts[indices[i + 1] - decal];
  59593. var p3 = pts[indices[i + 2] - decal];
  59594. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  59595. }
  59596. };
  59597. /** @hidden */
  59598. Collider.prototype._getResponse = function (pos, vel) {
  59599. pos.addToRef(vel, this._destinationPoint);
  59600. vel.scaleInPlace((this._nearestDistance / vel.length()));
  59601. this._basePoint.addToRef(vel, pos);
  59602. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  59603. this._slidePlaneNormal.normalize();
  59604. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  59605. pos.addInPlace(this._displacementVector);
  59606. this.intersectionPoint.addInPlace(this._displacementVector);
  59607. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  59608. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  59609. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  59610. };
  59611. return Collider;
  59612. }());
  59613. BABYLON.Collider = Collider;
  59614. })(BABYLON || (BABYLON = {}));
  59615. //# sourceMappingURL=babylon.collider.js.map
  59616. var BABYLON;
  59617. (function (BABYLON) {
  59618. //WebWorker code will be inserted to this variable.
  59619. /** @hidden */
  59620. BABYLON.CollisionWorker = "";
  59621. /** Defines supported task for worker process */
  59622. var WorkerTaskType;
  59623. (function (WorkerTaskType) {
  59624. /** Initialization */
  59625. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  59626. /** Update of geometry */
  59627. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  59628. /** Evaluate collision */
  59629. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  59630. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  59631. /** Defines kind of replies returned by worker */
  59632. var WorkerReplyType;
  59633. (function (WorkerReplyType) {
  59634. /** Success */
  59635. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  59636. /** Unkown error */
  59637. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  59638. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  59639. /** @hidden */
  59640. var CollisionCoordinatorWorker = /** @class */ (function () {
  59641. function CollisionCoordinatorWorker() {
  59642. var _this = this;
  59643. this._scaledPosition = BABYLON.Vector3.Zero();
  59644. this._scaledVelocity = BABYLON.Vector3.Zero();
  59645. this.onMeshUpdated = function (transformNode) {
  59646. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  59647. };
  59648. this.onGeometryUpdated = function (geometry) {
  59649. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  59650. };
  59651. this._afterRender = function () {
  59652. if (!_this._init) {
  59653. return;
  59654. }
  59655. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  59656. return;
  59657. }
  59658. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  59659. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  59660. if (_this._runningUpdated > 4) {
  59661. return;
  59662. }
  59663. ++_this._runningUpdated;
  59664. var payload = {
  59665. updatedMeshes: _this._addUpdateMeshesList,
  59666. updatedGeometries: _this._addUpdateGeometriesList,
  59667. removedGeometries: _this._toRemoveGeometryArray,
  59668. removedMeshes: _this._toRemoveMeshesArray
  59669. };
  59670. var message = {
  59671. payload: payload,
  59672. taskType: WorkerTaskType.UPDATE
  59673. };
  59674. var serializable = [];
  59675. for (var id in payload.updatedGeometries) {
  59676. if (payload.updatedGeometries.hasOwnProperty(id)) {
  59677. //prepare transferables
  59678. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  59679. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  59680. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  59681. }
  59682. }
  59683. _this._worker.postMessage(message, serializable);
  59684. _this._addUpdateMeshesList = {};
  59685. _this._addUpdateGeometriesList = {};
  59686. _this._toRemoveGeometryArray = [];
  59687. _this._toRemoveMeshesArray = [];
  59688. };
  59689. this._onMessageFromWorker = function (e) {
  59690. var returnData = e.data;
  59691. if (returnData.error != WorkerReplyType.SUCCESS) {
  59692. //TODO what errors can be returned from the worker?
  59693. BABYLON.Tools.Warn("error returned from worker!");
  59694. return;
  59695. }
  59696. switch (returnData.taskType) {
  59697. case WorkerTaskType.INIT:
  59698. _this._init = true;
  59699. //Update the worked with ALL of the scene's current state
  59700. _this._scene.meshes.forEach(function (mesh) {
  59701. _this.onMeshAdded(mesh);
  59702. });
  59703. _this._scene.getGeometries().forEach(function (geometry) {
  59704. _this.onGeometryAdded(geometry);
  59705. });
  59706. break;
  59707. case WorkerTaskType.UPDATE:
  59708. _this._runningUpdated--;
  59709. break;
  59710. case WorkerTaskType.COLLIDE:
  59711. var returnPayload = returnData.payload;
  59712. if (!_this._collisionsCallbackArray[returnPayload.collisionId]) {
  59713. return;
  59714. }
  59715. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  59716. if (callback) {
  59717. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  59718. if (mesh) {
  59719. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  59720. }
  59721. }
  59722. //cleanup
  59723. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  59724. break;
  59725. }
  59726. };
  59727. this._collisionsCallbackArray = [];
  59728. this._init = false;
  59729. this._runningUpdated = 0;
  59730. this._addUpdateMeshesList = {};
  59731. this._addUpdateGeometriesList = {};
  59732. this._toRemoveGeometryArray = [];
  59733. this._toRemoveMeshesArray = [];
  59734. }
  59735. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  59736. if (!this._init) {
  59737. return;
  59738. }
  59739. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000]) {
  59740. return;
  59741. }
  59742. position.divideToRef(collider._radius, this._scaledPosition);
  59743. displacement.divideToRef(collider._radius, this._scaledVelocity);
  59744. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  59745. var payload = {
  59746. collider: {
  59747. position: this._scaledPosition.asArray(),
  59748. velocity: this._scaledVelocity.asArray(),
  59749. radius: collider._radius.asArray()
  59750. },
  59751. collisionId: collisionIndex,
  59752. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  59753. maximumRetry: maximumRetry
  59754. };
  59755. var message = {
  59756. payload: payload,
  59757. taskType: WorkerTaskType.COLLIDE
  59758. };
  59759. this._worker.postMessage(message);
  59760. };
  59761. CollisionCoordinatorWorker.prototype.init = function (scene) {
  59762. this._scene = scene;
  59763. this._scene.registerAfterRender(this._afterRender);
  59764. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  59765. this._worker = new Worker(workerUrl);
  59766. this._worker.onmessage = this._onMessageFromWorker;
  59767. var message = {
  59768. payload: {},
  59769. taskType: WorkerTaskType.INIT
  59770. };
  59771. this._worker.postMessage(message);
  59772. };
  59773. CollisionCoordinatorWorker.prototype.destroy = function () {
  59774. this._scene.unregisterAfterRender(this._afterRender);
  59775. this._worker.terminate();
  59776. };
  59777. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  59778. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  59779. this.onMeshUpdated(mesh);
  59780. };
  59781. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  59782. this._toRemoveMeshesArray.push(mesh.uniqueId);
  59783. };
  59784. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  59785. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  59786. geometry.onGeometryUpdated = this.onGeometryUpdated;
  59787. this.onGeometryUpdated(geometry);
  59788. };
  59789. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  59790. this._toRemoveGeometryArray.push(geometry.id);
  59791. };
  59792. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  59793. var submeshes = [];
  59794. if (mesh.subMeshes) {
  59795. submeshes = mesh.subMeshes.map(function (sm, idx) {
  59796. var boundingInfo = sm.getBoundingInfo();
  59797. return {
  59798. position: idx,
  59799. verticesStart: sm.verticesStart,
  59800. verticesCount: sm.verticesCount,
  59801. indexStart: sm.indexStart,
  59802. indexCount: sm.indexCount,
  59803. hasMaterial: !!sm.getMaterial(),
  59804. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  59805. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  59806. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  59807. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  59808. };
  59809. });
  59810. }
  59811. var geometryId = null;
  59812. if (mesh instanceof BABYLON.Mesh) {
  59813. var geometry = mesh.geometry;
  59814. geometryId = geometry ? geometry.id : null;
  59815. }
  59816. else if (mesh instanceof BABYLON.InstancedMesh) {
  59817. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  59818. geometryId = geometry ? geometry.id : null;
  59819. }
  59820. var boundingInfo = mesh.getBoundingInfo();
  59821. return {
  59822. uniqueId: mesh.uniqueId,
  59823. id: mesh.id,
  59824. name: mesh.name,
  59825. geometryId: geometryId,
  59826. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  59827. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  59828. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  59829. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  59830. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  59831. subMeshes: submeshes,
  59832. checkCollisions: mesh.checkCollisions
  59833. };
  59834. };
  59835. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  59836. return {
  59837. id: geometry.id,
  59838. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  59839. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  59840. indices: new Uint32Array(geometry.getIndices() || []),
  59841. };
  59842. };
  59843. return CollisionCoordinatorWorker;
  59844. }());
  59845. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  59846. /** @hidden */
  59847. var CollisionCoordinatorLegacy = /** @class */ (function () {
  59848. function CollisionCoordinatorLegacy() {
  59849. this._scaledPosition = BABYLON.Vector3.Zero();
  59850. this._scaledVelocity = BABYLON.Vector3.Zero();
  59851. this._finalPosition = BABYLON.Vector3.Zero();
  59852. }
  59853. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  59854. position.divideToRef(collider._radius, this._scaledPosition);
  59855. displacement.divideToRef(collider._radius, this._scaledVelocity);
  59856. collider.collidedMesh = null;
  59857. collider._retry = 0;
  59858. collider._initialVelocity = this._scaledVelocity;
  59859. collider._initialPosition = this._scaledPosition;
  59860. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  59861. this._finalPosition.multiplyInPlace(collider._radius);
  59862. //run the callback
  59863. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  59864. };
  59865. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  59866. this._scene = scene;
  59867. };
  59868. CollisionCoordinatorLegacy.prototype.destroy = function () {
  59869. //Legacy need no destruction method.
  59870. };
  59871. //No update in legacy mode
  59872. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  59873. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  59874. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  59875. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  59876. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  59877. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  59878. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  59879. if (excludedMesh === void 0) { excludedMesh = null; }
  59880. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  59881. if (collider._retry >= maximumRetry) {
  59882. finalPosition.copyFrom(position);
  59883. return;
  59884. }
  59885. // Check if this is a mesh else camera or -1
  59886. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  59887. collider._initialize(position, velocity, closeDistance);
  59888. // Check all meshes
  59889. for (var index = 0; index < this._scene.meshes.length; index++) {
  59890. var mesh = this._scene.meshes[index];
  59891. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  59892. mesh._checkCollision(collider);
  59893. }
  59894. }
  59895. if (!collider.collisionFound) {
  59896. position.addToRef(velocity, finalPosition);
  59897. return;
  59898. }
  59899. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  59900. collider._getResponse(position, velocity);
  59901. }
  59902. if (velocity.length() <= closeDistance) {
  59903. finalPosition.copyFrom(position);
  59904. return;
  59905. }
  59906. collider._retry++;
  59907. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  59908. };
  59909. return CollisionCoordinatorLegacy;
  59910. }());
  59911. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  59912. })(BABYLON || (BABYLON = {}));
  59913. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  59914. var BABYLON;
  59915. (function (BABYLON) {
  59916. /**
  59917. * A particle represents one of the element emitted by a particle system.
  59918. * This is mainly define by its coordinates, direction, velocity and age.
  59919. */
  59920. var Particle = /** @class */ (function () {
  59921. /**
  59922. * Creates a new instance Particle
  59923. * @param particleSystem the particle system the particle belongs to
  59924. */
  59925. function Particle(
  59926. /**
  59927. * The particle system the particle belongs to.
  59928. */
  59929. particleSystem) {
  59930. this.particleSystem = particleSystem;
  59931. /**
  59932. * The world position of the particle in the scene.
  59933. */
  59934. this.position = BABYLON.Vector3.Zero();
  59935. /**
  59936. * The world direction of the particle in the scene.
  59937. */
  59938. this.direction = BABYLON.Vector3.Zero();
  59939. /**
  59940. * The color of the particle.
  59941. */
  59942. this.color = new BABYLON.Color4(0, 0, 0, 0);
  59943. /**
  59944. * The color change of the particle per step.
  59945. */
  59946. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  59947. /**
  59948. * Defines how long will the life of the particle be.
  59949. */
  59950. this.lifeTime = 1.0;
  59951. /**
  59952. * The current age of the particle.
  59953. */
  59954. this.age = 0;
  59955. /**
  59956. * The current size of the particle.
  59957. */
  59958. this.size = 0;
  59959. /**
  59960. * The current scale of the particle.
  59961. */
  59962. this.scale = new BABYLON.Vector2(1, 1);
  59963. /**
  59964. * The current angle of the particle.
  59965. */
  59966. this.angle = 0;
  59967. /**
  59968. * Defines how fast is the angle changing.
  59969. */
  59970. this.angularSpeed = 0;
  59971. /**
  59972. * Defines the cell index used by the particle to be rendered from a sprite.
  59973. */
  59974. this.cellIndex = 0;
  59975. /** @hidden */
  59976. this._attachedSubEmitters = null;
  59977. /** @hidden */
  59978. this._currentColor1 = new BABYLON.Color4(0, 0, 0, 0);
  59979. /** @hidden */
  59980. this._currentColor2 = new BABYLON.Color4(0, 0, 0, 0);
  59981. /** @hidden */
  59982. this._currentSize1 = 0;
  59983. /** @hidden */
  59984. this._currentSize2 = 0;
  59985. /** @hidden */
  59986. this._currentAngularSpeed1 = 0;
  59987. /** @hidden */
  59988. this._currentAngularSpeed2 = 0;
  59989. /** @hidden */
  59990. this._currentVelocity1 = 0;
  59991. /** @hidden */
  59992. this._currentVelocity2 = 0;
  59993. /** @hidden */
  59994. this._currentLimitVelocity1 = 0;
  59995. /** @hidden */
  59996. this._currentLimitVelocity2 = 0;
  59997. /** @hidden */
  59998. this._currentDrag1 = 0;
  59999. /** @hidden */
  60000. this._currentDrag2 = 0;
  60001. this.id = Particle._Count++;
  60002. if (!this.particleSystem.isAnimationSheetEnabled) {
  60003. return;
  60004. }
  60005. this.updateCellInfoFromSystem();
  60006. }
  60007. Particle.prototype.updateCellInfoFromSystem = function () {
  60008. this.cellIndex = this.particleSystem.startSpriteCellID;
  60009. };
  60010. /**
  60011. * Defines how the sprite cell index is updated for the particle
  60012. */
  60013. Particle.prototype.updateCellIndex = function () {
  60014. var offsetAge = this.age;
  60015. var changeSpeed = this.particleSystem.spriteCellChangeSpeed;
  60016. if (this.particleSystem.spriteRandomStartCell) {
  60017. if (this._randomCellOffset === undefined) {
  60018. this._randomCellOffset = Math.random() * this.lifeTime;
  60019. }
  60020. if (changeSpeed === 0) { // Special case when speed = 0 meaning we want to stay on initial cell
  60021. changeSpeed = 1;
  60022. offsetAge = this._randomCellOffset;
  60023. }
  60024. else {
  60025. offsetAge += this._randomCellOffset;
  60026. }
  60027. }
  60028. var dist = (this._initialEndSpriteCellID - this._initialStartSpriteCellID);
  60029. var ratio = BABYLON.Scalar.Clamp(((offsetAge * changeSpeed) % this.lifeTime) / this.lifeTime);
  60030. this.cellIndex = this._initialStartSpriteCellID + (ratio * dist) | 0;
  60031. };
  60032. /** @hidden */
  60033. Particle.prototype._inheritParticleInfoToSubEmitter = function (subEmitter) {
  60034. if (subEmitter.particleSystem.emitter.position) {
  60035. var emitterMesh = subEmitter.particleSystem.emitter;
  60036. emitterMesh.position.copyFrom(this.position);
  60037. if (subEmitter.inheritDirection) {
  60038. emitterMesh.position.subtractToRef(this.direction, BABYLON.Tmp.Vector3[0]);
  60039. // Look at using Y as forward
  60040. emitterMesh.lookAt(BABYLON.Tmp.Vector3[0], 0, Math.PI / 2);
  60041. }
  60042. }
  60043. else {
  60044. var emitterPosition = subEmitter.particleSystem.emitter;
  60045. emitterPosition.copyFrom(this.position);
  60046. }
  60047. // Set inheritedVelocityOffset to be used when new particles are created
  60048. this.direction.scaleToRef(subEmitter.inheritedVelocityAmount / 2, BABYLON.Tmp.Vector3[0]);
  60049. subEmitter.particleSystem._inheritedVelocityOffset.copyFrom(BABYLON.Tmp.Vector3[0]);
  60050. };
  60051. /** @hidden */
  60052. Particle.prototype._inheritParticleInfoToSubEmitters = function () {
  60053. var _this = this;
  60054. if (this._attachedSubEmitters && this._attachedSubEmitters.length > 0) {
  60055. this._attachedSubEmitters.forEach(function (subEmitter) {
  60056. _this._inheritParticleInfoToSubEmitter(subEmitter);
  60057. });
  60058. }
  60059. };
  60060. /** @hidden */
  60061. Particle.prototype._reset = function () {
  60062. this.age = 0;
  60063. this._currentColorGradient = null;
  60064. this._currentSizeGradient = null;
  60065. this._currentAngularSpeedGradient = null;
  60066. this._currentVelocityGradient = null;
  60067. this._currentLimitVelocityGradient = null;
  60068. this._currentDragGradient = null;
  60069. this.cellIndex = this.particleSystem.startSpriteCellID;
  60070. this._randomCellOffset = undefined;
  60071. };
  60072. /**
  60073. * Copy the properties of particle to another one.
  60074. * @param other the particle to copy the information to.
  60075. */
  60076. Particle.prototype.copyTo = function (other) {
  60077. other.position.copyFrom(this.position);
  60078. if (this._initialDirection) {
  60079. if (other._initialDirection) {
  60080. other._initialDirection.copyFrom(this._initialDirection);
  60081. }
  60082. else {
  60083. other._initialDirection = this._initialDirection.clone();
  60084. }
  60085. }
  60086. else {
  60087. other._initialDirection = null;
  60088. }
  60089. other.direction.copyFrom(this.direction);
  60090. other.color.copyFrom(this.color);
  60091. other.colorStep.copyFrom(this.colorStep);
  60092. other.lifeTime = this.lifeTime;
  60093. other.age = this.age;
  60094. other._randomCellOffset = this._randomCellOffset;
  60095. other.size = this.size;
  60096. other.scale.copyFrom(this.scale);
  60097. other.angle = this.angle;
  60098. other.angularSpeed = this.angularSpeed;
  60099. other.particleSystem = this.particleSystem;
  60100. other.cellIndex = this.cellIndex;
  60101. other.id = this.id;
  60102. other._attachedSubEmitters = this._attachedSubEmitters;
  60103. if (this._currentColorGradient) {
  60104. other._currentColorGradient = this._currentColorGradient;
  60105. other._currentColor1.copyFrom(this._currentColor1);
  60106. other._currentColor2.copyFrom(this._currentColor2);
  60107. }
  60108. if (this._currentSizeGradient) {
  60109. other._currentSizeGradient = this._currentSizeGradient;
  60110. other._currentSize1 = this._currentSize1;
  60111. other._currentSize2 = this._currentSize2;
  60112. }
  60113. if (this._currentAngularSpeedGradient) {
  60114. other._currentAngularSpeedGradient = this._currentAngularSpeedGradient;
  60115. other._currentAngularSpeed1 = this._currentAngularSpeed1;
  60116. other._currentAngularSpeed2 = this._currentAngularSpeed2;
  60117. }
  60118. if (this._currentVelocityGradient) {
  60119. other._currentVelocityGradient = this._currentVelocityGradient;
  60120. other._currentVelocity1 = this._currentVelocity1;
  60121. other._currentVelocity2 = this._currentVelocity2;
  60122. }
  60123. if (this._currentLimitVelocityGradient) {
  60124. other._currentLimitVelocityGradient = this._currentLimitVelocityGradient;
  60125. other._currentLimitVelocity1 = this._currentLimitVelocity1;
  60126. other._currentLimitVelocity2 = this._currentLimitVelocity2;
  60127. }
  60128. if (this._currentDragGradient) {
  60129. other._currentDragGradient = this._currentDragGradient;
  60130. other._currentDrag1 = this._currentDrag1;
  60131. other._currentDrag2 = this._currentDrag2;
  60132. }
  60133. if (this.particleSystem.isAnimationSheetEnabled) {
  60134. other._initialStartSpriteCellID = this._initialStartSpriteCellID;
  60135. other._initialEndSpriteCellID = this._initialEndSpriteCellID;
  60136. }
  60137. if (this.particleSystem.useRampGradients) {
  60138. other.remapData.copyFrom(this.remapData);
  60139. }
  60140. if (this._randomNoiseCoordinates1) {
  60141. if (other._randomNoiseCoordinates1) {
  60142. other._randomNoiseCoordinates1.copyFrom(this._randomNoiseCoordinates1);
  60143. other._randomNoiseCoordinates2.copyFrom(this._randomNoiseCoordinates2);
  60144. }
  60145. else {
  60146. other._randomNoiseCoordinates1 = this._randomNoiseCoordinates1.clone();
  60147. other._randomNoiseCoordinates2 = this._randomNoiseCoordinates2.clone();
  60148. }
  60149. }
  60150. };
  60151. Particle._Count = 0;
  60152. return Particle;
  60153. }());
  60154. BABYLON.Particle = Particle;
  60155. })(BABYLON || (BABYLON = {}));
  60156. //# sourceMappingURL=babylon.particle.js.map
  60157. var BABYLON;
  60158. (function (BABYLON) {
  60159. /**
  60160. * This represents the base class for particle system in Babylon.
  60161. * 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.
  60162. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  60163. * @example https://doc.babylonjs.com/babylon101/particles
  60164. */
  60165. var BaseParticleSystem = /** @class */ (function () {
  60166. /**
  60167. * Instantiates a particle system.
  60168. * 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.
  60169. * @param name The name of the particle system
  60170. */
  60171. function BaseParticleSystem(name) {
  60172. /**
  60173. * List of animations used by the particle system.
  60174. */
  60175. this.animations = [];
  60176. /**
  60177. * The rendering group used by the Particle system to chose when to render.
  60178. */
  60179. this.renderingGroupId = 0;
  60180. /**
  60181. * The emitter represents the Mesh or position we are attaching the particle system to.
  60182. */
  60183. this.emitter = null;
  60184. /**
  60185. * The maximum number of particles to emit per frame
  60186. */
  60187. this.emitRate = 10;
  60188. /**
  60189. * If you want to launch only a few particles at once, that can be done, as well.
  60190. */
  60191. this.manualEmitCount = -1;
  60192. /**
  60193. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  60194. */
  60195. this.updateSpeed = 0.01;
  60196. /**
  60197. * The amount of time the particle system is running (depends of the overall update speed).
  60198. */
  60199. this.targetStopDuration = 0;
  60200. /**
  60201. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  60202. */
  60203. this.disposeOnStop = false;
  60204. /**
  60205. * Minimum power of emitting particles.
  60206. */
  60207. this.minEmitPower = 1;
  60208. /**
  60209. * Maximum power of emitting particles.
  60210. */
  60211. this.maxEmitPower = 1;
  60212. /**
  60213. * Minimum life time of emitting particles.
  60214. */
  60215. this.minLifeTime = 1;
  60216. /**
  60217. * Maximum life time of emitting particles.
  60218. */
  60219. this.maxLifeTime = 1;
  60220. /**
  60221. * Minimum Size of emitting particles.
  60222. */
  60223. this.minSize = 1;
  60224. /**
  60225. * Maximum Size of emitting particles.
  60226. */
  60227. this.maxSize = 1;
  60228. /**
  60229. * Minimum scale of emitting particles on X axis.
  60230. */
  60231. this.minScaleX = 1;
  60232. /**
  60233. * Maximum scale of emitting particles on X axis.
  60234. */
  60235. this.maxScaleX = 1;
  60236. /**
  60237. * Minimum scale of emitting particles on Y axis.
  60238. */
  60239. this.minScaleY = 1;
  60240. /**
  60241. * Maximum scale of emitting particles on Y axis.
  60242. */
  60243. this.maxScaleY = 1;
  60244. /**
  60245. * Gets or sets the minimal initial rotation in radians.
  60246. */
  60247. this.minInitialRotation = 0;
  60248. /**
  60249. * Gets or sets the maximal initial rotation in radians.
  60250. */
  60251. this.maxInitialRotation = 0;
  60252. /**
  60253. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  60254. */
  60255. this.minAngularSpeed = 0;
  60256. /**
  60257. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  60258. */
  60259. this.maxAngularSpeed = 0;
  60260. /**
  60261. * The layer mask we are rendering the particles through.
  60262. */
  60263. this.layerMask = 0x0FFFFFFF;
  60264. /**
  60265. * This can help using your own shader to render the particle system.
  60266. * The according effect will be created
  60267. */
  60268. this.customShader = null;
  60269. /**
  60270. * By default particle system starts as soon as they are created. This prevents the
  60271. * automatic start to happen and let you decide when to start emitting particles.
  60272. */
  60273. this.preventAutoStart = false;
  60274. /** Gets or sets the strength to apply to the noise value (default is (10, 10, 10)) */
  60275. this.noiseStrength = new BABYLON.Vector3(10, 10, 10);
  60276. /**
  60277. * Callback triggered when the particle animation is ending.
  60278. */
  60279. this.onAnimationEnd = null;
  60280. /**
  60281. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  60282. */
  60283. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  60284. /**
  60285. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  60286. * to override the particles.
  60287. */
  60288. this.forceDepthWrite = false;
  60289. /** 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 */
  60290. this.preWarmCycles = 0;
  60291. /** Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) */
  60292. this.preWarmStepOffset = 1;
  60293. /**
  60294. * 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)
  60295. */
  60296. this.spriteCellChangeSpeed = 1;
  60297. /**
  60298. * If using a spritesheet (isAnimationSheetEnabled) defines the first sprite cell to display
  60299. */
  60300. this.startSpriteCellID = 0;
  60301. /**
  60302. * If using a spritesheet (isAnimationSheetEnabled) defines the last sprite cell to display
  60303. */
  60304. this.endSpriteCellID = 0;
  60305. /**
  60306. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use
  60307. */
  60308. this.spriteCellWidth = 0;
  60309. /**
  60310. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use
  60311. */
  60312. this.spriteCellHeight = 0;
  60313. /**
  60314. * This allows the system to random pick the start cell ID between startSpriteCellID and endSpriteCellID
  60315. */
  60316. this.spriteRandomStartCell = false;
  60317. /** Gets or sets a Vector2 used to move the pivot (by default (0,0)) */
  60318. this.translationPivot = new BABYLON.Vector2(0, 0);
  60319. /**
  60320. * Gets or sets a boolean indicating that hosted animations (in the system.animations array) must be started when system.start() is called
  60321. */
  60322. this.beginAnimationOnStart = false;
  60323. /**
  60324. * Gets or sets the frame to start the animation from when beginAnimationOnStart is true
  60325. */
  60326. this.beginAnimationFrom = 0;
  60327. /**
  60328. * Gets or sets the frame to end the animation on when beginAnimationOnStart is true
  60329. */
  60330. this.beginAnimationTo = 60;
  60331. /**
  60332. * Gets or sets a boolean indicating if animations must loop when beginAnimationOnStart is true
  60333. */
  60334. this.beginAnimationLoop = false;
  60335. /**
  60336. * You can use gravity if you want to give an orientation to your particles.
  60337. */
  60338. this.gravity = BABYLON.Vector3.Zero();
  60339. this._colorGradients = null;
  60340. this._sizeGradients = null;
  60341. this._lifeTimeGradients = null;
  60342. this._angularSpeedGradients = null;
  60343. this._velocityGradients = null;
  60344. this._limitVelocityGradients = null;
  60345. this._dragGradients = null;
  60346. this._emitRateGradients = null;
  60347. this._startSizeGradients = null;
  60348. this._rampGradients = null;
  60349. this._colorRemapGradients = null;
  60350. this._alphaRemapGradients = null;
  60351. /**
  60352. * Defines the delay in milliseconds before starting the system (0 by default)
  60353. */
  60354. this.startDelay = 0;
  60355. /** Gets or sets a value indicating the damping to apply if the limit velocity factor is reached */
  60356. this.limitVelocityDamping = 0.4;
  60357. /**
  60358. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  60359. */
  60360. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  60361. /**
  60362. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  60363. */
  60364. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  60365. /**
  60366. * Color the particle will have at the end of its lifetime
  60367. */
  60368. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  60369. /**
  60370. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel
  60371. */
  60372. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  60373. /** @hidden */
  60374. this._isSubEmitter = false;
  60375. /**
  60376. * Gets or sets the billboard mode to use when isBillboardBased = true.
  60377. * Value can be: ParticleSystem.BILLBOARDMODE_ALL, ParticleSystem.BILLBOARDMODE_Y, ParticleSystem.BILLBOARDMODE_STRETCHED
  60378. */
  60379. this.billboardMode = BABYLON.ParticleSystem.BILLBOARDMODE_ALL;
  60380. this._isBillboardBased = true;
  60381. /**
  60382. * Local cache of defines for image processing.
  60383. */
  60384. this._imageProcessingConfigurationDefines = new BABYLON.ImageProcessingConfigurationDefines();
  60385. this.id = name;
  60386. this.name = name;
  60387. }
  60388. Object.defineProperty(BaseParticleSystem.prototype, "isAnimationSheetEnabled", {
  60389. /**
  60390. * Gets or sets whether an animation sprite sheet is enabled or not on the particle system
  60391. */
  60392. get: function () {
  60393. return this._isAnimationSheetEnabled;
  60394. },
  60395. set: function (value) {
  60396. if (this._isAnimationSheetEnabled == value) {
  60397. return;
  60398. }
  60399. this._isAnimationSheetEnabled = value;
  60400. this._reset();
  60401. },
  60402. enumerable: true,
  60403. configurable: true
  60404. });
  60405. /**
  60406. * Get hosting scene
  60407. * @returns the scene
  60408. */
  60409. BaseParticleSystem.prototype.getScene = function () {
  60410. return this._scene;
  60411. };
  60412. BaseParticleSystem.prototype._hasTargetStopDurationDependantGradient = function () {
  60413. return (this._startSizeGradients && this._startSizeGradients.length > 0)
  60414. || (this._emitRateGradients && this._emitRateGradients.length > 0)
  60415. || (this._lifeTimeGradients && this._lifeTimeGradients.length > 0);
  60416. };
  60417. /**
  60418. * Gets the current list of drag gradients.
  60419. * You must use addDragGradient and removeDragGradient to udpate this list
  60420. * @returns the list of drag gradients
  60421. */
  60422. BaseParticleSystem.prototype.getDragGradients = function () {
  60423. return this._dragGradients;
  60424. };
  60425. /**
  60426. * Gets the current list of limit velocity gradients.
  60427. * You must use addLimitVelocityGradient and removeLimitVelocityGradient to udpate this list
  60428. * @returns the list of limit velocity gradients
  60429. */
  60430. BaseParticleSystem.prototype.getLimitVelocityGradients = function () {
  60431. return this._limitVelocityGradients;
  60432. };
  60433. /**
  60434. * Gets the current list of color gradients.
  60435. * You must use addColorGradient and removeColorGradient to udpate this list
  60436. * @returns the list of color gradients
  60437. */
  60438. BaseParticleSystem.prototype.getColorGradients = function () {
  60439. return this._colorGradients;
  60440. };
  60441. /**
  60442. * Gets the current list of size gradients.
  60443. * You must use addSizeGradient and removeSizeGradient to udpate this list
  60444. * @returns the list of size gradients
  60445. */
  60446. BaseParticleSystem.prototype.getSizeGradients = function () {
  60447. return this._sizeGradients;
  60448. };
  60449. /**
  60450. * Gets the current list of color remap gradients.
  60451. * You must use addColorRemapGradient and removeColorRemapGradient to udpate this list
  60452. * @returns the list of color remap gradients
  60453. */
  60454. BaseParticleSystem.prototype.getColorRemapGradients = function () {
  60455. return this._colorRemapGradients;
  60456. };
  60457. /**
  60458. * Gets the current list of alpha remap gradients.
  60459. * You must use addAlphaRemapGradient and removeAlphaRemapGradient to udpate this list
  60460. * @returns the list of alpha remap gradients
  60461. */
  60462. BaseParticleSystem.prototype.getAlphaRemapGradients = function () {
  60463. return this._alphaRemapGradients;
  60464. };
  60465. /**
  60466. * Gets the current list of life time gradients.
  60467. * You must use addLifeTimeGradient and removeLifeTimeGradient to udpate this list
  60468. * @returns the list of life time gradients
  60469. */
  60470. BaseParticleSystem.prototype.getLifeTimeGradients = function () {
  60471. return this._lifeTimeGradients;
  60472. };
  60473. /**
  60474. * Gets the current list of angular speed gradients.
  60475. * You must use addAngularSpeedGradient and removeAngularSpeedGradient to udpate this list
  60476. * @returns the list of angular speed gradients
  60477. */
  60478. BaseParticleSystem.prototype.getAngularSpeedGradients = function () {
  60479. return this._angularSpeedGradients;
  60480. };
  60481. /**
  60482. * Gets the current list of velocity gradients.
  60483. * You must use addVelocityGradient and removeVelocityGradient to udpate this list
  60484. * @returns the list of velocity gradients
  60485. */
  60486. BaseParticleSystem.prototype.getVelocityGradients = function () {
  60487. return this._velocityGradients;
  60488. };
  60489. /**
  60490. * Gets the current list of start size gradients.
  60491. * You must use addStartSizeGradient and removeStartSizeGradient to udpate this list
  60492. * @returns the list of start size gradients
  60493. */
  60494. BaseParticleSystem.prototype.getStartSizeGradients = function () {
  60495. return this._startSizeGradients;
  60496. };
  60497. /**
  60498. * Gets the current list of emit rate gradients.
  60499. * You must use addEmitRateGradient and removeEmitRateGradient to udpate this list
  60500. * @returns the list of emit rate gradients
  60501. */
  60502. BaseParticleSystem.prototype.getEmitRateGradients = function () {
  60503. return this._emitRateGradients;
  60504. };
  60505. Object.defineProperty(BaseParticleSystem.prototype, "direction1", {
  60506. /**
  60507. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  60508. * This only works when particleEmitterTyps is a BoxParticleEmitter
  60509. */
  60510. get: function () {
  60511. if (this.particleEmitterType.direction1) {
  60512. return this.particleEmitterType.direction1;
  60513. }
  60514. return BABYLON.Vector3.Zero();
  60515. },
  60516. set: function (value) {
  60517. if (this.particleEmitterType.direction1) {
  60518. this.particleEmitterType.direction1 = value;
  60519. }
  60520. },
  60521. enumerable: true,
  60522. configurable: true
  60523. });
  60524. Object.defineProperty(BaseParticleSystem.prototype, "direction2", {
  60525. /**
  60526. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  60527. * This only works when particleEmitterTyps is a BoxParticleEmitter
  60528. */
  60529. get: function () {
  60530. if (this.particleEmitterType.direction2) {
  60531. return this.particleEmitterType.direction2;
  60532. }
  60533. return BABYLON.Vector3.Zero();
  60534. },
  60535. set: function (value) {
  60536. if (this.particleEmitterType.direction2) {
  60537. this.particleEmitterType.direction2 = value;
  60538. }
  60539. },
  60540. enumerable: true,
  60541. configurable: true
  60542. });
  60543. Object.defineProperty(BaseParticleSystem.prototype, "minEmitBox", {
  60544. /**
  60545. * 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.
  60546. * This only works when particleEmitterTyps is a BoxParticleEmitter
  60547. */
  60548. get: function () {
  60549. if (this.particleEmitterType.minEmitBox) {
  60550. return this.particleEmitterType.minEmitBox;
  60551. }
  60552. return BABYLON.Vector3.Zero();
  60553. },
  60554. set: function (value) {
  60555. if (this.particleEmitterType.minEmitBox) {
  60556. this.particleEmitterType.minEmitBox = value;
  60557. }
  60558. },
  60559. enumerable: true,
  60560. configurable: true
  60561. });
  60562. Object.defineProperty(BaseParticleSystem.prototype, "maxEmitBox", {
  60563. /**
  60564. * 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.
  60565. * This only works when particleEmitterTyps is a BoxParticleEmitter
  60566. */
  60567. get: function () {
  60568. if (this.particleEmitterType.maxEmitBox) {
  60569. return this.particleEmitterType.maxEmitBox;
  60570. }
  60571. return BABYLON.Vector3.Zero();
  60572. },
  60573. set: function (value) {
  60574. if (this.particleEmitterType.maxEmitBox) {
  60575. this.particleEmitterType.maxEmitBox = value;
  60576. }
  60577. },
  60578. enumerable: true,
  60579. configurable: true
  60580. });
  60581. Object.defineProperty(BaseParticleSystem.prototype, "isBillboardBased", {
  60582. /**
  60583. * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction
  60584. */
  60585. get: function () {
  60586. return this._isBillboardBased;
  60587. },
  60588. set: function (value) {
  60589. if (this._isBillboardBased === value) {
  60590. return;
  60591. }
  60592. this._isBillboardBased = value;
  60593. this._reset();
  60594. },
  60595. enumerable: true,
  60596. configurable: true
  60597. });
  60598. Object.defineProperty(BaseParticleSystem.prototype, "imageProcessingConfiguration", {
  60599. /**
  60600. * Gets the image processing configuration used either in this material.
  60601. */
  60602. get: function () {
  60603. return this._imageProcessingConfiguration;
  60604. },
  60605. /**
  60606. * Sets the Default image processing configuration used either in the this material.
  60607. *
  60608. * If sets to null, the scene one is in use.
  60609. */
  60610. set: function (value) {
  60611. this._attachImageProcessingConfiguration(value);
  60612. },
  60613. enumerable: true,
  60614. configurable: true
  60615. });
  60616. /**
  60617. * Attaches a new image processing configuration to the Standard Material.
  60618. * @param configuration
  60619. */
  60620. BaseParticleSystem.prototype._attachImageProcessingConfiguration = function (configuration) {
  60621. if (configuration === this._imageProcessingConfiguration) {
  60622. return;
  60623. }
  60624. // Pick the scene configuration if needed.
  60625. if (!configuration) {
  60626. this._imageProcessingConfiguration = this._scene.imageProcessingConfiguration;
  60627. }
  60628. else {
  60629. this._imageProcessingConfiguration = configuration;
  60630. }
  60631. };
  60632. /** @hidden */
  60633. BaseParticleSystem.prototype._reset = function () {
  60634. };
  60635. /** @hidden */
  60636. BaseParticleSystem.prototype._removeGradientAndTexture = function (gradient, gradients, texture) {
  60637. if (!gradients) {
  60638. return this;
  60639. }
  60640. var index = 0;
  60641. for (var _i = 0, gradients_1 = gradients; _i < gradients_1.length; _i++) {
  60642. var valueGradient = gradients_1[_i];
  60643. if (valueGradient.gradient === gradient) {
  60644. gradients.splice(index, 1);
  60645. break;
  60646. }
  60647. index++;
  60648. }
  60649. if (texture) {
  60650. texture.dispose();
  60651. }
  60652. return this;
  60653. };
  60654. /**
  60655. * Creates a Point Emitter for the particle system (emits directly from the emitter position)
  60656. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  60657. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  60658. * @returns the emitter
  60659. */
  60660. BaseParticleSystem.prototype.createPointEmitter = function (direction1, direction2) {
  60661. var particleEmitter = new BABYLON.PointParticleEmitter();
  60662. particleEmitter.direction1 = direction1;
  60663. particleEmitter.direction2 = direction2;
  60664. this.particleEmitterType = particleEmitter;
  60665. return particleEmitter;
  60666. };
  60667. /**
  60668. * Creates a Hemisphere Emitter for the particle system (emits along the hemisphere radius)
  60669. * @param radius The radius of the hemisphere to emit from
  60670. * @param radiusRange The range of the hemisphere to emit from [0-1] 0 Surface Only, 1 Entire Radius
  60671. * @returns the emitter
  60672. */
  60673. BaseParticleSystem.prototype.createHemisphericEmitter = function (radius, radiusRange) {
  60674. if (radius === void 0) { radius = 1; }
  60675. if (radiusRange === void 0) { radiusRange = 1; }
  60676. var particleEmitter = new BABYLON.HemisphericParticleEmitter(radius, radiusRange);
  60677. this.particleEmitterType = particleEmitter;
  60678. return particleEmitter;
  60679. };
  60680. /**
  60681. * Creates a Sphere Emitter for the particle system (emits along the sphere radius)
  60682. * @param radius The radius of the sphere to emit from
  60683. * @param radiusRange The range of the sphere to emit from [0-1] 0 Surface Only, 1 Entire Radius
  60684. * @returns the emitter
  60685. */
  60686. BaseParticleSystem.prototype.createSphereEmitter = function (radius, radiusRange) {
  60687. if (radius === void 0) { radius = 1; }
  60688. if (radiusRange === void 0) { radiusRange = 1; }
  60689. var particleEmitter = new BABYLON.SphereParticleEmitter(radius, radiusRange);
  60690. this.particleEmitterType = particleEmitter;
  60691. return particleEmitter;
  60692. };
  60693. /**
  60694. * Creates a Directed Sphere Emitter for the particle system (emits between direction1 and direction2)
  60695. * @param radius The radius of the sphere to emit from
  60696. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  60697. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  60698. * @returns the emitter
  60699. */
  60700. BaseParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  60701. if (radius === void 0) { radius = 1; }
  60702. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  60703. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  60704. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  60705. this.particleEmitterType = particleEmitter;
  60706. return particleEmitter;
  60707. };
  60708. /**
  60709. * Creates a Cylinder Emitter for the particle system (emits from the cylinder to the particle position)
  60710. * @param radius The radius of the emission cylinder
  60711. * @param height The height of the emission cylinder
  60712. * @param radiusRange The range of emission [0-1] 0 Surface only, 1 Entire Radius
  60713. * @param directionRandomizer How much to randomize the particle direction [0-1]
  60714. * @returns the emitter
  60715. */
  60716. BaseParticleSystem.prototype.createCylinderEmitter = function (radius, height, radiusRange, directionRandomizer) {
  60717. if (radius === void 0) { radius = 1; }
  60718. if (height === void 0) { height = 1; }
  60719. if (radiusRange === void 0) { radiusRange = 1; }
  60720. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  60721. var particleEmitter = new BABYLON.CylinderParticleEmitter(radius, height, radiusRange, directionRandomizer);
  60722. this.particleEmitterType = particleEmitter;
  60723. return particleEmitter;
  60724. };
  60725. /**
  60726. * Creates a Directed Cylinder Emitter for the particle system (emits between direction1 and direction2)
  60727. * @param radius The radius of the cylinder to emit from
  60728. * @param height The height of the emission cylinder
  60729. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  60730. * @param direction1 Particles are emitted between the direction1 and direction2 from within the cylinder
  60731. * @param direction2 Particles are emitted between the direction1 and direction2 from within the cylinder
  60732. * @returns the emitter
  60733. */
  60734. BaseParticleSystem.prototype.createDirectedCylinderEmitter = function (radius, height, radiusRange, direction1, direction2) {
  60735. if (radius === void 0) { radius = 1; }
  60736. if (height === void 0) { height = 1; }
  60737. if (radiusRange === void 0) { radiusRange = 1; }
  60738. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  60739. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  60740. var particleEmitter = new BABYLON.CylinderDirectedParticleEmitter(radius, height, radiusRange, direction1, direction2);
  60741. this.particleEmitterType = particleEmitter;
  60742. return particleEmitter;
  60743. };
  60744. /**
  60745. * Creates a Cone Emitter for the particle system (emits from the cone to the particle position)
  60746. * @param radius The radius of the cone to emit from
  60747. * @param angle The base angle of the cone
  60748. * @returns the emitter
  60749. */
  60750. BaseParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  60751. if (radius === void 0) { radius = 1; }
  60752. if (angle === void 0) { angle = Math.PI / 4; }
  60753. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  60754. this.particleEmitterType = particleEmitter;
  60755. return particleEmitter;
  60756. };
  60757. /**
  60758. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  60759. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  60760. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  60761. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  60762. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  60763. * @returns the emitter
  60764. */
  60765. BaseParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  60766. var particleEmitter = new BABYLON.BoxParticleEmitter();
  60767. this.particleEmitterType = particleEmitter;
  60768. this.direction1 = direction1;
  60769. this.direction2 = direction2;
  60770. this.minEmitBox = minEmitBox;
  60771. this.maxEmitBox = maxEmitBox;
  60772. return particleEmitter;
  60773. };
  60774. /**
  60775. * Source color is added to the destination color without alpha affecting the result
  60776. */
  60777. BaseParticleSystem.BLENDMODE_ONEONE = 0;
  60778. /**
  60779. * Blend current color and particle color using particle’s alpha
  60780. */
  60781. BaseParticleSystem.BLENDMODE_STANDARD = 1;
  60782. /**
  60783. * Add current color and particle color multiplied by particle’s alpha
  60784. */
  60785. BaseParticleSystem.BLENDMODE_ADD = 2;
  60786. /**
  60787. * Multiply current color with particle color
  60788. */
  60789. BaseParticleSystem.BLENDMODE_MULTIPLY = 3;
  60790. /**
  60791. * Multiply current color with particle color then add current color and particle color multiplied by particle’s alpha
  60792. */
  60793. BaseParticleSystem.BLENDMODE_MULTIPLYADD = 4;
  60794. return BaseParticleSystem;
  60795. }());
  60796. BABYLON.BaseParticleSystem = BaseParticleSystem;
  60797. })(BABYLON || (BABYLON = {}));
  60798. //# sourceMappingURL=babylon.baseParticleSystem.js.map
  60799. var BABYLON;
  60800. (function (BABYLON) {
  60801. /**
  60802. * This represents a particle system in Babylon.
  60803. * 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.
  60804. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  60805. * @example https://doc.babylonjs.com/babylon101/particles
  60806. */
  60807. var ParticleSystem = /** @class */ (function (_super) {
  60808. __extends(ParticleSystem, _super);
  60809. /**
  60810. * Instantiates a particle system.
  60811. * 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.
  60812. * @param name The name of the particle system
  60813. * @param capacity The max number of particles alive at the same time
  60814. * @param scene The scene the particle system belongs to
  60815. * @param customEffect a custom effect used to change the way particles are rendered by default
  60816. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  60817. * @param epsilon Offset used to render the particles
  60818. */
  60819. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  60820. if (customEffect === void 0) { customEffect = null; }
  60821. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  60822. if (epsilon === void 0) { epsilon = 0.01; }
  60823. var _this = _super.call(this, name) || this;
  60824. /**
  60825. * @hidden
  60826. */
  60827. _this._inheritedVelocityOffset = new BABYLON.Vector3();
  60828. /**
  60829. * An event triggered when the system is disposed
  60830. */
  60831. _this.onDisposeObservable = new BABYLON.Observable();
  60832. _this._particles = new Array();
  60833. _this._stockParticles = new Array();
  60834. _this._newPartsExcess = 0;
  60835. _this._vertexBuffers = {};
  60836. _this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  60837. _this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  60838. _this._scaledDirection = BABYLON.Vector3.Zero();
  60839. _this._scaledGravity = BABYLON.Vector3.Zero();
  60840. _this._currentRenderId = -1;
  60841. _this._useInstancing = false;
  60842. _this._started = false;
  60843. _this._stopped = false;
  60844. _this._actualFrame = 0;
  60845. /** @hidden */
  60846. _this._currentEmitRate1 = 0;
  60847. /** @hidden */
  60848. _this._currentEmitRate2 = 0;
  60849. /** @hidden */
  60850. _this._currentStartSize1 = 0;
  60851. /** @hidden */
  60852. _this._currentStartSize2 = 0;
  60853. _this._rawTextureWidth = 256;
  60854. _this._useRampGradients = false;
  60855. /**
  60856. * @hidden
  60857. * If the particle systems emitter should be disposed when the particle system is disposed
  60858. */
  60859. _this._disposeEmitterOnDispose = false;
  60860. // start of sub system methods
  60861. /**
  60862. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  60863. * Its lifetime will start back at 0.
  60864. */
  60865. _this.recycleParticle = function (particle) {
  60866. // move particle from activeParticle list to stock particles
  60867. var lastParticle = _this._particles.pop();
  60868. if (lastParticle !== particle) {
  60869. lastParticle.copyTo(particle);
  60870. }
  60871. _this._stockParticles.push(lastParticle);
  60872. };
  60873. _this._createParticle = function () {
  60874. var particle;
  60875. if (_this._stockParticles.length !== 0) {
  60876. particle = _this._stockParticles.pop();
  60877. particle._reset();
  60878. }
  60879. else {
  60880. particle = new BABYLON.Particle(_this);
  60881. }
  60882. // Attach emitters
  60883. if (_this._subEmitters && _this._subEmitters.length > 0) {
  60884. var subEmitters = _this._subEmitters[Math.floor(Math.random() * _this._subEmitters.length)];
  60885. particle._attachedSubEmitters = [];
  60886. subEmitters.forEach(function (subEmitter) {
  60887. if (subEmitter.type === BABYLON.SubEmitterType.ATTACHED) {
  60888. var newEmitter = subEmitter.clone();
  60889. particle._attachedSubEmitters.push(newEmitter);
  60890. newEmitter.particleSystem.start();
  60891. }
  60892. });
  60893. }
  60894. return particle;
  60895. };
  60896. _this._emitFromParticle = function (particle) {
  60897. if (!_this._subEmitters || _this._subEmitters.length === 0) {
  60898. return;
  60899. }
  60900. var templateIndex = Math.floor(Math.random() * _this._subEmitters.length);
  60901. _this._subEmitters[templateIndex].forEach(function (subEmitter) {
  60902. if (subEmitter.type === BABYLON.SubEmitterType.END) {
  60903. var subSystem = subEmitter.clone();
  60904. particle._inheritParticleInfoToSubEmitter(subSystem);
  60905. subSystem.particleSystem._rootParticleSystem = _this;
  60906. _this.activeSubSystems.push(subSystem.particleSystem);
  60907. subSystem.particleSystem.start();
  60908. }
  60909. });
  60910. };
  60911. _this._capacity = capacity;
  60912. _this._epsilon = epsilon;
  60913. _this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  60914. _this._scene = scene || BABYLON.Engine.LastCreatedScene;
  60915. // Setup the default processing configuration to the scene.
  60916. _this._attachImageProcessingConfiguration(null);
  60917. _this._customEffect = customEffect;
  60918. _this._scene.particleSystems.push(_this);
  60919. _this._useInstancing = _this._scene.getEngine().getCaps().instancedArrays;
  60920. _this._createIndexBuffer();
  60921. _this._createVertexBuffers();
  60922. // Default emitter type
  60923. _this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  60924. // Update
  60925. _this.updateFunction = function (particles) {
  60926. var noiseTextureSize = null;
  60927. var noiseTextureData = null;
  60928. if (_this.noiseTexture) { // We need to get texture data back to CPU
  60929. noiseTextureSize = _this.noiseTexture.getSize();
  60930. noiseTextureData = (_this.noiseTexture.getContent());
  60931. }
  60932. var _loop_1 = function () {
  60933. particle = particles[index];
  60934. var scaledUpdateSpeed = _this._scaledUpdateSpeed;
  60935. var previousAge = particle.age;
  60936. particle.age += scaledUpdateSpeed;
  60937. // Evaluate step to death
  60938. if (particle.age > particle.lifeTime) {
  60939. var diff = particle.age - previousAge;
  60940. var oldDiff = particle.lifeTime - previousAge;
  60941. scaledUpdateSpeed = (oldDiff * scaledUpdateSpeed) / diff;
  60942. particle.age = particle.lifeTime;
  60943. }
  60944. var ratio = particle.age / particle.lifeTime;
  60945. // Color
  60946. if (_this._colorGradients && _this._colorGradients.length > 0) {
  60947. BABYLON.Tools.GetCurrentGradient(ratio, _this._colorGradients, function (currentGradient, nextGradient, scale) {
  60948. if (currentGradient !== particle._currentColorGradient) {
  60949. particle._currentColor1.copyFrom(particle._currentColor2);
  60950. nextGradient.getColorToRef(particle._currentColor2);
  60951. particle._currentColorGradient = currentGradient;
  60952. }
  60953. BABYLON.Color4.LerpToRef(particle._currentColor1, particle._currentColor2, scale, particle.color);
  60954. });
  60955. }
  60956. else {
  60957. particle.colorStep.scaleToRef(scaledUpdateSpeed, _this._scaledColorStep);
  60958. particle.color.addInPlace(_this._scaledColorStep);
  60959. if (particle.color.a < 0) {
  60960. particle.color.a = 0;
  60961. }
  60962. }
  60963. // Angular speed
  60964. if (_this._angularSpeedGradients && _this._angularSpeedGradients.length > 0) {
  60965. BABYLON.Tools.GetCurrentGradient(ratio, _this._angularSpeedGradients, function (currentGradient, nextGradient, scale) {
  60966. if (currentGradient !== particle._currentAngularSpeedGradient) {
  60967. particle._currentAngularSpeed1 = particle._currentAngularSpeed2;
  60968. particle._currentAngularSpeed2 = nextGradient.getFactor();
  60969. particle._currentAngularSpeedGradient = currentGradient;
  60970. }
  60971. particle.angularSpeed = BABYLON.Scalar.Lerp(particle._currentAngularSpeed1, particle._currentAngularSpeed2, scale);
  60972. });
  60973. }
  60974. particle.angle += particle.angularSpeed * scaledUpdateSpeed;
  60975. // Direction
  60976. var directionScale = scaledUpdateSpeed;
  60977. /// Velocity
  60978. if (_this._velocityGradients && _this._velocityGradients.length > 0) {
  60979. BABYLON.Tools.GetCurrentGradient(ratio, _this._velocityGradients, function (currentGradient, nextGradient, scale) {
  60980. if (currentGradient !== particle._currentVelocityGradient) {
  60981. particle._currentVelocity1 = particle._currentVelocity2;
  60982. particle._currentVelocity2 = nextGradient.getFactor();
  60983. particle._currentVelocityGradient = currentGradient;
  60984. }
  60985. directionScale *= BABYLON.Scalar.Lerp(particle._currentVelocity1, particle._currentVelocity2, scale);
  60986. });
  60987. }
  60988. particle.direction.scaleToRef(directionScale, _this._scaledDirection);
  60989. /// Limit velocity
  60990. if (_this._limitVelocityGradients && _this._limitVelocityGradients.length > 0) {
  60991. BABYLON.Tools.GetCurrentGradient(ratio, _this._limitVelocityGradients, function (currentGradient, nextGradient, scale) {
  60992. if (currentGradient !== particle._currentLimitVelocityGradient) {
  60993. particle._currentLimitVelocity1 = particle._currentLimitVelocity2;
  60994. particle._currentLimitVelocity2 = nextGradient.getFactor();
  60995. particle._currentLimitVelocityGradient = currentGradient;
  60996. }
  60997. var limitVelocity = BABYLON.Scalar.Lerp(particle._currentLimitVelocity1, particle._currentLimitVelocity2, scale);
  60998. var currentVelocity = particle.direction.length();
  60999. if (currentVelocity > limitVelocity) {
  61000. particle.direction.scaleInPlace(_this.limitVelocityDamping);
  61001. }
  61002. });
  61003. }
  61004. /// Drag
  61005. if (_this._dragGradients && _this._dragGradients.length > 0) {
  61006. BABYLON.Tools.GetCurrentGradient(ratio, _this._dragGradients, function (currentGradient, nextGradient, scale) {
  61007. if (currentGradient !== particle._currentDragGradient) {
  61008. particle._currentDrag1 = particle._currentDrag2;
  61009. particle._currentDrag2 = nextGradient.getFactor();
  61010. particle._currentDragGradient = currentGradient;
  61011. }
  61012. var drag = BABYLON.Scalar.Lerp(particle._currentDrag1, particle._currentDrag2, scale);
  61013. _this._scaledDirection.scaleInPlace(1.0 - drag);
  61014. });
  61015. }
  61016. particle.position.addInPlace(_this._scaledDirection);
  61017. // Noise
  61018. if (noiseTextureData && noiseTextureSize) {
  61019. var fetchedColorR = _this._fetchR(particle._randomNoiseCoordinates1.x, particle._randomNoiseCoordinates1.y, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  61020. var fetchedColorG = _this._fetchR(particle._randomNoiseCoordinates1.z, particle._randomNoiseCoordinates2.x, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  61021. var fetchedColorB = _this._fetchR(particle._randomNoiseCoordinates2.y, particle._randomNoiseCoordinates2.z, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  61022. var force = BABYLON.Tmp.Vector3[0];
  61023. var scaledForce = BABYLON.Tmp.Vector3[1];
  61024. force.copyFromFloats((2 * fetchedColorR - 1) * _this.noiseStrength.x, (2 * fetchedColorG - 1) * _this.noiseStrength.y, (2 * fetchedColorB - 1) * _this.noiseStrength.z);
  61025. force.scaleToRef(scaledUpdateSpeed, scaledForce);
  61026. particle.direction.addInPlace(scaledForce);
  61027. }
  61028. // Gravity
  61029. _this.gravity.scaleToRef(scaledUpdateSpeed, _this._scaledGravity);
  61030. particle.direction.addInPlace(_this._scaledGravity);
  61031. // Size
  61032. if (_this._sizeGradients && _this._sizeGradients.length > 0) {
  61033. BABYLON.Tools.GetCurrentGradient(ratio, _this._sizeGradients, function (currentGradient, nextGradient, scale) {
  61034. if (currentGradient !== particle._currentSizeGradient) {
  61035. particle._currentSize1 = particle._currentSize2;
  61036. particle._currentSize2 = nextGradient.getFactor();
  61037. particle._currentSizeGradient = currentGradient;
  61038. }
  61039. particle.size = BABYLON.Scalar.Lerp(particle._currentSize1, particle._currentSize2, scale);
  61040. });
  61041. }
  61042. // Remap data
  61043. if (_this._useRampGradients) {
  61044. if (_this._colorRemapGradients && _this._colorRemapGradients.length > 0) {
  61045. BABYLON.Tools.GetCurrentGradient(ratio, _this._colorRemapGradients, function (currentGradient, nextGradient, scale) {
  61046. var min = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  61047. var max = BABYLON.Scalar.Lerp(currentGradient.factor2, nextGradient.factor2, scale);
  61048. particle.remapData.x = min;
  61049. particle.remapData.y = max - min;
  61050. });
  61051. }
  61052. if (_this._alphaRemapGradients && _this._alphaRemapGradients.length > 0) {
  61053. BABYLON.Tools.GetCurrentGradient(ratio, _this._alphaRemapGradients, function (currentGradient, nextGradient, scale) {
  61054. var min = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  61055. var max = BABYLON.Scalar.Lerp(currentGradient.factor2, nextGradient.factor2, scale);
  61056. particle.remapData.z = min;
  61057. particle.remapData.w = max - min;
  61058. });
  61059. }
  61060. }
  61061. if (_this._isAnimationSheetEnabled) {
  61062. particle.updateCellIndex();
  61063. }
  61064. // Update the position of the attached sub-emitters to match their attached particle
  61065. particle._inheritParticleInfoToSubEmitters();
  61066. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  61067. _this._emitFromParticle(particle);
  61068. if (particle._attachedSubEmitters) {
  61069. particle._attachedSubEmitters.forEach(function (subEmitter) {
  61070. subEmitter.particleSystem.disposeOnStop = true;
  61071. subEmitter.particleSystem.stop();
  61072. });
  61073. particle._attachedSubEmitters = null;
  61074. }
  61075. _this.recycleParticle(particle);
  61076. index--;
  61077. return "continue";
  61078. }
  61079. };
  61080. var particle;
  61081. for (var index = 0; index < particles.length; index++) {
  61082. _loop_1();
  61083. }
  61084. };
  61085. return _this;
  61086. }
  61087. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  61088. /**
  61089. * Sets a callback that will be triggered when the system is disposed
  61090. */
  61091. set: function (callback) {
  61092. if (this._onDisposeObserver) {
  61093. this.onDisposeObservable.remove(this._onDisposeObserver);
  61094. }
  61095. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  61096. },
  61097. enumerable: true,
  61098. configurable: true
  61099. });
  61100. Object.defineProperty(ParticleSystem.prototype, "useRampGradients", {
  61101. /** Gets or sets a boolean indicating that ramp gradients must be used
  61102. * @see http://doc.babylonjs.com/babylon101/particles#ramp-gradients
  61103. */
  61104. get: function () {
  61105. return this._useRampGradients;
  61106. },
  61107. set: function (value) {
  61108. if (this._useRampGradients === value) {
  61109. return;
  61110. }
  61111. this._useRampGradients = value;
  61112. this._resetEffect();
  61113. },
  61114. enumerable: true,
  61115. configurable: true
  61116. });
  61117. Object.defineProperty(ParticleSystem.prototype, "particles", {
  61118. //end of Sub-emitter
  61119. /**
  61120. * Gets the current list of active particles
  61121. */
  61122. get: function () {
  61123. return this._particles;
  61124. },
  61125. enumerable: true,
  61126. configurable: true
  61127. });
  61128. /**
  61129. * Returns the string "ParticleSystem"
  61130. * @returns a string containing the class name
  61131. */
  61132. ParticleSystem.prototype.getClassName = function () {
  61133. return "ParticleSystem";
  61134. };
  61135. ParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor, factor2) {
  61136. var newGradient = new BABYLON.FactorGradient();
  61137. newGradient.gradient = gradient;
  61138. newGradient.factor1 = factor;
  61139. newGradient.factor2 = factor2;
  61140. factorGradients.push(newGradient);
  61141. factorGradients.sort(function (a, b) {
  61142. if (a.gradient < b.gradient) {
  61143. return -1;
  61144. }
  61145. else if (a.gradient > b.gradient) {
  61146. return 1;
  61147. }
  61148. return 0;
  61149. });
  61150. };
  61151. ParticleSystem.prototype._removeFactorGradient = function (factorGradients, gradient) {
  61152. if (!factorGradients) {
  61153. return;
  61154. }
  61155. var index = 0;
  61156. for (var _i = 0, factorGradients_1 = factorGradients; _i < factorGradients_1.length; _i++) {
  61157. var factorGradient = factorGradients_1[_i];
  61158. if (factorGradient.gradient === gradient) {
  61159. factorGradients.splice(index, 1);
  61160. break;
  61161. }
  61162. index++;
  61163. }
  61164. };
  61165. /**
  61166. * Adds a new life time gradient
  61167. * @param gradient defines the gradient to use (between 0 and 1)
  61168. * @param factor defines the life time factor to affect to the specified gradient
  61169. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  61170. * @returns the current particle system
  61171. */
  61172. ParticleSystem.prototype.addLifeTimeGradient = function (gradient, factor, factor2) {
  61173. if (!this._lifeTimeGradients) {
  61174. this._lifeTimeGradients = [];
  61175. }
  61176. this._addFactorGradient(this._lifeTimeGradients, gradient, factor, factor2);
  61177. return this;
  61178. };
  61179. /**
  61180. * Remove a specific life time gradient
  61181. * @param gradient defines the gradient to remove
  61182. * @returns the current particle system
  61183. */
  61184. ParticleSystem.prototype.removeLifeTimeGradient = function (gradient) {
  61185. this._removeFactorGradient(this._lifeTimeGradients, gradient);
  61186. return this;
  61187. };
  61188. /**
  61189. * Adds a new size gradient
  61190. * @param gradient defines the gradient to use (between 0 and 1)
  61191. * @param factor defines the size factor to affect to the specified gradient
  61192. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  61193. * @returns the current particle system
  61194. */
  61195. ParticleSystem.prototype.addSizeGradient = function (gradient, factor, factor2) {
  61196. if (!this._sizeGradients) {
  61197. this._sizeGradients = [];
  61198. }
  61199. this._addFactorGradient(this._sizeGradients, gradient, factor, factor2);
  61200. return this;
  61201. };
  61202. /**
  61203. * Remove a specific size gradient
  61204. * @param gradient defines the gradient to remove
  61205. * @returns the current particle system
  61206. */
  61207. ParticleSystem.prototype.removeSizeGradient = function (gradient) {
  61208. this._removeFactorGradient(this._sizeGradients, gradient);
  61209. return this;
  61210. };
  61211. /**
  61212. * Adds a new color remap gradient
  61213. * @param gradient defines the gradient to use (between 0 and 1)
  61214. * @param min defines the color remap minimal range
  61215. * @param max defines the color remap maximal range
  61216. * @returns the current particle system
  61217. */
  61218. ParticleSystem.prototype.addColorRemapGradient = function (gradient, min, max) {
  61219. if (!this._colorRemapGradients) {
  61220. this._colorRemapGradients = [];
  61221. }
  61222. this._addFactorGradient(this._colorRemapGradients, gradient, min, max);
  61223. return this;
  61224. };
  61225. /**
  61226. * Remove a specific color remap gradient
  61227. * @param gradient defines the gradient to remove
  61228. * @returns the current particle system
  61229. */
  61230. ParticleSystem.prototype.removeColorRemapGradient = function (gradient) {
  61231. this._removeFactorGradient(this._colorRemapGradients, gradient);
  61232. return this;
  61233. };
  61234. /**
  61235. * Adds a new alpha remap gradient
  61236. * @param gradient defines the gradient to use (between 0 and 1)
  61237. * @param min defines the alpha remap minimal range
  61238. * @param max defines the alpha remap maximal range
  61239. * @returns the current particle system
  61240. */
  61241. ParticleSystem.prototype.addAlphaRemapGradient = function (gradient, min, max) {
  61242. if (!this._alphaRemapGradients) {
  61243. this._alphaRemapGradients = [];
  61244. }
  61245. this._addFactorGradient(this._alphaRemapGradients, gradient, min, max);
  61246. return this;
  61247. };
  61248. /**
  61249. * Remove a specific alpha remap gradient
  61250. * @param gradient defines the gradient to remove
  61251. * @returns the current particle system
  61252. */
  61253. ParticleSystem.prototype.removeAlphaRemapGradient = function (gradient) {
  61254. this._removeFactorGradient(this._alphaRemapGradients, gradient);
  61255. return this;
  61256. };
  61257. /**
  61258. * Adds a new angular speed gradient
  61259. * @param gradient defines the gradient to use (between 0 and 1)
  61260. * @param factor defines the angular speed to affect to the specified gradient
  61261. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  61262. * @returns the current particle system
  61263. */
  61264. ParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor, factor2) {
  61265. if (!this._angularSpeedGradients) {
  61266. this._angularSpeedGradients = [];
  61267. }
  61268. this._addFactorGradient(this._angularSpeedGradients, gradient, factor, factor2);
  61269. return this;
  61270. };
  61271. /**
  61272. * Remove a specific angular speed gradient
  61273. * @param gradient defines the gradient to remove
  61274. * @returns the current particle system
  61275. */
  61276. ParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  61277. this._removeFactorGradient(this._angularSpeedGradients, gradient);
  61278. return this;
  61279. };
  61280. /**
  61281. * Adds a new velocity gradient
  61282. * @param gradient defines the gradient to use (between 0 and 1)
  61283. * @param factor defines the velocity to affect to the specified gradient
  61284. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  61285. * @returns the current particle system
  61286. */
  61287. ParticleSystem.prototype.addVelocityGradient = function (gradient, factor, factor2) {
  61288. if (!this._velocityGradients) {
  61289. this._velocityGradients = [];
  61290. }
  61291. this._addFactorGradient(this._velocityGradients, gradient, factor, factor2);
  61292. return this;
  61293. };
  61294. /**
  61295. * Remove a specific velocity gradient
  61296. * @param gradient defines the gradient to remove
  61297. * @returns the current particle system
  61298. */
  61299. ParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  61300. this._removeFactorGradient(this._velocityGradients, gradient);
  61301. return this;
  61302. };
  61303. /**
  61304. * Adds a new limit velocity gradient
  61305. * @param gradient defines the gradient to use (between 0 and 1)
  61306. * @param factor defines the limit velocity value to affect to the specified gradient
  61307. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  61308. * @returns the current particle system
  61309. */
  61310. ParticleSystem.prototype.addLimitVelocityGradient = function (gradient, factor, factor2) {
  61311. if (!this._limitVelocityGradients) {
  61312. this._limitVelocityGradients = [];
  61313. }
  61314. this._addFactorGradient(this._limitVelocityGradients, gradient, factor, factor2);
  61315. return this;
  61316. };
  61317. /**
  61318. * Remove a specific limit velocity gradient
  61319. * @param gradient defines the gradient to remove
  61320. * @returns the current particle system
  61321. */
  61322. ParticleSystem.prototype.removeLimitVelocityGradient = function (gradient) {
  61323. this._removeFactorGradient(this._limitVelocityGradients, gradient);
  61324. return this;
  61325. };
  61326. /**
  61327. * Adds a new drag gradient
  61328. * @param gradient defines the gradient to use (between 0 and 1)
  61329. * @param factor defines the drag value to affect to the specified gradient
  61330. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  61331. * @returns the current particle system
  61332. */
  61333. ParticleSystem.prototype.addDragGradient = function (gradient, factor, factor2) {
  61334. if (!this._dragGradients) {
  61335. this._dragGradients = [];
  61336. }
  61337. this._addFactorGradient(this._dragGradients, gradient, factor, factor2);
  61338. return this;
  61339. };
  61340. /**
  61341. * Remove a specific drag gradient
  61342. * @param gradient defines the gradient to remove
  61343. * @returns the current particle system
  61344. */
  61345. ParticleSystem.prototype.removeDragGradient = function (gradient) {
  61346. this._removeFactorGradient(this._dragGradients, gradient);
  61347. return this;
  61348. };
  61349. /**
  61350. * Adds a new emit rate gradient (please note that this will only work if you set the targetStopDuration property)
  61351. * @param gradient defines the gradient to use (between 0 and 1)
  61352. * @param factor defines the emit rate value to affect to the specified gradient
  61353. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  61354. * @returns the current particle system
  61355. */
  61356. ParticleSystem.prototype.addEmitRateGradient = function (gradient, factor, factor2) {
  61357. if (!this._emitRateGradients) {
  61358. this._emitRateGradients = [];
  61359. }
  61360. this._addFactorGradient(this._emitRateGradients, gradient, factor, factor2);
  61361. return this;
  61362. };
  61363. /**
  61364. * Remove a specific emit rate gradient
  61365. * @param gradient defines the gradient to remove
  61366. * @returns the current particle system
  61367. */
  61368. ParticleSystem.prototype.removeEmitRateGradient = function (gradient) {
  61369. this._removeFactorGradient(this._emitRateGradients, gradient);
  61370. return this;
  61371. };
  61372. /**
  61373. * Adds a new start size gradient (please note that this will only work if you set the targetStopDuration property)
  61374. * @param gradient defines the gradient to use (between 0 and 1)
  61375. * @param factor defines the start size value to affect to the specified gradient
  61376. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  61377. * @returns the current particle system
  61378. */
  61379. ParticleSystem.prototype.addStartSizeGradient = function (gradient, factor, factor2) {
  61380. if (!this._startSizeGradients) {
  61381. this._startSizeGradients = [];
  61382. }
  61383. this._addFactorGradient(this._startSizeGradients, gradient, factor, factor2);
  61384. return this;
  61385. };
  61386. /**
  61387. * Remove a specific start size gradient
  61388. * @param gradient defines the gradient to remove
  61389. * @returns the current particle system
  61390. */
  61391. ParticleSystem.prototype.removeStartSizeGradient = function (gradient) {
  61392. this._removeFactorGradient(this._emitRateGradients, gradient);
  61393. return this;
  61394. };
  61395. ParticleSystem.prototype._createRampGradientTexture = function () {
  61396. if (!this._rampGradients || !this._rampGradients.length || this._rampGradientsTexture) {
  61397. return;
  61398. }
  61399. var data = new Uint8Array(this._rawTextureWidth * 4);
  61400. var tmpColor = BABYLON.Tmp.Color3[0];
  61401. for (var x = 0; x < this._rawTextureWidth; x++) {
  61402. var ratio = x / this._rawTextureWidth;
  61403. BABYLON.Tools.GetCurrentGradient(ratio, this._rampGradients, function (currentGradient, nextGradient, scale) {
  61404. BABYLON.Color3.LerpToRef(currentGradient.color, nextGradient.color, scale, tmpColor);
  61405. data[x * 4] = tmpColor.r * 255;
  61406. data[x * 4 + 1] = tmpColor.g * 255;
  61407. data[x * 4 + 2] = tmpColor.b * 255;
  61408. data[x * 4 + 3] = 255;
  61409. });
  61410. }
  61411. this._rampGradientsTexture = BABYLON.RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  61412. };
  61413. /**
  61414. * Gets the current list of ramp gradients.
  61415. * You must use addRampGradient and removeRampGradient to udpate this list
  61416. * @returns the list of ramp gradients
  61417. */
  61418. ParticleSystem.prototype.getRampGradients = function () {
  61419. return this._rampGradients;
  61420. };
  61421. /**
  61422. * Adds a new ramp gradient used to remap particle colors
  61423. * @param gradient defines the gradient to use (between 0 and 1)
  61424. * @param color defines the color to affect to the specified gradient
  61425. * @returns the current particle system
  61426. */
  61427. ParticleSystem.prototype.addRampGradient = function (gradient, color) {
  61428. if (!this._rampGradients) {
  61429. this._rampGradients = [];
  61430. }
  61431. var rampGradient = new BABYLON.Color3Gradient();
  61432. rampGradient.gradient = gradient;
  61433. rampGradient.color = color;
  61434. this._rampGradients.push(rampGradient);
  61435. this._rampGradients.sort(function (a, b) {
  61436. if (a.gradient < b.gradient) {
  61437. return -1;
  61438. }
  61439. else if (a.gradient > b.gradient) {
  61440. return 1;
  61441. }
  61442. return 0;
  61443. });
  61444. if (this._rampGradientsTexture) {
  61445. this._rampGradientsTexture.dispose();
  61446. this._rampGradientsTexture = null;
  61447. }
  61448. this._createRampGradientTexture();
  61449. return this;
  61450. };
  61451. /**
  61452. * Remove a specific ramp gradient
  61453. * @param gradient defines the gradient to remove
  61454. * @returns the current particle system
  61455. */
  61456. ParticleSystem.prototype.removeRampGradient = function (gradient) {
  61457. this._removeGradientAndTexture(gradient, this._rampGradients, this._rampGradientsTexture);
  61458. this._rampGradientsTexture = null;
  61459. if (this._rampGradients && this._rampGradients.length > 0) {
  61460. this._createRampGradientTexture();
  61461. }
  61462. return this;
  61463. };
  61464. /**
  61465. * Adds a new color gradient
  61466. * @param gradient defines the gradient to use (between 0 and 1)
  61467. * @param color1 defines the color to affect to the specified gradient
  61468. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  61469. * @returns this particle system
  61470. */
  61471. ParticleSystem.prototype.addColorGradient = function (gradient, color1, color2) {
  61472. if (!this._colorGradients) {
  61473. this._colorGradients = [];
  61474. }
  61475. var colorGradient = new BABYLON.ColorGradient();
  61476. colorGradient.gradient = gradient;
  61477. colorGradient.color1 = color1;
  61478. colorGradient.color2 = color2;
  61479. this._colorGradients.push(colorGradient);
  61480. this._colorGradients.sort(function (a, b) {
  61481. if (a.gradient < b.gradient) {
  61482. return -1;
  61483. }
  61484. else if (a.gradient > b.gradient) {
  61485. return 1;
  61486. }
  61487. return 0;
  61488. });
  61489. return this;
  61490. };
  61491. /**
  61492. * Remove a specific color gradient
  61493. * @param gradient defines the gradient to remove
  61494. * @returns this particle system
  61495. */
  61496. ParticleSystem.prototype.removeColorGradient = function (gradient) {
  61497. if (!this._colorGradients) {
  61498. return this;
  61499. }
  61500. var index = 0;
  61501. for (var _i = 0, _a = this._colorGradients; _i < _a.length; _i++) {
  61502. var colorGradient = _a[_i];
  61503. if (colorGradient.gradient === gradient) {
  61504. this._colorGradients.splice(index, 1);
  61505. break;
  61506. }
  61507. index++;
  61508. }
  61509. return this;
  61510. };
  61511. ParticleSystem.prototype._fetchR = function (u, v, width, height, pixels) {
  61512. u = Math.abs(u) * 0.5 + 0.5;
  61513. v = Math.abs(v) * 0.5 + 0.5;
  61514. var wrappedU = ((u * width) % width) | 0;
  61515. var wrappedV = ((v * height) % height) | 0;
  61516. var position = (wrappedU + wrappedV * width) * 4;
  61517. return pixels[position] / 255;
  61518. };
  61519. ParticleSystem.prototype._reset = function () {
  61520. this._resetEffect();
  61521. };
  61522. ParticleSystem.prototype._resetEffect = function () {
  61523. if (this._vertexBuffer) {
  61524. this._vertexBuffer.dispose();
  61525. this._vertexBuffer = null;
  61526. }
  61527. if (this._spriteBuffer) {
  61528. this._spriteBuffer.dispose();
  61529. this._spriteBuffer = null;
  61530. }
  61531. this._createVertexBuffers();
  61532. };
  61533. ParticleSystem.prototype._createVertexBuffers = function () {
  61534. this._vertexBufferSize = this._useInstancing ? 10 : 12;
  61535. if (this._isAnimationSheetEnabled) {
  61536. this._vertexBufferSize += 1;
  61537. }
  61538. if (!this._isBillboardBased || this.billboardMode === ParticleSystem.BILLBOARDMODE_STRETCHED) {
  61539. this._vertexBufferSize += 3;
  61540. }
  61541. if (this._useRampGradients) {
  61542. this._vertexBufferSize += 4;
  61543. }
  61544. var engine = this._scene.getEngine();
  61545. this._vertexData = new Float32Array(this._capacity * this._vertexBufferSize * (this._useInstancing ? 1 : 4));
  61546. this._vertexBuffer = new BABYLON.Buffer(engine, this._vertexData, true, this._vertexBufferSize);
  61547. var dataOffset = 0;
  61548. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  61549. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  61550. dataOffset += 3;
  61551. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, dataOffset, 4, this._vertexBufferSize, this._useInstancing);
  61552. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  61553. dataOffset += 4;
  61554. var options = this._vertexBuffer.createVertexBuffer("angle", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  61555. this._vertexBuffers["angle"] = options;
  61556. dataOffset += 1;
  61557. var size = this._vertexBuffer.createVertexBuffer("size", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  61558. this._vertexBuffers["size"] = size;
  61559. dataOffset += 2;
  61560. if (this._isAnimationSheetEnabled) {
  61561. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  61562. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  61563. dataOffset += 1;
  61564. }
  61565. if (!this._isBillboardBased || this.billboardMode === ParticleSystem.BILLBOARDMODE_STRETCHED) {
  61566. var directionBuffer = this._vertexBuffer.createVertexBuffer("direction", dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  61567. this._vertexBuffers["direction"] = directionBuffer;
  61568. dataOffset += 3;
  61569. }
  61570. if (this._useRampGradients) {
  61571. var rampDataBuffer = this._vertexBuffer.createVertexBuffer("remapData", dataOffset, 4, this._vertexBufferSize, this._useInstancing);
  61572. this._vertexBuffers["remapData"] = rampDataBuffer;
  61573. dataOffset += 4;
  61574. }
  61575. var offsets;
  61576. if (this._useInstancing) {
  61577. var spriteData = new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]);
  61578. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 2);
  61579. offsets = this._spriteBuffer.createVertexBuffer("offset", 0, 2);
  61580. }
  61581. else {
  61582. offsets = this._vertexBuffer.createVertexBuffer("offset", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  61583. dataOffset += 2;
  61584. }
  61585. this._vertexBuffers["offset"] = offsets;
  61586. };
  61587. ParticleSystem.prototype._createIndexBuffer = function () {
  61588. if (this._useInstancing) {
  61589. return;
  61590. }
  61591. var indices = [];
  61592. var index = 0;
  61593. for (var count = 0; count < this._capacity; count++) {
  61594. indices.push(index);
  61595. indices.push(index + 1);
  61596. indices.push(index + 2);
  61597. indices.push(index);
  61598. indices.push(index + 2);
  61599. indices.push(index + 3);
  61600. index += 4;
  61601. }
  61602. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  61603. };
  61604. /**
  61605. * Gets the maximum number of particles active at the same time.
  61606. * @returns The max number of active particles.
  61607. */
  61608. ParticleSystem.prototype.getCapacity = function () {
  61609. return this._capacity;
  61610. };
  61611. /**
  61612. * Gets whether there are still active particles in the system.
  61613. * @returns True if it is alive, otherwise false.
  61614. */
  61615. ParticleSystem.prototype.isAlive = function () {
  61616. return this._alive;
  61617. };
  61618. /**
  61619. * Gets if the system has been started. (Note: this will still be true after stop is called)
  61620. * @returns True if it has been started, otherwise false.
  61621. */
  61622. ParticleSystem.prototype.isStarted = function () {
  61623. return this._started;
  61624. };
  61625. ParticleSystem.prototype._prepareSubEmitterInternalArray = function () {
  61626. var _this = this;
  61627. this._subEmitters = new Array();
  61628. if (this.subEmitters) {
  61629. this.subEmitters.forEach(function (subEmitter) {
  61630. if (subEmitter instanceof ParticleSystem) {
  61631. _this._subEmitters.push([new BABYLON.SubEmitter(subEmitter)]);
  61632. }
  61633. else if (subEmitter instanceof BABYLON.SubEmitter) {
  61634. _this._subEmitters.push([subEmitter]);
  61635. }
  61636. else if (subEmitter instanceof Array) {
  61637. _this._subEmitters.push(subEmitter);
  61638. }
  61639. });
  61640. }
  61641. };
  61642. /**
  61643. * Starts the particle system and begins to emit
  61644. * @param delay defines the delay in milliseconds before starting the system (this.startDelay by default)
  61645. */
  61646. ParticleSystem.prototype.start = function (delay) {
  61647. var _this = this;
  61648. if (delay === void 0) { delay = this.startDelay; }
  61649. if (!this.targetStopDuration && this._hasTargetStopDurationDependantGradient()) {
  61650. throw "Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set";
  61651. }
  61652. if (delay) {
  61653. setTimeout(function () {
  61654. _this.start(0);
  61655. }, delay);
  61656. return;
  61657. }
  61658. // Convert the subEmitters field to the constant type field _subEmitters
  61659. this._prepareSubEmitterInternalArray();
  61660. this._started = true;
  61661. this._stopped = false;
  61662. this._actualFrame = 0;
  61663. if (this._subEmitters && this._subEmitters.length != 0) {
  61664. this.activeSubSystems = new Array();
  61665. }
  61666. // Reset emit gradient so it acts the same on every start
  61667. if (this._emitRateGradients) {
  61668. if (this._emitRateGradients.length > 0) {
  61669. this._currentEmitRateGradient = this._emitRateGradients[0];
  61670. this._currentEmitRate1 = this._currentEmitRateGradient.getFactor();
  61671. this._currentEmitRate2 = this._currentEmitRate1;
  61672. }
  61673. if (this._emitRateGradients.length > 1) {
  61674. this._currentEmitRate2 = this._emitRateGradients[1].getFactor();
  61675. }
  61676. }
  61677. // Reset start size gradient so it acts the same on every start
  61678. if (this._startSizeGradients) {
  61679. if (this._startSizeGradients.length > 0) {
  61680. this._currentStartSizeGradient = this._startSizeGradients[0];
  61681. this._currentStartSize1 = this._currentStartSizeGradient.getFactor();
  61682. this._currentStartSize2 = this._currentStartSize1;
  61683. }
  61684. if (this._startSizeGradients.length > 1) {
  61685. this._currentStartSize2 = this._startSizeGradients[1].getFactor();
  61686. }
  61687. }
  61688. if (this.preWarmCycles) {
  61689. if (this.emitter instanceof BABYLON.AbstractMesh) {
  61690. this.emitter.computeWorldMatrix(true);
  61691. }
  61692. var noiseTextureAsProcedural_1 = this.noiseTexture;
  61693. if (noiseTextureAsProcedural_1 && noiseTextureAsProcedural_1.onGeneratedObservable) {
  61694. noiseTextureAsProcedural_1.onGeneratedObservable.addOnce(function () {
  61695. setTimeout(function () {
  61696. for (var index = 0; index < _this.preWarmCycles; index++) {
  61697. _this.animate(true);
  61698. noiseTextureAsProcedural_1.render();
  61699. }
  61700. });
  61701. });
  61702. }
  61703. else {
  61704. for (var index = 0; index < this.preWarmCycles; index++) {
  61705. this.animate(true);
  61706. }
  61707. }
  61708. }
  61709. // Animations
  61710. if (this.beginAnimationOnStart && this.animations && this.animations.length > 0) {
  61711. this.getScene().beginAnimation(this, this.beginAnimationFrom, this.beginAnimationTo, this.beginAnimationLoop);
  61712. }
  61713. };
  61714. /**
  61715. * Stops the particle system.
  61716. * @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.
  61717. */
  61718. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  61719. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  61720. this._stopped = true;
  61721. if (stopSubEmitters) {
  61722. this._stopSubEmitters();
  61723. }
  61724. };
  61725. // animation sheet
  61726. /**
  61727. * Remove all active particles
  61728. */
  61729. ParticleSystem.prototype.reset = function () {
  61730. this._stockParticles = [];
  61731. this._particles = [];
  61732. };
  61733. /**
  61734. * @hidden (for internal use only)
  61735. */
  61736. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  61737. var offset = index * this._vertexBufferSize;
  61738. this._vertexData[offset++] = particle.position.x;
  61739. this._vertexData[offset++] = particle.position.y;
  61740. this._vertexData[offset++] = particle.position.z;
  61741. this._vertexData[offset++] = particle.color.r;
  61742. this._vertexData[offset++] = particle.color.g;
  61743. this._vertexData[offset++] = particle.color.b;
  61744. this._vertexData[offset++] = particle.color.a;
  61745. this._vertexData[offset++] = particle.angle;
  61746. this._vertexData[offset++] = particle.scale.x * particle.size;
  61747. this._vertexData[offset++] = particle.scale.y * particle.size;
  61748. if (this._isAnimationSheetEnabled) {
  61749. this._vertexData[offset++] = particle.cellIndex;
  61750. }
  61751. if (!this._isBillboardBased) {
  61752. if (particle._initialDirection) {
  61753. this._vertexData[offset++] = particle._initialDirection.x;
  61754. this._vertexData[offset++] = particle._initialDirection.y;
  61755. this._vertexData[offset++] = particle._initialDirection.z;
  61756. }
  61757. else {
  61758. this._vertexData[offset++] = particle.direction.x;
  61759. this._vertexData[offset++] = particle.direction.y;
  61760. this._vertexData[offset++] = particle.direction.z;
  61761. }
  61762. }
  61763. else if (this.billboardMode === ParticleSystem.BILLBOARDMODE_STRETCHED) {
  61764. this._vertexData[offset++] = particle.direction.x;
  61765. this._vertexData[offset++] = particle.direction.y;
  61766. this._vertexData[offset++] = particle.direction.z;
  61767. }
  61768. if (this._useRampGradients) {
  61769. this._vertexData[offset++] = particle.remapData.x;
  61770. this._vertexData[offset++] = particle.remapData.y;
  61771. this._vertexData[offset++] = particle.remapData.z;
  61772. this._vertexData[offset++] = particle.remapData.w;
  61773. }
  61774. if (!this._useInstancing) {
  61775. if (this._isAnimationSheetEnabled) {
  61776. if (offsetX === 0) {
  61777. offsetX = this._epsilon;
  61778. }
  61779. else if (offsetX === 1) {
  61780. offsetX = 1 - this._epsilon;
  61781. }
  61782. if (offsetY === 0) {
  61783. offsetY = this._epsilon;
  61784. }
  61785. else if (offsetY === 1) {
  61786. offsetY = 1 - this._epsilon;
  61787. }
  61788. }
  61789. this._vertexData[offset++] = offsetX;
  61790. this._vertexData[offset++] = offsetY;
  61791. }
  61792. };
  61793. ParticleSystem.prototype._stopSubEmitters = function () {
  61794. if (!this.activeSubSystems) {
  61795. return;
  61796. }
  61797. this.activeSubSystems.forEach(function (subSystem) {
  61798. subSystem.stop(true);
  61799. });
  61800. this.activeSubSystems = new Array();
  61801. };
  61802. ParticleSystem.prototype._removeFromRoot = function () {
  61803. if (!this._rootParticleSystem) {
  61804. return;
  61805. }
  61806. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  61807. if (index !== -1) {
  61808. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  61809. }
  61810. this._rootParticleSystem = null;
  61811. };
  61812. // End of sub system methods
  61813. ParticleSystem.prototype._update = function (newParticles) {
  61814. var _this = this;
  61815. // Update current
  61816. this._alive = this._particles.length > 0;
  61817. if (this.emitter.position) {
  61818. var emitterMesh = this.emitter;
  61819. this._emitterWorldMatrix = emitterMesh.getWorldMatrix();
  61820. }
  61821. else {
  61822. var emitterPosition = this.emitter;
  61823. this._emitterWorldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  61824. }
  61825. this.updateFunction(this._particles);
  61826. // Add new ones
  61827. var particle;
  61828. var _loop_2 = function () {
  61829. if (this_1._particles.length === this_1._capacity) {
  61830. return "break";
  61831. }
  61832. particle = this_1._createParticle();
  61833. this_1._particles.push(particle);
  61834. // Emitter
  61835. var emitPower = BABYLON.Scalar.RandomRange(this_1.minEmitPower, this_1.maxEmitPower);
  61836. if (this_1.startPositionFunction) {
  61837. this_1.startPositionFunction(this_1._emitterWorldMatrix, particle.position, particle);
  61838. }
  61839. else {
  61840. this_1.particleEmitterType.startPositionFunction(this_1._emitterWorldMatrix, particle.position, particle);
  61841. }
  61842. if (this_1.startDirectionFunction) {
  61843. this_1.startDirectionFunction(this_1._emitterWorldMatrix, particle.direction, particle);
  61844. }
  61845. else {
  61846. this_1.particleEmitterType.startDirectionFunction(this_1._emitterWorldMatrix, particle.direction, particle);
  61847. }
  61848. if (emitPower === 0) {
  61849. if (!particle._initialDirection) {
  61850. particle._initialDirection = particle.direction.clone();
  61851. }
  61852. else {
  61853. particle._initialDirection.copyFrom(particle.direction);
  61854. }
  61855. }
  61856. else {
  61857. particle._initialDirection = null;
  61858. }
  61859. particle.direction.scaleInPlace(emitPower);
  61860. // Life time
  61861. if (this_1.targetStopDuration && this_1._lifeTimeGradients && this_1._lifeTimeGradients.length > 0) {
  61862. var ratio_1 = BABYLON.Scalar.Clamp(this_1._actualFrame / this_1.targetStopDuration);
  61863. BABYLON.Tools.GetCurrentGradient(ratio_1, this_1._lifeTimeGradients, function (currentGradient, nextGradient, scale) {
  61864. var factorGradient1 = currentGradient;
  61865. var factorGradient2 = nextGradient;
  61866. var lifeTime1 = factorGradient1.getFactor();
  61867. var lifeTime2 = factorGradient2.getFactor();
  61868. var gradient = (ratio_1 - factorGradient1.gradient) / (factorGradient2.gradient - factorGradient1.gradient);
  61869. particle.lifeTime = BABYLON.Scalar.Lerp(lifeTime1, lifeTime2, gradient);
  61870. });
  61871. }
  61872. else {
  61873. particle.lifeTime = BABYLON.Scalar.RandomRange(this_1.minLifeTime, this_1.maxLifeTime);
  61874. }
  61875. // Size
  61876. if (!this_1._sizeGradients || this_1._sizeGradients.length === 0) {
  61877. particle.size = BABYLON.Scalar.RandomRange(this_1.minSize, this_1.maxSize);
  61878. }
  61879. else {
  61880. particle._currentSizeGradient = this_1._sizeGradients[0];
  61881. particle._currentSize1 = particle._currentSizeGradient.getFactor();
  61882. particle.size = particle._currentSize1;
  61883. if (this_1._sizeGradients.length > 1) {
  61884. particle._currentSize2 = this_1._sizeGradients[1].getFactor();
  61885. }
  61886. else {
  61887. particle._currentSize2 = particle._currentSize1;
  61888. }
  61889. }
  61890. // Size and scale
  61891. particle.scale.copyFromFloats(BABYLON.Scalar.RandomRange(this_1.minScaleX, this_1.maxScaleX), BABYLON.Scalar.RandomRange(this_1.minScaleY, this_1.maxScaleY));
  61892. // Adjust scale by start size
  61893. if (this_1._startSizeGradients && this_1._startSizeGradients[0] && this_1.targetStopDuration) {
  61894. var ratio = this_1._actualFrame / this_1.targetStopDuration;
  61895. BABYLON.Tools.GetCurrentGradient(ratio, this_1._startSizeGradients, function (currentGradient, nextGradient, scale) {
  61896. if (currentGradient !== _this._currentStartSizeGradient) {
  61897. _this._currentStartSize1 = _this._currentStartSize2;
  61898. _this._currentStartSize2 = nextGradient.getFactor();
  61899. _this._currentStartSizeGradient = currentGradient;
  61900. }
  61901. var value = BABYLON.Scalar.Lerp(_this._currentStartSize1, _this._currentStartSize2, scale);
  61902. particle.scale.scaleInPlace(value);
  61903. });
  61904. }
  61905. // Angle
  61906. if (!this_1._angularSpeedGradients || this_1._angularSpeedGradients.length === 0) {
  61907. particle.angularSpeed = BABYLON.Scalar.RandomRange(this_1.minAngularSpeed, this_1.maxAngularSpeed);
  61908. }
  61909. else {
  61910. particle._currentAngularSpeedGradient = this_1._angularSpeedGradients[0];
  61911. particle.angularSpeed = particle._currentAngularSpeedGradient.getFactor();
  61912. particle._currentAngularSpeed1 = particle.angularSpeed;
  61913. if (this_1._angularSpeedGradients.length > 1) {
  61914. particle._currentAngularSpeed2 = this_1._angularSpeedGradients[1].getFactor();
  61915. }
  61916. else {
  61917. particle._currentAngularSpeed2 = particle._currentAngularSpeed1;
  61918. }
  61919. }
  61920. particle.angle = BABYLON.Scalar.RandomRange(this_1.minInitialRotation, this_1.maxInitialRotation);
  61921. // Velocity
  61922. if (this_1._velocityGradients && this_1._velocityGradients.length > 0) {
  61923. particle._currentVelocityGradient = this_1._velocityGradients[0];
  61924. particle._currentVelocity1 = particle._currentVelocityGradient.getFactor();
  61925. if (this_1._velocityGradients.length > 1) {
  61926. particle._currentVelocity2 = this_1._velocityGradients[1].getFactor();
  61927. }
  61928. else {
  61929. particle._currentVelocity2 = particle._currentVelocity1;
  61930. }
  61931. }
  61932. // Limit velocity
  61933. if (this_1._limitVelocityGradients && this_1._limitVelocityGradients.length > 0) {
  61934. particle._currentLimitVelocityGradient = this_1._limitVelocityGradients[0];
  61935. particle._currentLimitVelocity1 = particle._currentLimitVelocityGradient.getFactor();
  61936. if (this_1._limitVelocityGradients.length > 1) {
  61937. particle._currentLimitVelocity2 = this_1._limitVelocityGradients[1].getFactor();
  61938. }
  61939. else {
  61940. particle._currentLimitVelocity2 = particle._currentLimitVelocity1;
  61941. }
  61942. }
  61943. // Drag
  61944. if (this_1._dragGradients && this_1._dragGradients.length > 0) {
  61945. particle._currentDragGradient = this_1._dragGradients[0];
  61946. particle._currentDrag1 = particle._currentDragGradient.getFactor();
  61947. if (this_1._dragGradients.length > 1) {
  61948. particle._currentDrag2 = this_1._dragGradients[1].getFactor();
  61949. }
  61950. else {
  61951. particle._currentDrag2 = particle._currentDrag1;
  61952. }
  61953. }
  61954. // Color
  61955. if (!this_1._colorGradients || this_1._colorGradients.length === 0) {
  61956. step = BABYLON.Scalar.RandomRange(0, 1.0);
  61957. BABYLON.Color4.LerpToRef(this_1.color1, this_1.color2, step, particle.color);
  61958. this_1.colorDead.subtractToRef(particle.color, this_1._colorDiff);
  61959. this_1._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  61960. }
  61961. else {
  61962. particle._currentColorGradient = this_1._colorGradients[0];
  61963. particle._currentColorGradient.getColorToRef(particle.color);
  61964. particle._currentColor1.copyFrom(particle.color);
  61965. if (this_1._colorGradients.length > 1) {
  61966. this_1._colorGradients[1].getColorToRef(particle._currentColor2);
  61967. }
  61968. else {
  61969. particle._currentColor2.copyFrom(particle.color);
  61970. }
  61971. }
  61972. // Sheet
  61973. if (this_1._isAnimationSheetEnabled) {
  61974. particle._initialStartSpriteCellID = this_1.startSpriteCellID;
  61975. particle._initialEndSpriteCellID = this_1.endSpriteCellID;
  61976. }
  61977. // Inherited Velocity
  61978. particle.direction.addInPlace(this_1._inheritedVelocityOffset);
  61979. // Ramp
  61980. if (this_1._useRampGradients) {
  61981. particle.remapData = new BABYLON.Vector4(0, 1, 0, 1);
  61982. }
  61983. // Noise texture coordinates
  61984. if (this_1.noiseTexture) {
  61985. if (particle._randomNoiseCoordinates1) {
  61986. particle._randomNoiseCoordinates1.copyFromFloats(Math.random(), Math.random(), Math.random());
  61987. particle._randomNoiseCoordinates2.copyFromFloats(Math.random(), Math.random(), Math.random());
  61988. }
  61989. else {
  61990. particle._randomNoiseCoordinates1 = new BABYLON.Vector3(Math.random(), Math.random(), Math.random());
  61991. particle._randomNoiseCoordinates2 = new BABYLON.Vector3(Math.random(), Math.random(), Math.random());
  61992. }
  61993. }
  61994. // Update the position of the attached sub-emitters to match their attached particle
  61995. particle._inheritParticleInfoToSubEmitters();
  61996. };
  61997. var this_1 = this, step;
  61998. for (var index = 0; index < newParticles; index++) {
  61999. var state_1 = _loop_2();
  62000. if (state_1 === "break")
  62001. break;
  62002. }
  62003. };
  62004. /** @hidden */
  62005. ParticleSystem._GetAttributeNamesOrOptions = function (isAnimationSheetEnabled, isBillboardBased, useRampGradients) {
  62006. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  62007. if (isBillboardBased === void 0) { isBillboardBased = false; }
  62008. if (useRampGradients === void 0) { useRampGradients = false; }
  62009. var attributeNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "angle", "offset", "size"];
  62010. if (isAnimationSheetEnabled) {
  62011. attributeNamesOrOptions.push("cellIndex");
  62012. }
  62013. if (!isBillboardBased) {
  62014. attributeNamesOrOptions.push("direction");
  62015. }
  62016. if (useRampGradients) {
  62017. attributeNamesOrOptions.push("remapData");
  62018. }
  62019. return attributeNamesOrOptions;
  62020. };
  62021. /** @hidden */
  62022. ParticleSystem._GetEffectCreationOptions = function (isAnimationSheetEnabled) {
  62023. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  62024. var effectCreationOption = ["invView", "view", "projection", "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "textureMask", "translationPivot", "eyePosition"];
  62025. if (isAnimationSheetEnabled) {
  62026. effectCreationOption.push("particlesInfos");
  62027. }
  62028. return effectCreationOption;
  62029. };
  62030. /** @hidden */
  62031. ParticleSystem.prototype._getEffect = function (blendMode) {
  62032. if (this._customEffect) {
  62033. return this._customEffect;
  62034. }
  62035. var defines = [];
  62036. if (this._scene.clipPlane) {
  62037. defines.push("#define CLIPPLANE");
  62038. }
  62039. if (this._scene.clipPlane2) {
  62040. defines.push("#define CLIPPLANE2");
  62041. }
  62042. if (this._scene.clipPlane3) {
  62043. defines.push("#define CLIPPLANE3");
  62044. }
  62045. if (this._scene.clipPlane4) {
  62046. defines.push("#define CLIPPLANE4");
  62047. }
  62048. if (this._isAnimationSheetEnabled) {
  62049. defines.push("#define ANIMATESHEET");
  62050. }
  62051. if (blendMode === ParticleSystem.BLENDMODE_MULTIPLY) {
  62052. defines.push("#define BLENDMULTIPLYMODE");
  62053. }
  62054. if (this._useRampGradients) {
  62055. defines.push("#define RAMPGRADIENT");
  62056. }
  62057. if (this._isBillboardBased) {
  62058. defines.push("#define BILLBOARD");
  62059. switch (this.billboardMode) {
  62060. case ParticleSystem.BILLBOARDMODE_Y:
  62061. defines.push("#define BILLBOARDY");
  62062. break;
  62063. case ParticleSystem.BILLBOARDMODE_STRETCHED:
  62064. defines.push("#define BILLBOARDSTRETCHED");
  62065. break;
  62066. case ParticleSystem.BILLBOARDMODE_ALL:
  62067. default:
  62068. break;
  62069. }
  62070. }
  62071. if (this._imageProcessingConfiguration) {
  62072. this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines);
  62073. defines.push(this._imageProcessingConfigurationDefines.toString());
  62074. }
  62075. // Effect
  62076. var join = defines.join("\n");
  62077. if (this._cachedDefines !== join) {
  62078. this._cachedDefines = join;
  62079. var attributesNamesOrOptions = ParticleSystem._GetAttributeNamesOrOptions(this._isAnimationSheetEnabled, this._isBillboardBased && this.billboardMode !== ParticleSystem.BILLBOARDMODE_STRETCHED, this._useRampGradients);
  62080. var effectCreationOption = ParticleSystem._GetEffectCreationOptions(this._isAnimationSheetEnabled);
  62081. var samplers = ["diffuseSampler", "rampSampler"];
  62082. if (BABYLON.ImageProcessingConfiguration) {
  62083. BABYLON.ImageProcessingConfiguration.PrepareUniforms(effectCreationOption, this._imageProcessingConfigurationDefines);
  62084. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._imageProcessingConfigurationDefines);
  62085. }
  62086. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, samplers, join);
  62087. }
  62088. return this._effect;
  62089. };
  62090. /**
  62091. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  62092. * @param preWarmOnly will prevent the system from updating the vertex buffer (default is false)
  62093. */
  62094. ParticleSystem.prototype.animate = function (preWarmOnly) {
  62095. var _this = this;
  62096. if (preWarmOnly === void 0) { preWarmOnly = false; }
  62097. if (!this._started) {
  62098. return;
  62099. }
  62100. if (!preWarmOnly) {
  62101. // Check
  62102. if (!this.isReady()) {
  62103. return;
  62104. }
  62105. if (this._currentRenderId === this._scene.getFrameId()) {
  62106. return;
  62107. }
  62108. this._currentRenderId = this._scene.getFrameId();
  62109. }
  62110. this._scaledUpdateSpeed = this.updateSpeed * (preWarmOnly ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  62111. // Determine the number of particles we need to create
  62112. var newParticles;
  62113. if (this.manualEmitCount > -1) {
  62114. newParticles = this.manualEmitCount;
  62115. this._newPartsExcess = 0;
  62116. this.manualEmitCount = 0;
  62117. }
  62118. else {
  62119. var rate_1 = this.emitRate;
  62120. if (this._emitRateGradients && this._emitRateGradients.length > 0 && this.targetStopDuration) {
  62121. var ratio = this._actualFrame / this.targetStopDuration;
  62122. BABYLON.Tools.GetCurrentGradient(ratio, this._emitRateGradients, function (currentGradient, nextGradient, scale) {
  62123. if (currentGradient !== _this._currentEmitRateGradient) {
  62124. _this._currentEmitRate1 = _this._currentEmitRate2;
  62125. _this._currentEmitRate2 = nextGradient.getFactor();
  62126. _this._currentEmitRateGradient = currentGradient;
  62127. }
  62128. rate_1 = BABYLON.Scalar.Lerp(_this._currentEmitRate1, _this._currentEmitRate2, scale);
  62129. });
  62130. }
  62131. newParticles = ((rate_1 * this._scaledUpdateSpeed) >> 0);
  62132. this._newPartsExcess += rate_1 * this._scaledUpdateSpeed - newParticles;
  62133. }
  62134. if (this._newPartsExcess > 1.0) {
  62135. newParticles += this._newPartsExcess >> 0;
  62136. this._newPartsExcess -= this._newPartsExcess >> 0;
  62137. }
  62138. this._alive = false;
  62139. if (!this._stopped) {
  62140. this._actualFrame += this._scaledUpdateSpeed;
  62141. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  62142. this.stop();
  62143. }
  62144. }
  62145. else {
  62146. newParticles = 0;
  62147. }
  62148. this._update(newParticles);
  62149. // Stopped?
  62150. if (this._stopped) {
  62151. if (!this._alive) {
  62152. this._started = false;
  62153. if (this.onAnimationEnd) {
  62154. this.onAnimationEnd();
  62155. }
  62156. if (this.disposeOnStop) {
  62157. this._scene._toBeDisposed.push(this);
  62158. }
  62159. }
  62160. }
  62161. if (!preWarmOnly) {
  62162. // Update VBO
  62163. var offset = 0;
  62164. for (var index = 0; index < this._particles.length; index++) {
  62165. var particle = this._particles[index];
  62166. this._appendParticleVertices(offset, particle);
  62167. offset += this._useInstancing ? 1 : 4;
  62168. }
  62169. if (this._vertexBuffer) {
  62170. this._vertexBuffer.update(this._vertexData);
  62171. }
  62172. }
  62173. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  62174. this.stop();
  62175. }
  62176. };
  62177. ParticleSystem.prototype._appendParticleVertices = function (offset, particle) {
  62178. this._appendParticleVertex(offset++, particle, 0, 0);
  62179. if (!this._useInstancing) {
  62180. this._appendParticleVertex(offset++, particle, 1, 0);
  62181. this._appendParticleVertex(offset++, particle, 1, 1);
  62182. this._appendParticleVertex(offset++, particle, 0, 1);
  62183. }
  62184. };
  62185. /**
  62186. * Rebuilds the particle system.
  62187. */
  62188. ParticleSystem.prototype.rebuild = function () {
  62189. this._createIndexBuffer();
  62190. if (this._vertexBuffer) {
  62191. this._vertexBuffer._rebuild();
  62192. }
  62193. };
  62194. /**
  62195. * Is this system ready to be used/rendered
  62196. * @return true if the system is ready
  62197. */
  62198. ParticleSystem.prototype.isReady = function () {
  62199. if (!this.emitter || !this._imageProcessingConfiguration.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  62200. return false;
  62201. }
  62202. if (this.blendMode !== ParticleSystem.BLENDMODE_MULTIPLYADD) {
  62203. if (!this._getEffect(this.blendMode).isReady()) {
  62204. return false;
  62205. }
  62206. }
  62207. else {
  62208. if (!this._getEffect(ParticleSystem.BLENDMODE_MULTIPLY).isReady()) {
  62209. return false;
  62210. }
  62211. if (!this._getEffect(ParticleSystem.BLENDMODE_ADD).isReady()) {
  62212. return false;
  62213. }
  62214. }
  62215. return true;
  62216. };
  62217. ParticleSystem.prototype._render = function (blendMode) {
  62218. var effect = this._getEffect(blendMode);
  62219. var engine = this._scene.getEngine();
  62220. // Render
  62221. engine.enableEffect(effect);
  62222. var viewMatrix = this._scene.getViewMatrix();
  62223. effect.setTexture("diffuseSampler", this.particleTexture);
  62224. effect.setMatrix("view", viewMatrix);
  62225. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  62226. if (this._isAnimationSheetEnabled && this.particleTexture) {
  62227. var baseSize = this.particleTexture.getBaseSize();
  62228. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  62229. }
  62230. effect.setVector2("translationPivot", this.translationPivot);
  62231. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  62232. if (this._isBillboardBased) {
  62233. var camera = this._scene.activeCamera;
  62234. effect.setVector3("eyePosition", camera.globalPosition);
  62235. }
  62236. if (this._rampGradientsTexture) {
  62237. effect.setTexture("rampSampler", this._rampGradientsTexture);
  62238. }
  62239. if (this._scene.clipPlane || this._scene.clipPlane2 || this._scene.clipPlane3 || this._scene.clipPlane4) {
  62240. var invView = viewMatrix.clone();
  62241. invView.invert();
  62242. effect.setMatrix("invView", invView);
  62243. BABYLON.MaterialHelper.BindClipPlane(effect, this._scene);
  62244. }
  62245. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  62246. // image processing
  62247. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  62248. this._imageProcessingConfiguration.bind(effect);
  62249. }
  62250. // Draw order
  62251. switch (blendMode) {
  62252. case ParticleSystem.BLENDMODE_ADD:
  62253. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  62254. break;
  62255. case ParticleSystem.BLENDMODE_ONEONE:
  62256. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  62257. break;
  62258. case ParticleSystem.BLENDMODE_STANDARD:
  62259. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  62260. break;
  62261. case ParticleSystem.BLENDMODE_MULTIPLY:
  62262. engine.setAlphaMode(BABYLON.Engine.ALPHA_MULTIPLY);
  62263. break;
  62264. }
  62265. if (this._useInstancing) {
  62266. engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._particles.length);
  62267. }
  62268. else {
  62269. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  62270. }
  62271. return this._particles.length;
  62272. };
  62273. /**
  62274. * Renders the particle system in its current state.
  62275. * @returns the current number of particles
  62276. */
  62277. ParticleSystem.prototype.render = function () {
  62278. // Check
  62279. if (!this.isReady() || !this._particles.length) {
  62280. return 0;
  62281. }
  62282. var engine = this._scene.getEngine();
  62283. engine.setState(false);
  62284. if (this.forceDepthWrite) {
  62285. engine.setDepthWrite(true);
  62286. }
  62287. var outparticles = 0;
  62288. if (this.blendMode === ParticleSystem.BLENDMODE_MULTIPLYADD) {
  62289. outparticles = this._render(ParticleSystem.BLENDMODE_MULTIPLY) + this._render(ParticleSystem.BLENDMODE_ADD);
  62290. }
  62291. outparticles = this._render(this.blendMode);
  62292. engine.unbindInstanceAttributes();
  62293. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  62294. return outparticles;
  62295. };
  62296. /**
  62297. * Disposes the particle system and free the associated resources
  62298. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  62299. */
  62300. ParticleSystem.prototype.dispose = function (disposeTexture) {
  62301. if (disposeTexture === void 0) { disposeTexture = true; }
  62302. if (this._vertexBuffer) {
  62303. this._vertexBuffer.dispose();
  62304. this._vertexBuffer = null;
  62305. }
  62306. if (this._spriteBuffer) {
  62307. this._spriteBuffer.dispose();
  62308. this._spriteBuffer = null;
  62309. }
  62310. if (this._indexBuffer) {
  62311. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  62312. this._indexBuffer = null;
  62313. }
  62314. if (disposeTexture && this.particleTexture) {
  62315. this.particleTexture.dispose();
  62316. this.particleTexture = null;
  62317. }
  62318. if (disposeTexture && this.noiseTexture) {
  62319. this.noiseTexture.dispose();
  62320. this.noiseTexture = null;
  62321. }
  62322. if (this._rampGradientsTexture) {
  62323. this._rampGradientsTexture.dispose();
  62324. this._rampGradientsTexture = null;
  62325. }
  62326. this._removeFromRoot();
  62327. if (this._subEmitters && this._subEmitters.length) {
  62328. for (var index = 0; index < this._subEmitters.length; index++) {
  62329. for (var _i = 0, _a = this._subEmitters[index]; _i < _a.length; _i++) {
  62330. var subEmitter = _a[_i];
  62331. subEmitter.dispose();
  62332. }
  62333. }
  62334. this._subEmitters = [];
  62335. this.subEmitters = [];
  62336. }
  62337. if (this._disposeEmitterOnDispose && this.emitter && this.emitter.dispose) {
  62338. this.emitter.dispose(true);
  62339. }
  62340. // Remove from scene
  62341. var index = this._scene.particleSystems.indexOf(this);
  62342. if (index > -1) {
  62343. this._scene.particleSystems.splice(index, 1);
  62344. }
  62345. this._scene._activeParticleSystems.dispose();
  62346. // Callback
  62347. this.onDisposeObservable.notifyObservers(this);
  62348. this.onDisposeObservable.clear();
  62349. this.reset();
  62350. };
  62351. // Clone
  62352. /**
  62353. * Clones the particle system.
  62354. * @param name The name of the cloned object
  62355. * @param newEmitter The new emitter to use
  62356. * @returns the cloned particle system
  62357. */
  62358. ParticleSystem.prototype.clone = function (name, newEmitter) {
  62359. var custom = null;
  62360. var program = null;
  62361. if (this.customShader != null) {
  62362. program = this.customShader;
  62363. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  62364. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  62365. }
  62366. else if (this._customEffect) {
  62367. custom = this._customEffect;
  62368. }
  62369. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  62370. result.customShader = program;
  62371. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader", "noiseTexture"]);
  62372. if (newEmitter === undefined) {
  62373. newEmitter = this.emitter;
  62374. }
  62375. result.noiseTexture = this.noiseTexture;
  62376. result.emitter = newEmitter;
  62377. if (this.particleTexture) {
  62378. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  62379. }
  62380. // Clone gradients
  62381. if (this._colorGradients) {
  62382. this._colorGradients.forEach(function (v) {
  62383. result.addColorGradient(v.gradient, v.color1, v.color2);
  62384. });
  62385. }
  62386. if (this._dragGradients) {
  62387. this._dragGradients.forEach(function (v) {
  62388. result.addDragGradient(v.gradient, v.factor1, v.factor2);
  62389. });
  62390. }
  62391. if (this._angularSpeedGradients) {
  62392. this._angularSpeedGradients.forEach(function (v) {
  62393. result.addAngularSpeedGradient(v.gradient, v.factor1, v.factor2);
  62394. });
  62395. }
  62396. if (this._emitRateGradients) {
  62397. this._emitRateGradients.forEach(function (v) {
  62398. result.addEmitRateGradient(v.gradient, v.factor1, v.factor2);
  62399. });
  62400. }
  62401. if (this._lifeTimeGradients) {
  62402. this._lifeTimeGradients.forEach(function (v) {
  62403. result.addLifeTimeGradient(v.gradient, v.factor1, v.factor2);
  62404. });
  62405. }
  62406. if (this._limitVelocityGradients) {
  62407. this._limitVelocityGradients.forEach(function (v) {
  62408. result.addLimitVelocityGradient(v.gradient, v.factor1, v.factor2);
  62409. });
  62410. }
  62411. if (this._sizeGradients) {
  62412. this._sizeGradients.forEach(function (v) {
  62413. result.addSizeGradient(v.gradient, v.factor1, v.factor2);
  62414. });
  62415. }
  62416. if (this._startSizeGradients) {
  62417. this._startSizeGradients.forEach(function (v) {
  62418. result.addStartSizeGradient(v.gradient, v.factor1, v.factor2);
  62419. });
  62420. }
  62421. if (this._velocityGradients) {
  62422. this._velocityGradients.forEach(function (v) {
  62423. result.addVelocityGradient(v.gradient, v.factor1, v.factor2);
  62424. });
  62425. }
  62426. if (this._rampGradients) {
  62427. this._rampGradients.forEach(function (v) {
  62428. result.addRampGradient(v.gradient, v.color);
  62429. });
  62430. }
  62431. if (this._colorRemapGradients) {
  62432. this._colorRemapGradients.forEach(function (v) {
  62433. result.addColorRemapGradient(v.gradient, v.factor1, v.factor2);
  62434. });
  62435. }
  62436. if (this._alphaRemapGradients) {
  62437. this._alphaRemapGradients.forEach(function (v) {
  62438. result.addAlphaRemapGradient(v.gradient, v.factor1, v.factor2);
  62439. });
  62440. }
  62441. if (!this.preventAutoStart) {
  62442. result.start();
  62443. }
  62444. return result;
  62445. };
  62446. /**
  62447. * Serializes the particle system to a JSON object.
  62448. * @returns the JSON object
  62449. */
  62450. ParticleSystem.prototype.serialize = function () {
  62451. var serializationObject = {};
  62452. ParticleSystem._Serialize(serializationObject, this);
  62453. serializationObject.textureMask = this.textureMask.asArray();
  62454. serializationObject.customShader = this.customShader;
  62455. serializationObject.preventAutoStart = this.preventAutoStart;
  62456. // SubEmitters
  62457. if (this.subEmitters) {
  62458. serializationObject.subEmitters = [];
  62459. if (!this._subEmitters) {
  62460. this._prepareSubEmitterInternalArray();
  62461. }
  62462. for (var _i = 0, _a = this._subEmitters; _i < _a.length; _i++) {
  62463. var subs = _a[_i];
  62464. var cell = [];
  62465. for (var _b = 0, subs_1 = subs; _b < subs_1.length; _b++) {
  62466. var sub = subs_1[_b];
  62467. cell.push(sub.serialize());
  62468. }
  62469. serializationObject.subEmitters.push(cell);
  62470. }
  62471. }
  62472. return serializationObject;
  62473. };
  62474. /** @hidden */
  62475. ParticleSystem._Serialize = function (serializationObject, particleSystem) {
  62476. serializationObject.name = particleSystem.name;
  62477. serializationObject.id = particleSystem.id;
  62478. serializationObject.capacity = particleSystem.getCapacity();
  62479. // Emitter
  62480. if (particleSystem.emitter.position) {
  62481. var emitterMesh = particleSystem.emitter;
  62482. serializationObject.emitterId = emitterMesh.id;
  62483. }
  62484. else {
  62485. var emitterPosition = particleSystem.emitter;
  62486. serializationObject.emitter = emitterPosition.asArray();
  62487. }
  62488. // Emitter
  62489. if (particleSystem.particleEmitterType) {
  62490. serializationObject.particleEmitterType = particleSystem.particleEmitterType.serialize();
  62491. }
  62492. if (particleSystem.particleTexture) {
  62493. serializationObject.textureName = particleSystem.particleTexture.name;
  62494. serializationObject.invertY = particleSystem.particleTexture._invertY;
  62495. }
  62496. // Animations
  62497. BABYLON.Animation.AppendSerializedAnimations(particleSystem, serializationObject);
  62498. serializationObject.beginAnimationOnStart = particleSystem.beginAnimationOnStart;
  62499. serializationObject.beginAnimationFrom = particleSystem.beginAnimationFrom;
  62500. serializationObject.beginAnimationTo = particleSystem.beginAnimationTo;
  62501. serializationObject.beginAnimationLoop = particleSystem.beginAnimationLoop;
  62502. // Particle system
  62503. serializationObject.startDelay = particleSystem.startDelay;
  62504. serializationObject.renderingGroupId = particleSystem.renderingGroupId;
  62505. serializationObject.isBillboardBased = particleSystem.isBillboardBased;
  62506. serializationObject.billboardMode = particleSystem.billboardMode;
  62507. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  62508. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  62509. serializationObject.minSize = particleSystem.minSize;
  62510. serializationObject.maxSize = particleSystem.maxSize;
  62511. serializationObject.minScaleX = particleSystem.minScaleX;
  62512. serializationObject.maxScaleX = particleSystem.maxScaleX;
  62513. serializationObject.minScaleY = particleSystem.minScaleY;
  62514. serializationObject.maxScaleY = particleSystem.maxScaleY;
  62515. serializationObject.minEmitPower = particleSystem.minEmitPower;
  62516. serializationObject.maxEmitPower = particleSystem.maxEmitPower;
  62517. serializationObject.minLifeTime = particleSystem.minLifeTime;
  62518. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  62519. serializationObject.emitRate = particleSystem.emitRate;
  62520. serializationObject.gravity = particleSystem.gravity.asArray();
  62521. serializationObject.noiseStrength = particleSystem.noiseStrength.asArray();
  62522. serializationObject.color1 = particleSystem.color1.asArray();
  62523. serializationObject.color2 = particleSystem.color2.asArray();
  62524. serializationObject.colorDead = particleSystem.colorDead.asArray();
  62525. serializationObject.updateSpeed = particleSystem.updateSpeed;
  62526. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  62527. serializationObject.blendMode = particleSystem.blendMode;
  62528. serializationObject.preWarmCycles = particleSystem.preWarmCycles;
  62529. serializationObject.preWarmStepOffset = particleSystem.preWarmStepOffset;
  62530. serializationObject.minInitialRotation = particleSystem.minInitialRotation;
  62531. serializationObject.maxInitialRotation = particleSystem.maxInitialRotation;
  62532. serializationObject.startSpriteCellID = particleSystem.startSpriteCellID;
  62533. serializationObject.endSpriteCellID = particleSystem.endSpriteCellID;
  62534. serializationObject.spriteCellChangeSpeed = particleSystem.spriteCellChangeSpeed;
  62535. serializationObject.spriteCellWidth = particleSystem.spriteCellWidth;
  62536. serializationObject.spriteCellHeight = particleSystem.spriteCellHeight;
  62537. serializationObject.spriteRandomStartCell = particleSystem.spriteRandomStartCell;
  62538. serializationObject.isAnimationSheetEnabled = particleSystem.isAnimationSheetEnabled;
  62539. var colorGradients = particleSystem.getColorGradients();
  62540. if (colorGradients) {
  62541. serializationObject.colorGradients = [];
  62542. for (var _i = 0, colorGradients_1 = colorGradients; _i < colorGradients_1.length; _i++) {
  62543. var colorGradient = colorGradients_1[_i];
  62544. var serializedGradient = {
  62545. gradient: colorGradient.gradient,
  62546. color1: colorGradient.color1.asArray()
  62547. };
  62548. if (colorGradient.color2) {
  62549. serializedGradient.color2 = colorGradient.color2.asArray();
  62550. }
  62551. serializationObject.colorGradients.push(serializedGradient);
  62552. }
  62553. }
  62554. var rampGradients = particleSystem.getRampGradients();
  62555. if (rampGradients) {
  62556. serializationObject.rampGradients = [];
  62557. for (var _a = 0, rampGradients_1 = rampGradients; _a < rampGradients_1.length; _a++) {
  62558. var rampGradient = rampGradients_1[_a];
  62559. var serializedGradient = {
  62560. gradient: rampGradient.gradient,
  62561. color: rampGradient.color.asArray()
  62562. };
  62563. serializationObject.rampGradients.push(serializedGradient);
  62564. }
  62565. serializationObject.useRampGradients = particleSystem.useRampGradients;
  62566. }
  62567. var colorRemapGradients = particleSystem.getColorRemapGradients();
  62568. if (colorRemapGradients) {
  62569. serializationObject.colorRemapGradients = [];
  62570. for (var _b = 0, colorRemapGradients_1 = colorRemapGradients; _b < colorRemapGradients_1.length; _b++) {
  62571. var colorRemapGradient = colorRemapGradients_1[_b];
  62572. var serializedGradient = {
  62573. gradient: colorRemapGradient.gradient,
  62574. factor1: colorRemapGradient.factor1
  62575. };
  62576. if (colorRemapGradient.factor2 !== undefined) {
  62577. serializedGradient.factor2 = colorRemapGradient.factor2;
  62578. }
  62579. serializationObject.colorRemapGradients.push(serializedGradient);
  62580. }
  62581. }
  62582. var alphaRemapGradients = particleSystem.getAlphaRemapGradients();
  62583. if (alphaRemapGradients) {
  62584. serializationObject.alphaRemapGradients = [];
  62585. for (var _c = 0, alphaRemapGradients_1 = alphaRemapGradients; _c < alphaRemapGradients_1.length; _c++) {
  62586. var alphaRemapGradient = alphaRemapGradients_1[_c];
  62587. var serializedGradient = {
  62588. gradient: alphaRemapGradient.gradient,
  62589. factor1: alphaRemapGradient.factor1
  62590. };
  62591. if (alphaRemapGradient.factor2 !== undefined) {
  62592. serializedGradient.factor2 = alphaRemapGradient.factor2;
  62593. }
  62594. serializationObject.alphaRemapGradients.push(serializedGradient);
  62595. }
  62596. }
  62597. var sizeGradients = particleSystem.getSizeGradients();
  62598. if (sizeGradients) {
  62599. serializationObject.sizeGradients = [];
  62600. for (var _d = 0, sizeGradients_1 = sizeGradients; _d < sizeGradients_1.length; _d++) {
  62601. var sizeGradient = sizeGradients_1[_d];
  62602. var serializedGradient = {
  62603. gradient: sizeGradient.gradient,
  62604. factor1: sizeGradient.factor1
  62605. };
  62606. if (sizeGradient.factor2 !== undefined) {
  62607. serializedGradient.factor2 = sizeGradient.factor2;
  62608. }
  62609. serializationObject.sizeGradients.push(serializedGradient);
  62610. }
  62611. }
  62612. var angularSpeedGradients = particleSystem.getAngularSpeedGradients();
  62613. if (angularSpeedGradients) {
  62614. serializationObject.angularSpeedGradients = [];
  62615. for (var _e = 0, angularSpeedGradients_1 = angularSpeedGradients; _e < angularSpeedGradients_1.length; _e++) {
  62616. var angularSpeedGradient = angularSpeedGradients_1[_e];
  62617. var serializedGradient = {
  62618. gradient: angularSpeedGradient.gradient,
  62619. factor1: angularSpeedGradient.factor1
  62620. };
  62621. if (angularSpeedGradient.factor2 !== undefined) {
  62622. serializedGradient.factor2 = angularSpeedGradient.factor2;
  62623. }
  62624. serializationObject.angularSpeedGradients.push(serializedGradient);
  62625. }
  62626. }
  62627. var velocityGradients = particleSystem.getVelocityGradients();
  62628. if (velocityGradients) {
  62629. serializationObject.velocityGradients = [];
  62630. for (var _f = 0, velocityGradients_1 = velocityGradients; _f < velocityGradients_1.length; _f++) {
  62631. var velocityGradient = velocityGradients_1[_f];
  62632. var serializedGradient = {
  62633. gradient: velocityGradient.gradient,
  62634. factor1: velocityGradient.factor1
  62635. };
  62636. if (velocityGradient.factor2 !== undefined) {
  62637. serializedGradient.factor2 = velocityGradient.factor2;
  62638. }
  62639. serializationObject.velocityGradients.push(serializedGradient);
  62640. }
  62641. }
  62642. var dragGradients = particleSystem.getDragGradients();
  62643. if (dragGradients) {
  62644. serializationObject.dragyGradients = [];
  62645. for (var _g = 0, dragGradients_1 = dragGradients; _g < dragGradients_1.length; _g++) {
  62646. var dragGradient = dragGradients_1[_g];
  62647. var serializedGradient = {
  62648. gradient: dragGradient.gradient,
  62649. factor1: dragGradient.factor1
  62650. };
  62651. if (dragGradient.factor2 !== undefined) {
  62652. serializedGradient.factor2 = dragGradient.factor2;
  62653. }
  62654. serializationObject.dragGradients.push(serializedGradient);
  62655. }
  62656. }
  62657. var emitRateGradients = particleSystem.getEmitRateGradients();
  62658. if (emitRateGradients) {
  62659. serializationObject.emitRateGradients = [];
  62660. for (var _h = 0, emitRateGradients_1 = emitRateGradients; _h < emitRateGradients_1.length; _h++) {
  62661. var emitRateGradient = emitRateGradients_1[_h];
  62662. var serializedGradient = {
  62663. gradient: emitRateGradient.gradient,
  62664. factor1: emitRateGradient.factor1
  62665. };
  62666. if (emitRateGradient.factor2 !== undefined) {
  62667. serializedGradient.factor2 = emitRateGradient.factor2;
  62668. }
  62669. serializationObject.emitRateGradients.push(serializedGradient);
  62670. }
  62671. }
  62672. var startSizeGradients = particleSystem.getStartSizeGradients();
  62673. if (startSizeGradients) {
  62674. serializationObject.startSizeGradients = [];
  62675. for (var _j = 0, startSizeGradients_1 = startSizeGradients; _j < startSizeGradients_1.length; _j++) {
  62676. var startSizeGradient = startSizeGradients_1[_j];
  62677. var serializedGradient = {
  62678. gradient: startSizeGradient.gradient,
  62679. factor1: startSizeGradient.factor1
  62680. };
  62681. if (startSizeGradient.factor2 !== undefined) {
  62682. serializedGradient.factor2 = startSizeGradient.factor2;
  62683. }
  62684. serializationObject.startSizeGradients.push(serializedGradient);
  62685. }
  62686. }
  62687. var lifeTimeGradients = particleSystem.getLifeTimeGradients();
  62688. if (lifeTimeGradients) {
  62689. serializationObject.lifeTimeGradients = [];
  62690. for (var _k = 0, lifeTimeGradients_1 = lifeTimeGradients; _k < lifeTimeGradients_1.length; _k++) {
  62691. var lifeTimeGradient = lifeTimeGradients_1[_k];
  62692. var serializedGradient = {
  62693. gradient: lifeTimeGradient.gradient,
  62694. factor1: lifeTimeGradient.factor1
  62695. };
  62696. if (lifeTimeGradient.factor2 !== undefined) {
  62697. serializedGradient.factor2 = lifeTimeGradient.factor2;
  62698. }
  62699. serializationObject.lifeTimeGradients.push(serializedGradient);
  62700. }
  62701. }
  62702. var limitVelocityGradients = particleSystem.getLimitVelocityGradients();
  62703. if (limitVelocityGradients) {
  62704. serializationObject.limitVelocityGradients = [];
  62705. for (var _l = 0, limitVelocityGradients_1 = limitVelocityGradients; _l < limitVelocityGradients_1.length; _l++) {
  62706. var limitVelocityGradient = limitVelocityGradients_1[_l];
  62707. var serializedGradient = {
  62708. gradient: limitVelocityGradient.gradient,
  62709. factor1: limitVelocityGradient.factor1
  62710. };
  62711. if (limitVelocityGradient.factor2 !== undefined) {
  62712. serializedGradient.factor2 = limitVelocityGradient.factor2;
  62713. }
  62714. serializationObject.limitVelocityGradients.push(serializedGradient);
  62715. }
  62716. serializationObject.limitVelocityDamping = particleSystem.limitVelocityDamping;
  62717. }
  62718. if (particleSystem.noiseTexture) {
  62719. serializationObject.noiseTexture = particleSystem.noiseTexture.serialize();
  62720. }
  62721. };
  62722. /** @hidden */
  62723. ParticleSystem._Parse = function (parsedParticleSystem, particleSystem, scene, rootUrl) {
  62724. // Texture
  62725. if (parsedParticleSystem.textureName) {
  62726. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene, false, parsedParticleSystem.invertY !== undefined ? parsedParticleSystem.invertY : true);
  62727. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  62728. }
  62729. // Emitter
  62730. if (!parsedParticleSystem.emitterId && parsedParticleSystem.emitterId !== 0 && parsedParticleSystem.emitter === undefined) {
  62731. particleSystem.emitter = BABYLON.Vector3.Zero();
  62732. }
  62733. else if (parsedParticleSystem.emitterId) {
  62734. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  62735. }
  62736. else {
  62737. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  62738. }
  62739. // Misc.
  62740. if (parsedParticleSystem.renderingGroupId !== undefined) {
  62741. particleSystem.renderingGroupId = parsedParticleSystem.renderingGroupId;
  62742. }
  62743. if (parsedParticleSystem.isBillboardBased !== undefined) {
  62744. particleSystem.isBillboardBased = parsedParticleSystem.isBillboardBased;
  62745. }
  62746. if (parsedParticleSystem.billboardMode !== undefined) {
  62747. particleSystem.billboardMode = parsedParticleSystem.billboardMode;
  62748. }
  62749. // Animations
  62750. if (parsedParticleSystem.animations) {
  62751. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  62752. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  62753. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  62754. }
  62755. particleSystem.beginAnimationOnStart = parsedParticleSystem.beginAnimationOnStart;
  62756. particleSystem.beginAnimationFrom = parsedParticleSystem.beginAnimationFrom;
  62757. particleSystem.beginAnimationTo = parsedParticleSystem.beginAnimationTo;
  62758. particleSystem.beginAnimationLoop = parsedParticleSystem.beginAnimationLoop;
  62759. }
  62760. if (parsedParticleSystem.autoAnimate) {
  62761. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  62762. }
  62763. // Particle system
  62764. particleSystem.startDelay = parsedParticleSystem.startDelay | 0;
  62765. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  62766. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  62767. particleSystem.minSize = parsedParticleSystem.minSize;
  62768. particleSystem.maxSize = parsedParticleSystem.maxSize;
  62769. if (parsedParticleSystem.minScaleX) {
  62770. particleSystem.minScaleX = parsedParticleSystem.minScaleX;
  62771. particleSystem.maxScaleX = parsedParticleSystem.maxScaleX;
  62772. particleSystem.minScaleY = parsedParticleSystem.minScaleY;
  62773. particleSystem.maxScaleY = parsedParticleSystem.maxScaleY;
  62774. }
  62775. if (parsedParticleSystem.preWarmCycles !== undefined) {
  62776. particleSystem.preWarmCycles = parsedParticleSystem.preWarmCycles;
  62777. particleSystem.preWarmStepOffset = parsedParticleSystem.preWarmStepOffset;
  62778. }
  62779. if (parsedParticleSystem.minInitialRotation !== undefined) {
  62780. particleSystem.minInitialRotation = parsedParticleSystem.minInitialRotation;
  62781. particleSystem.maxInitialRotation = parsedParticleSystem.maxInitialRotation;
  62782. }
  62783. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  62784. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  62785. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  62786. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  62787. particleSystem.emitRate = parsedParticleSystem.emitRate;
  62788. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  62789. if (parsedParticleSystem.noiseStrength) {
  62790. particleSystem.noiseStrength = BABYLON.Vector3.FromArray(parsedParticleSystem.noiseStrength);
  62791. }
  62792. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  62793. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  62794. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  62795. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  62796. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  62797. particleSystem.blendMode = parsedParticleSystem.blendMode;
  62798. if (parsedParticleSystem.colorGradients) {
  62799. for (var _i = 0, _a = parsedParticleSystem.colorGradients; _i < _a.length; _i++) {
  62800. var colorGradient = _a[_i];
  62801. particleSystem.addColorGradient(colorGradient.gradient, BABYLON.Color4.FromArray(colorGradient.color1), colorGradient.color2 ? BABYLON.Color4.FromArray(colorGradient.color2) : undefined);
  62802. }
  62803. }
  62804. if (parsedParticleSystem.rampGradients) {
  62805. for (var _b = 0, _c = parsedParticleSystem.rampGradients; _b < _c.length; _b++) {
  62806. var rampGradient = _c[_b];
  62807. particleSystem.addRampGradient(rampGradient.gradient, BABYLON.Color3.FromArray(rampGradient.color));
  62808. }
  62809. particleSystem.useRampGradients = parsedParticleSystem.useRampGradients;
  62810. }
  62811. if (parsedParticleSystem.colorRemapGradients) {
  62812. for (var _d = 0, _e = parsedParticleSystem.colorRemapGradients; _d < _e.length; _d++) {
  62813. var colorRemapGradient = _e[_d];
  62814. particleSystem.addColorRemapGradient(colorRemapGradient.gradient, colorRemapGradient.factor1 !== undefined ? colorRemapGradient.factor1 : colorRemapGradient.factor, colorRemapGradient.factor2);
  62815. }
  62816. }
  62817. if (parsedParticleSystem.alphaRemapGradients) {
  62818. for (var _f = 0, _g = parsedParticleSystem.alphaRemapGradients; _f < _g.length; _f++) {
  62819. var alphaRemapGradient = _g[_f];
  62820. particleSystem.addAlphaRemapGradient(alphaRemapGradient.gradient, alphaRemapGradient.factor1 !== undefined ? alphaRemapGradient.factor1 : alphaRemapGradient.factor, alphaRemapGradient.factor2);
  62821. }
  62822. }
  62823. if (parsedParticleSystem.sizeGradients) {
  62824. for (var _h = 0, _j = parsedParticleSystem.sizeGradients; _h < _j.length; _h++) {
  62825. var sizeGradient = _j[_h];
  62826. particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor1 !== undefined ? sizeGradient.factor1 : sizeGradient.factor, sizeGradient.factor2);
  62827. }
  62828. }
  62829. if (parsedParticleSystem.sizeGradients) {
  62830. for (var _k = 0, _l = parsedParticleSystem.sizeGradients; _k < _l.length; _k++) {
  62831. var sizeGradient = _l[_k];
  62832. particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor1 !== undefined ? sizeGradient.factor1 : sizeGradient.factor, sizeGradient.factor2);
  62833. }
  62834. }
  62835. if (parsedParticleSystem.angularSpeedGradients) {
  62836. for (var _m = 0, _o = parsedParticleSystem.angularSpeedGradients; _m < _o.length; _m++) {
  62837. var angularSpeedGradient = _o[_m];
  62838. particleSystem.addAngularSpeedGradient(angularSpeedGradient.gradient, angularSpeedGradient.factor1 !== undefined ? angularSpeedGradient.factor1 : angularSpeedGradient.factor, angularSpeedGradient.factor2);
  62839. }
  62840. }
  62841. if (parsedParticleSystem.velocityGradients) {
  62842. for (var _p = 0, _q = parsedParticleSystem.velocityGradients; _p < _q.length; _p++) {
  62843. var velocityGradient = _q[_p];
  62844. particleSystem.addVelocityGradient(velocityGradient.gradient, velocityGradient.factor1 !== undefined ? velocityGradient.factor1 : velocityGradient.factor, velocityGradient.factor2);
  62845. }
  62846. }
  62847. if (parsedParticleSystem.dragGradients) {
  62848. for (var _r = 0, _s = parsedParticleSystem.dragGradients; _r < _s.length; _r++) {
  62849. var dragGradient = _s[_r];
  62850. particleSystem.addDragGradient(dragGradient.gradient, dragGradient.factor1 !== undefined ? dragGradient.factor1 : dragGradient.factor, dragGradient.factor2);
  62851. }
  62852. }
  62853. if (parsedParticleSystem.emitRateGradients) {
  62854. for (var _t = 0, _u = parsedParticleSystem.emitRateGradients; _t < _u.length; _t++) {
  62855. var emitRateGradient = _u[_t];
  62856. particleSystem.addEmitRateGradient(emitRateGradient.gradient, emitRateGradient.factor1 !== undefined ? emitRateGradient.factor1 : emitRateGradient.factor, emitRateGradient.factor2);
  62857. }
  62858. }
  62859. if (parsedParticleSystem.startSizeGradients) {
  62860. for (var _v = 0, _w = parsedParticleSystem.startSizeGradients; _v < _w.length; _v++) {
  62861. var startSizeGradient = _w[_v];
  62862. particleSystem.addStartSizeGradient(startSizeGradient.gradient, startSizeGradient.factor1 !== undefined ? startSizeGradient.factor1 : startSizeGradient.factor, startSizeGradient.factor2);
  62863. }
  62864. }
  62865. if (parsedParticleSystem.lifeTimeGradients) {
  62866. for (var _x = 0, _y = parsedParticleSystem.lifeTimeGradients; _x < _y.length; _x++) {
  62867. var lifeTimeGradient = _y[_x];
  62868. particleSystem.addLifeTimeGradient(lifeTimeGradient.gradient, lifeTimeGradient.factor1 !== undefined ? lifeTimeGradient.factor1 : lifeTimeGradient.factor, lifeTimeGradient.factor2);
  62869. }
  62870. }
  62871. if (parsedParticleSystem.limitVelocityGradients) {
  62872. for (var _z = 0, _0 = parsedParticleSystem.limitVelocityGradients; _z < _0.length; _z++) {
  62873. var limitVelocityGradient = _0[_z];
  62874. particleSystem.addLimitVelocityGradient(limitVelocityGradient.gradient, limitVelocityGradient.factor1 !== undefined ? limitVelocityGradient.factor1 : limitVelocityGradient.factor, limitVelocityGradient.factor2);
  62875. }
  62876. particleSystem.limitVelocityDamping = parsedParticleSystem.limitVelocityDamping;
  62877. }
  62878. if (parsedParticleSystem.noiseTexture) {
  62879. particleSystem.noiseTexture = BABYLON.ProceduralTexture.Parse(parsedParticleSystem.noiseTexture, scene, rootUrl);
  62880. }
  62881. // Emitter
  62882. var emitterType;
  62883. if (parsedParticleSystem.particleEmitterType) {
  62884. switch (parsedParticleSystem.particleEmitterType.type) {
  62885. case "SphereParticleEmitter":
  62886. emitterType = new BABYLON.SphereParticleEmitter();
  62887. break;
  62888. case "SphereDirectedParticleEmitter":
  62889. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  62890. break;
  62891. case "ConeEmitter":
  62892. case "ConeParticleEmitter":
  62893. emitterType = new BABYLON.ConeParticleEmitter();
  62894. break;
  62895. case "CylinderParticleEmitter":
  62896. emitterType = new BABYLON.CylinderParticleEmitter();
  62897. break;
  62898. case "HemisphericParticleEmitter":
  62899. emitterType = new BABYLON.HemisphericParticleEmitter();
  62900. break;
  62901. case "BoxEmitter":
  62902. case "BoxParticleEmitter":
  62903. default:
  62904. emitterType = new BABYLON.BoxParticleEmitter();
  62905. break;
  62906. }
  62907. emitterType.parse(parsedParticleSystem.particleEmitterType);
  62908. }
  62909. else {
  62910. emitterType = new BABYLON.BoxParticleEmitter();
  62911. emitterType.parse(parsedParticleSystem);
  62912. }
  62913. particleSystem.particleEmitterType = emitterType;
  62914. // Animation sheet
  62915. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  62916. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  62917. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  62918. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  62919. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  62920. particleSystem.spriteRandomStartCell = parsedParticleSystem.spriteRandomStartCell;
  62921. };
  62922. /**
  62923. * Parses a JSON object to create a particle system.
  62924. * @param parsedParticleSystem The JSON object to parse
  62925. * @param scene The scene to create the particle system in
  62926. * @param rootUrl The root url to use to load external dependencies like texture
  62927. * @param doNotStart Ignore the preventAutoStart attribute and does not start
  62928. * @returns the Parsed particle system
  62929. */
  62930. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl, doNotStart) {
  62931. if (doNotStart === void 0) { doNotStart = false; }
  62932. var name = parsedParticleSystem.name;
  62933. var custom = null;
  62934. var program = null;
  62935. if (parsedParticleSystem.customShader) {
  62936. program = parsedParticleSystem.customShader;
  62937. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  62938. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  62939. }
  62940. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  62941. particleSystem.customShader = program;
  62942. if (parsedParticleSystem.id) {
  62943. particleSystem.id = parsedParticleSystem.id;
  62944. }
  62945. // SubEmitters
  62946. if (parsedParticleSystem.subEmitters) {
  62947. particleSystem.subEmitters = [];
  62948. for (var _i = 0, _a = parsedParticleSystem.subEmitters; _i < _a.length; _i++) {
  62949. var cell = _a[_i];
  62950. var cellArray = [];
  62951. for (var _b = 0, cell_1 = cell; _b < cell_1.length; _b++) {
  62952. var sub = cell_1[_b];
  62953. cellArray.push(BABYLON.SubEmitter.Parse(sub, scene, rootUrl));
  62954. }
  62955. particleSystem.subEmitters.push(cellArray);
  62956. }
  62957. }
  62958. ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  62959. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  62960. // Auto start
  62961. if (parsedParticleSystem.preventAutoStart) {
  62962. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  62963. }
  62964. if (!doNotStart && !particleSystem.preventAutoStart) {
  62965. particleSystem.start();
  62966. }
  62967. return particleSystem;
  62968. };
  62969. /**
  62970. * Billboard mode will only apply to Y axis
  62971. */
  62972. ParticleSystem.BILLBOARDMODE_Y = 2;
  62973. /**
  62974. * Billboard mode will apply to all axes
  62975. */
  62976. ParticleSystem.BILLBOARDMODE_ALL = 7;
  62977. /**
  62978. * Special billboard mode where the particle will be biilboard to the camera but rotated to align with direction
  62979. */
  62980. ParticleSystem.BILLBOARDMODE_STRETCHED = 8;
  62981. return ParticleSystem;
  62982. }(BABYLON.BaseParticleSystem));
  62983. BABYLON.ParticleSystem = ParticleSystem;
  62984. })(BABYLON || (BABYLON = {}));
  62985. //# sourceMappingURL=babylon.particleSystem.js.map
  62986. var BABYLON;
  62987. (function (BABYLON) {
  62988. /**
  62989. * Particle emitter emitting particles from the inside of a box.
  62990. * It emits the particles randomly between 2 given directions.
  62991. */
  62992. var BoxParticleEmitter = /** @class */ (function () {
  62993. /**
  62994. * Creates a new instance BoxParticleEmitter
  62995. */
  62996. function BoxParticleEmitter() {
  62997. /**
  62998. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  62999. */
  63000. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  63001. /**
  63002. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  63003. */
  63004. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  63005. /**
  63006. * 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.
  63007. */
  63008. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  63009. /**
  63010. * 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.
  63011. */
  63012. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  63013. }
  63014. /**
  63015. * Called by the particle System when the direction is computed for the created particle.
  63016. * @param worldMatrix is the world matrix of the particle system
  63017. * @param directionToUpdate is the direction vector to update with the result
  63018. * @param particle is the particle we are computed the direction for
  63019. */
  63020. BoxParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  63021. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  63022. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  63023. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  63024. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  63025. };
  63026. /**
  63027. * Called by the particle System when the position is computed for the created particle.
  63028. * @param worldMatrix is the world matrix of the particle system
  63029. * @param positionToUpdate is the position vector to update with the result
  63030. * @param particle is the particle we are computed the position for
  63031. */
  63032. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  63033. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  63034. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  63035. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  63036. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  63037. };
  63038. /**
  63039. * Clones the current emitter and returns a copy of it
  63040. * @returns the new emitter
  63041. */
  63042. BoxParticleEmitter.prototype.clone = function () {
  63043. var newOne = new BoxParticleEmitter();
  63044. BABYLON.Tools.DeepCopy(this, newOne);
  63045. return newOne;
  63046. };
  63047. /**
  63048. * Called by the GPUParticleSystem to setup the update shader
  63049. * @param effect defines the update shader
  63050. */
  63051. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  63052. effect.setVector3("direction1", this.direction1);
  63053. effect.setVector3("direction2", this.direction2);
  63054. effect.setVector3("minEmitBox", this.minEmitBox);
  63055. effect.setVector3("maxEmitBox", this.maxEmitBox);
  63056. };
  63057. /**
  63058. * Returns a string to use to update the GPU particles update shader
  63059. * @returns a string containng the defines string
  63060. */
  63061. BoxParticleEmitter.prototype.getEffectDefines = function () {
  63062. return "#define BOXEMITTER";
  63063. };
  63064. /**
  63065. * Returns the string "BoxParticleEmitter"
  63066. * @returns a string containing the class name
  63067. */
  63068. BoxParticleEmitter.prototype.getClassName = function () {
  63069. return "BoxParticleEmitter";
  63070. };
  63071. /**
  63072. * Serializes the particle system to a JSON object.
  63073. * @returns the JSON object
  63074. */
  63075. BoxParticleEmitter.prototype.serialize = function () {
  63076. var serializationObject = {};
  63077. serializationObject.type = this.getClassName();
  63078. serializationObject.direction1 = this.direction1.asArray();
  63079. serializationObject.direction2 = this.direction2.asArray();
  63080. serializationObject.minEmitBox = this.minEmitBox.asArray();
  63081. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  63082. return serializationObject;
  63083. };
  63084. /**
  63085. * Parse properties from a JSON object
  63086. * @param serializationObject defines the JSON object
  63087. */
  63088. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  63089. BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
  63090. BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  63091. BABYLON.Vector3.FromArrayToRef(serializationObject.minEmitBox, 0, this.minEmitBox);
  63092. BABYLON.Vector3.FromArrayToRef(serializationObject.maxEmitBox, 0, this.maxEmitBox);
  63093. };
  63094. return BoxParticleEmitter;
  63095. }());
  63096. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  63097. })(BABYLON || (BABYLON = {}));
  63098. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  63099. var BABYLON;
  63100. (function (BABYLON) {
  63101. /**
  63102. * Particle emitter emitting particles from the inside of a cylinder.
  63103. * It emits the particles alongside the cylinder radius. The emission direction might be randomized.
  63104. */
  63105. var CylinderParticleEmitter = /** @class */ (function () {
  63106. /**
  63107. * Creates a new instance CylinderParticleEmitter
  63108. * @param radius the radius of the emission cylinder (1 by default)
  63109. * @param height the height of the emission cylinder (1 by default)
  63110. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  63111. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  63112. */
  63113. function CylinderParticleEmitter(
  63114. /**
  63115. * The radius of the emission cylinder.
  63116. */
  63117. radius,
  63118. /**
  63119. * The height of the emission cylinder.
  63120. */
  63121. height,
  63122. /**
  63123. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  63124. */
  63125. radiusRange,
  63126. /**
  63127. * How much to randomize the particle direction [0-1].
  63128. */
  63129. directionRandomizer) {
  63130. if (radius === void 0) { radius = 1; }
  63131. if (height === void 0) { height = 1; }
  63132. if (radiusRange === void 0) { radiusRange = 1; }
  63133. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  63134. this.radius = radius;
  63135. this.height = height;
  63136. this.radiusRange = radiusRange;
  63137. this.directionRandomizer = directionRandomizer;
  63138. }
  63139. /**
  63140. * Called by the particle System when the direction is computed for the created particle.
  63141. * @param worldMatrix is the world matrix of the particle system
  63142. * @param directionToUpdate is the direction vector to update with the result
  63143. * @param particle is the particle we are computed the direction for
  63144. */
  63145. CylinderParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  63146. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  63147. var randY = BABYLON.Scalar.RandomRange(-this.directionRandomizer / 2, this.directionRandomizer / 2);
  63148. var angle = Math.atan2(direction.x, direction.z);
  63149. angle += BABYLON.Scalar.RandomRange(-Math.PI / 2, Math.PI / 2) * this.directionRandomizer;
  63150. direction.y = randY; // set direction y to rand y to mirror normal of cylinder surface
  63151. direction.x = Math.sin(angle);
  63152. direction.z = Math.cos(angle);
  63153. direction.normalize();
  63154. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  63155. };
  63156. /**
  63157. * Called by the particle System when the position is computed for the created particle.
  63158. * @param worldMatrix is the world matrix of the particle system
  63159. * @param positionToUpdate is the position vector to update with the result
  63160. * @param particle is the particle we are computed the position for
  63161. */
  63162. CylinderParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  63163. var yPos = BABYLON.Scalar.RandomRange(-this.height / 2, this.height / 2);
  63164. var angle = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  63165. // Pick a properly distributed point within the circle https://programming.guide/random-point-within-circle.html
  63166. var radiusDistribution = BABYLON.Scalar.RandomRange((1 - this.radiusRange) * (1 - this.radiusRange), 1);
  63167. var positionRadius = Math.sqrt(radiusDistribution) * this.radius;
  63168. var xPos = positionRadius * Math.cos(angle);
  63169. var zPos = positionRadius * Math.sin(angle);
  63170. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(xPos, yPos, zPos, worldMatrix, positionToUpdate);
  63171. };
  63172. /**
  63173. * Clones the current emitter and returns a copy of it
  63174. * @returns the new emitter
  63175. */
  63176. CylinderParticleEmitter.prototype.clone = function () {
  63177. var newOne = new CylinderParticleEmitter(this.radius, this.directionRandomizer);
  63178. BABYLON.Tools.DeepCopy(this, newOne);
  63179. return newOne;
  63180. };
  63181. /**
  63182. * Called by the GPUParticleSystem to setup the update shader
  63183. * @param effect defines the update shader
  63184. */
  63185. CylinderParticleEmitter.prototype.applyToShader = function (effect) {
  63186. effect.setFloat("radius", this.radius);
  63187. effect.setFloat("height", this.height);
  63188. effect.setFloat("radiusRange", this.radiusRange);
  63189. effect.setFloat("directionRandomizer", this.directionRandomizer);
  63190. };
  63191. /**
  63192. * Returns a string to use to update the GPU particles update shader
  63193. * @returns a string containng the defines string
  63194. */
  63195. CylinderParticleEmitter.prototype.getEffectDefines = function () {
  63196. return "#define CYLINDEREMITTER";
  63197. };
  63198. /**
  63199. * Returns the string "CylinderParticleEmitter"
  63200. * @returns a string containing the class name
  63201. */
  63202. CylinderParticleEmitter.prototype.getClassName = function () {
  63203. return "CylinderParticleEmitter";
  63204. };
  63205. /**
  63206. * Serializes the particle system to a JSON object.
  63207. * @returns the JSON object
  63208. */
  63209. CylinderParticleEmitter.prototype.serialize = function () {
  63210. var serializationObject = {};
  63211. serializationObject.type = this.getClassName();
  63212. serializationObject.radius = this.radius;
  63213. serializationObject.height = this.height;
  63214. serializationObject.radiusRange = this.radiusRange;
  63215. serializationObject.directionRandomizer = this.directionRandomizer;
  63216. return serializationObject;
  63217. };
  63218. /**
  63219. * Parse properties from a JSON object
  63220. * @param serializationObject defines the JSON object
  63221. */
  63222. CylinderParticleEmitter.prototype.parse = function (serializationObject) {
  63223. this.radius = serializationObject.radius;
  63224. this.height = serializationObject.height;
  63225. this.radiusRange = serializationObject.radiusRange;
  63226. this.directionRandomizer = serializationObject.directionRandomizer;
  63227. };
  63228. return CylinderParticleEmitter;
  63229. }());
  63230. BABYLON.CylinderParticleEmitter = CylinderParticleEmitter;
  63231. /**
  63232. * Particle emitter emitting particles from the inside of a cylinder.
  63233. * It emits the particles randomly between two vectors.
  63234. */
  63235. var CylinderDirectedParticleEmitter = /** @class */ (function (_super) {
  63236. __extends(CylinderDirectedParticleEmitter, _super);
  63237. /**
  63238. * Creates a new instance CylinderDirectedParticleEmitter
  63239. * @param radius the radius of the emission cylinder (1 by default)
  63240. * @param height the height of the emission cylinder (1 by default)
  63241. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  63242. * @param direction1 the min limit of the emission direction (up vector by default)
  63243. * @param direction2 the max limit of the emission direction (up vector by default)
  63244. */
  63245. function CylinderDirectedParticleEmitter(radius, height, radiusRange,
  63246. /**
  63247. * The min limit of the emission direction.
  63248. */
  63249. direction1,
  63250. /**
  63251. * The max limit of the emission direction.
  63252. */
  63253. direction2) {
  63254. if (radius === void 0) { radius = 1; }
  63255. if (height === void 0) { height = 1; }
  63256. if (radiusRange === void 0) { radiusRange = 1; }
  63257. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  63258. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  63259. var _this = _super.call(this, radius, height, radiusRange) || this;
  63260. _this.direction1 = direction1;
  63261. _this.direction2 = direction2;
  63262. return _this;
  63263. }
  63264. /**
  63265. * Called by the particle System when the direction is computed for the created particle.
  63266. * @param worldMatrix is the world matrix of the particle system
  63267. * @param directionToUpdate is the direction vector to update with the result
  63268. * @param particle is the particle we are computed the direction for
  63269. */
  63270. CylinderDirectedParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  63271. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  63272. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  63273. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  63274. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  63275. };
  63276. /**
  63277. * Clones the current emitter and returns a copy of it
  63278. * @returns the new emitter
  63279. */
  63280. CylinderDirectedParticleEmitter.prototype.clone = function () {
  63281. var newOne = new CylinderDirectedParticleEmitter(this.radius, this.height, this.radiusRange, this.direction1, this.direction2);
  63282. BABYLON.Tools.DeepCopy(this, newOne);
  63283. return newOne;
  63284. };
  63285. /**
  63286. * Called by the GPUParticleSystem to setup the update shader
  63287. * @param effect defines the update shader
  63288. */
  63289. CylinderDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  63290. effect.setFloat("radius", this.radius);
  63291. effect.setFloat("height", this.height);
  63292. effect.setFloat("radiusRange", this.radiusRange);
  63293. effect.setVector3("direction1", this.direction1);
  63294. effect.setVector3("direction2", this.direction2);
  63295. };
  63296. /**
  63297. * Returns a string to use to update the GPU particles update shader
  63298. * @returns a string containng the defines string
  63299. */
  63300. CylinderDirectedParticleEmitter.prototype.getEffectDefines = function () {
  63301. return "#define CYLINDEREMITTER\n#define DIRECTEDCYLINDEREMITTER";
  63302. };
  63303. /**
  63304. * Returns the string "CylinderDirectedParticleEmitter"
  63305. * @returns a string containing the class name
  63306. */
  63307. CylinderDirectedParticleEmitter.prototype.getClassName = function () {
  63308. return "CylinderDirectedParticleEmitter";
  63309. };
  63310. /**
  63311. * Serializes the particle system to a JSON object.
  63312. * @returns the JSON object
  63313. */
  63314. CylinderDirectedParticleEmitter.prototype.serialize = function () {
  63315. var serializationObject = _super.prototype.serialize.call(this);
  63316. serializationObject.direction1 = this.direction1.asArray();
  63317. serializationObject.direction2 = this.direction2.asArray();
  63318. return serializationObject;
  63319. };
  63320. /**
  63321. * Parse properties from a JSON object
  63322. * @param serializationObject defines the JSON object
  63323. */
  63324. CylinderDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  63325. _super.prototype.parse.call(this, serializationObject);
  63326. this.direction1.copyFrom(serializationObject.direction1);
  63327. this.direction2.copyFrom(serializationObject.direction2);
  63328. };
  63329. return CylinderDirectedParticleEmitter;
  63330. }(CylinderParticleEmitter));
  63331. BABYLON.CylinderDirectedParticleEmitter = CylinderDirectedParticleEmitter;
  63332. })(BABYLON || (BABYLON = {}));
  63333. //# sourceMappingURL=babylon.cylinderParticleEmitter.js.map
  63334. var BABYLON;
  63335. (function (BABYLON) {
  63336. /**
  63337. * Particle emitter emitting particles from the inside of a cone.
  63338. * It emits the particles alongside the cone volume from the base to the particle.
  63339. * The emission direction might be randomized.
  63340. */
  63341. var ConeParticleEmitter = /** @class */ (function () {
  63342. /**
  63343. * Creates a new instance ConeParticleEmitter
  63344. * @param radius the radius of the emission cone (1 by default)
  63345. * @param angles the cone base angle (PI by default)
  63346. * @param directionRandomizer defines how much to randomize the particle direction [0-1] (default is 0)
  63347. */
  63348. function ConeParticleEmitter(radius, angle,
  63349. /** defines how much to randomize the particle direction [0-1] (default is 0) */
  63350. directionRandomizer) {
  63351. if (radius === void 0) { radius = 1; }
  63352. if (angle === void 0) { angle = Math.PI; }
  63353. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  63354. this.directionRandomizer = directionRandomizer;
  63355. /**
  63356. * Gets or sets a value indicating where on the radius the start position should be picked (1 = everywhere, 0 = only surface)
  63357. */
  63358. this.radiusRange = 1;
  63359. /**
  63360. * Gets or sets a value indicating where on the height the start position should be picked (1 = everywhere, 0 = only surface)
  63361. */
  63362. this.heightRange = 1;
  63363. /**
  63364. * Gets or sets a value indicating if all the particles should be emitted from the spawn point only (the base of the cone)
  63365. */
  63366. this.emitFromSpawnPointOnly = false;
  63367. this.angle = angle;
  63368. this.radius = radius;
  63369. }
  63370. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  63371. /**
  63372. * Gets or sets the radius of the emission cone
  63373. */
  63374. get: function () {
  63375. return this._radius;
  63376. },
  63377. set: function (value) {
  63378. this._radius = value;
  63379. this._buildHeight();
  63380. },
  63381. enumerable: true,
  63382. configurable: true
  63383. });
  63384. Object.defineProperty(ConeParticleEmitter.prototype, "angle", {
  63385. /**
  63386. * Gets or sets the angle of the emission cone
  63387. */
  63388. get: function () {
  63389. return this._angle;
  63390. },
  63391. set: function (value) {
  63392. this._angle = value;
  63393. this._buildHeight();
  63394. },
  63395. enumerable: true,
  63396. configurable: true
  63397. });
  63398. ConeParticleEmitter.prototype._buildHeight = function () {
  63399. if (this._angle !== 0) {
  63400. this._height = this._radius / Math.tan(this._angle / 2);
  63401. }
  63402. else {
  63403. this._height = 1;
  63404. }
  63405. };
  63406. /**
  63407. * Called by the particle System when the direction is computed for the created particle.
  63408. * @param worldMatrix is the world matrix of the particle system
  63409. * @param directionToUpdate is the direction vector to update with the result
  63410. * @param particle is the particle we are computed the direction for
  63411. */
  63412. ConeParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  63413. if (Math.abs(Math.cos(this._angle)) === 1.0) {
  63414. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, 1.0, 0, worldMatrix, directionToUpdate);
  63415. }
  63416. else {
  63417. // measure the direction Vector from the emitter to the particle.
  63418. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  63419. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  63420. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  63421. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  63422. direction.x += randX;
  63423. direction.y += randY;
  63424. direction.z += randZ;
  63425. direction.normalize();
  63426. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  63427. }
  63428. };
  63429. /**
  63430. * Called by the particle System when the position is computed for the created particle.
  63431. * @param worldMatrix is the world matrix of the particle system
  63432. * @param positionToUpdate is the position vector to update with the result
  63433. * @param particle is the particle we are computed the position for
  63434. */
  63435. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  63436. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  63437. var h;
  63438. if (!this.emitFromSpawnPointOnly) {
  63439. h = BABYLON.Scalar.RandomRange(0, this.heightRange);
  63440. // Better distribution in a cone at normal angles.
  63441. h = 1 - h * h;
  63442. }
  63443. else {
  63444. h = 0.0001;
  63445. }
  63446. var radius = this._radius - BABYLON.Scalar.RandomRange(0, this._radius * this.radiusRange);
  63447. radius = radius * h;
  63448. var randX = radius * Math.sin(s);
  63449. var randZ = radius * Math.cos(s);
  63450. var randY = h * this._height;
  63451. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  63452. };
  63453. /**
  63454. * Clones the current emitter and returns a copy of it
  63455. * @returns the new emitter
  63456. */
  63457. ConeParticleEmitter.prototype.clone = function () {
  63458. var newOne = new ConeParticleEmitter(this._radius, this._angle, this.directionRandomizer);
  63459. BABYLON.Tools.DeepCopy(this, newOne);
  63460. return newOne;
  63461. };
  63462. /**
  63463. * Called by the GPUParticleSystem to setup the update shader
  63464. * @param effect defines the update shader
  63465. */
  63466. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  63467. effect.setFloat2("radius", this._radius, this.radiusRange);
  63468. effect.setFloat("coneAngle", this._angle);
  63469. effect.setFloat2("height", this._height, this.heightRange);
  63470. effect.setFloat("directionRandomizer", this.directionRandomizer);
  63471. };
  63472. /**
  63473. * Returns a string to use to update the GPU particles update shader
  63474. * @returns a string containng the defines string
  63475. */
  63476. ConeParticleEmitter.prototype.getEffectDefines = function () {
  63477. var defines = "#define CONEEMITTER";
  63478. if (this.emitFromSpawnPointOnly) {
  63479. defines += "\n#define CONEEMITTERSPAWNPOINT";
  63480. }
  63481. return defines;
  63482. };
  63483. /**
  63484. * Returns the string "ConeParticleEmitter"
  63485. * @returns a string containing the class name
  63486. */
  63487. ConeParticleEmitter.prototype.getClassName = function () {
  63488. return "ConeParticleEmitter";
  63489. };
  63490. /**
  63491. * Serializes the particle system to a JSON object.
  63492. * @returns the JSON object
  63493. */
  63494. ConeParticleEmitter.prototype.serialize = function () {
  63495. var serializationObject = {};
  63496. serializationObject.type = this.getClassName();
  63497. serializationObject.radius = this._radius;
  63498. serializationObject.angle = this._angle;
  63499. serializationObject.directionRandomizer = this.directionRandomizer;
  63500. return serializationObject;
  63501. };
  63502. /**
  63503. * Parse properties from a JSON object
  63504. * @param serializationObject defines the JSON object
  63505. */
  63506. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  63507. this.radius = serializationObject.radius;
  63508. this.angle = serializationObject.angle;
  63509. this.directionRandomizer = serializationObject.directionRandomizer;
  63510. };
  63511. return ConeParticleEmitter;
  63512. }());
  63513. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  63514. })(BABYLON || (BABYLON = {}));
  63515. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  63516. var BABYLON;
  63517. (function (BABYLON) {
  63518. /**
  63519. * Particle emitter emitting particles from the inside of a sphere.
  63520. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  63521. */
  63522. var SphereParticleEmitter = /** @class */ (function () {
  63523. /**
  63524. * Creates a new instance SphereParticleEmitter
  63525. * @param radius the radius of the emission sphere (1 by default)
  63526. * @param radiusRange the range of the emission sphere [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  63527. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  63528. */
  63529. function SphereParticleEmitter(
  63530. /**
  63531. * The radius of the emission sphere.
  63532. */
  63533. radius,
  63534. /**
  63535. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  63536. */
  63537. radiusRange,
  63538. /**
  63539. * How much to randomize the particle direction [0-1].
  63540. */
  63541. directionRandomizer) {
  63542. if (radius === void 0) { radius = 1; }
  63543. if (radiusRange === void 0) { radiusRange = 1; }
  63544. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  63545. this.radius = radius;
  63546. this.radiusRange = radiusRange;
  63547. this.directionRandomizer = directionRandomizer;
  63548. }
  63549. /**
  63550. * Called by the particle System when the direction is computed for the created particle.
  63551. * @param worldMatrix is the world matrix of the particle system
  63552. * @param directionToUpdate is the direction vector to update with the result
  63553. * @param particle is the particle we are computed the direction for
  63554. */
  63555. SphereParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  63556. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  63557. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  63558. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  63559. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  63560. direction.x += randX;
  63561. direction.y += randY;
  63562. direction.z += randZ;
  63563. direction.normalize();
  63564. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  63565. };
  63566. /**
  63567. * Called by the particle System when the position is computed for the created particle.
  63568. * @param worldMatrix is the world matrix of the particle system
  63569. * @param positionToUpdate is the position vector to update with the result
  63570. * @param particle is the particle we are computed the position for
  63571. */
  63572. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  63573. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  63574. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  63575. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  63576. var theta = Math.acos(2 * v - 1);
  63577. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  63578. var randY = randRadius * Math.cos(theta);
  63579. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  63580. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  63581. };
  63582. /**
  63583. * Clones the current emitter and returns a copy of it
  63584. * @returns the new emitter
  63585. */
  63586. SphereParticleEmitter.prototype.clone = function () {
  63587. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  63588. BABYLON.Tools.DeepCopy(this, newOne);
  63589. return newOne;
  63590. };
  63591. /**
  63592. * Called by the GPUParticleSystem to setup the update shader
  63593. * @param effect defines the update shader
  63594. */
  63595. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  63596. effect.setFloat("radius", this.radius);
  63597. effect.setFloat("radiusRange", this.radiusRange);
  63598. effect.setFloat("directionRandomizer", this.directionRandomizer);
  63599. };
  63600. /**
  63601. * Returns a string to use to update the GPU particles update shader
  63602. * @returns a string containng the defines string
  63603. */
  63604. SphereParticleEmitter.prototype.getEffectDefines = function () {
  63605. return "#define SPHEREEMITTER";
  63606. };
  63607. /**
  63608. * Returns the string "SphereParticleEmitter"
  63609. * @returns a string containing the class name
  63610. */
  63611. SphereParticleEmitter.prototype.getClassName = function () {
  63612. return "SphereParticleEmitter";
  63613. };
  63614. /**
  63615. * Serializes the particle system to a JSON object.
  63616. * @returns the JSON object
  63617. */
  63618. SphereParticleEmitter.prototype.serialize = function () {
  63619. var serializationObject = {};
  63620. serializationObject.type = this.getClassName();
  63621. serializationObject.radius = this.radius;
  63622. serializationObject.radiusRange = this.radiusRange;
  63623. serializationObject.directionRandomizer = this.directionRandomizer;
  63624. return serializationObject;
  63625. };
  63626. /**
  63627. * Parse properties from a JSON object
  63628. * @param serializationObject defines the JSON object
  63629. */
  63630. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  63631. this.radius = serializationObject.radius;
  63632. this.radiusRange = serializationObject.radiusRange;
  63633. this.directionRandomizer = serializationObject.directionRandomizer;
  63634. };
  63635. return SphereParticleEmitter;
  63636. }());
  63637. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  63638. /**
  63639. * Particle emitter emitting particles from the inside of a sphere.
  63640. * It emits the particles randomly between two vectors.
  63641. */
  63642. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  63643. __extends(SphereDirectedParticleEmitter, _super);
  63644. /**
  63645. * Creates a new instance SphereDirectedParticleEmitter
  63646. * @param radius the radius of the emission sphere (1 by default)
  63647. * @param direction1 the min limit of the emission direction (up vector by default)
  63648. * @param direction2 the max limit of the emission direction (up vector by default)
  63649. */
  63650. function SphereDirectedParticleEmitter(radius,
  63651. /**
  63652. * The min limit of the emission direction.
  63653. */
  63654. direction1,
  63655. /**
  63656. * The max limit of the emission direction.
  63657. */
  63658. direction2) {
  63659. if (radius === void 0) { radius = 1; }
  63660. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  63661. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  63662. var _this = _super.call(this, radius) || this;
  63663. _this.direction1 = direction1;
  63664. _this.direction2 = direction2;
  63665. return _this;
  63666. }
  63667. /**
  63668. * Called by the particle System when the direction is computed for the created particle.
  63669. * @param worldMatrix is the world matrix of the particle system
  63670. * @param directionToUpdate is the direction vector to update with the result
  63671. * @param particle is the particle we are computed the direction for
  63672. */
  63673. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  63674. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  63675. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  63676. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  63677. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  63678. };
  63679. /**
  63680. * Clones the current emitter and returns a copy of it
  63681. * @returns the new emitter
  63682. */
  63683. SphereDirectedParticleEmitter.prototype.clone = function () {
  63684. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  63685. BABYLON.Tools.DeepCopy(this, newOne);
  63686. return newOne;
  63687. };
  63688. /**
  63689. * Called by the GPUParticleSystem to setup the update shader
  63690. * @param effect defines the update shader
  63691. */
  63692. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  63693. effect.setFloat("radius", this.radius);
  63694. effect.setFloat("radiusRange", this.radiusRange);
  63695. effect.setVector3("direction1", this.direction1);
  63696. effect.setVector3("direction2", this.direction2);
  63697. };
  63698. /**
  63699. * Returns a string to use to update the GPU particles update shader
  63700. * @returns a string containng the defines string
  63701. */
  63702. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  63703. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  63704. };
  63705. /**
  63706. * Returns the string "SphereDirectedParticleEmitter"
  63707. * @returns a string containing the class name
  63708. */
  63709. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  63710. return "SphereDirectedParticleEmitter";
  63711. };
  63712. /**
  63713. * Serializes the particle system to a JSON object.
  63714. * @returns the JSON object
  63715. */
  63716. SphereDirectedParticleEmitter.prototype.serialize = function () {
  63717. var serializationObject = _super.prototype.serialize.call(this);
  63718. serializationObject.direction1 = this.direction1.asArray();
  63719. serializationObject.direction2 = this.direction2.asArray();
  63720. return serializationObject;
  63721. };
  63722. /**
  63723. * Parse properties from a JSON object
  63724. * @param serializationObject defines the JSON object
  63725. */
  63726. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  63727. _super.prototype.parse.call(this, serializationObject);
  63728. this.direction1.copyFrom(serializationObject.direction1);
  63729. this.direction2.copyFrom(serializationObject.direction2);
  63730. };
  63731. return SphereDirectedParticleEmitter;
  63732. }(SphereParticleEmitter));
  63733. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  63734. })(BABYLON || (BABYLON = {}));
  63735. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  63736. var BABYLON;
  63737. (function (BABYLON) {
  63738. /**
  63739. * Particle emitter emitting particles from the inside of a hemisphere.
  63740. * It emits the particles alongside the hemisphere radius. The emission direction might be randomized.
  63741. */
  63742. var HemisphericParticleEmitter = /** @class */ (function () {
  63743. /**
  63744. * Creates a new instance HemisphericParticleEmitter
  63745. * @param radius the radius of the emission hemisphere (1 by default)
  63746. * @param radiusRange the range of the emission hemisphere [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  63747. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  63748. */
  63749. function HemisphericParticleEmitter(
  63750. /**
  63751. * The radius of the emission hemisphere.
  63752. */
  63753. radius,
  63754. /**
  63755. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  63756. */
  63757. radiusRange,
  63758. /**
  63759. * How much to randomize the particle direction [0-1].
  63760. */
  63761. directionRandomizer) {
  63762. if (radius === void 0) { radius = 1; }
  63763. if (radiusRange === void 0) { radiusRange = 1; }
  63764. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  63765. this.radius = radius;
  63766. this.radiusRange = radiusRange;
  63767. this.directionRandomizer = directionRandomizer;
  63768. }
  63769. /**
  63770. * Called by the particle System when the direction is computed for the created particle.
  63771. * @param worldMatrix is the world matrix of the particle system
  63772. * @param directionToUpdate is the direction vector to update with the result
  63773. * @param particle is the particle we are computed the direction for
  63774. */
  63775. HemisphericParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  63776. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  63777. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  63778. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  63779. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  63780. direction.x += randX;
  63781. direction.y += randY;
  63782. direction.z += randZ;
  63783. direction.normalize();
  63784. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  63785. };
  63786. /**
  63787. * Called by the particle System when the position is computed for the created particle.
  63788. * @param worldMatrix is the world matrix of the particle system
  63789. * @param positionToUpdate is the position vector to update with the result
  63790. * @param particle is the particle we are computed the position for
  63791. */
  63792. HemisphericParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  63793. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  63794. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  63795. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  63796. var theta = Math.acos(2 * v - 1);
  63797. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  63798. var randY = randRadius * Math.cos(theta);
  63799. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  63800. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, Math.abs(randY), randZ, worldMatrix, positionToUpdate);
  63801. };
  63802. /**
  63803. * Clones the current emitter and returns a copy of it
  63804. * @returns the new emitter
  63805. */
  63806. HemisphericParticleEmitter.prototype.clone = function () {
  63807. var newOne = new HemisphericParticleEmitter(this.radius, this.directionRandomizer);
  63808. BABYLON.Tools.DeepCopy(this, newOne);
  63809. return newOne;
  63810. };
  63811. /**
  63812. * Called by the GPUParticleSystem to setup the update shader
  63813. * @param effect defines the update shader
  63814. */
  63815. HemisphericParticleEmitter.prototype.applyToShader = function (effect) {
  63816. effect.setFloat("radius", this.radius);
  63817. effect.setFloat("radiusRange", this.radiusRange);
  63818. effect.setFloat("directionRandomizer", this.directionRandomizer);
  63819. };
  63820. /**
  63821. * Returns a string to use to update the GPU particles update shader
  63822. * @returns a string containng the defines string
  63823. */
  63824. HemisphericParticleEmitter.prototype.getEffectDefines = function () {
  63825. return "#define HEMISPHERICEMITTER";
  63826. };
  63827. /**
  63828. * Returns the string "HemisphericParticleEmitter"
  63829. * @returns a string containing the class name
  63830. */
  63831. HemisphericParticleEmitter.prototype.getClassName = function () {
  63832. return "HemisphericParticleEmitter";
  63833. };
  63834. /**
  63835. * Serializes the particle system to a JSON object.
  63836. * @returns the JSON object
  63837. */
  63838. HemisphericParticleEmitter.prototype.serialize = function () {
  63839. var serializationObject = {};
  63840. serializationObject.type = this.getClassName();
  63841. serializationObject.radius = this.radius;
  63842. serializationObject.radiusRange = this.radiusRange;
  63843. serializationObject.directionRandomizer = this.directionRandomizer;
  63844. return serializationObject;
  63845. };
  63846. /**
  63847. * Parse properties from a JSON object
  63848. * @param serializationObject defines the JSON object
  63849. */
  63850. HemisphericParticleEmitter.prototype.parse = function (serializationObject) {
  63851. this.radius = serializationObject.radius;
  63852. this.radiusRange = serializationObject.radiusRange;
  63853. this.directionRandomizer = serializationObject.directionRandomizer;
  63854. };
  63855. return HemisphericParticleEmitter;
  63856. }());
  63857. BABYLON.HemisphericParticleEmitter = HemisphericParticleEmitter;
  63858. })(BABYLON || (BABYLON = {}));
  63859. //# sourceMappingURL=babylon.hemisphericParticleEmitter.js.map
  63860. var BABYLON;
  63861. (function (BABYLON) {
  63862. /**
  63863. * Particle emitter emitting particles from a point.
  63864. * It emits the particles randomly between 2 given directions.
  63865. */
  63866. var PointParticleEmitter = /** @class */ (function () {
  63867. /**
  63868. * Creates a new instance PointParticleEmitter
  63869. */
  63870. function PointParticleEmitter() {
  63871. /**
  63872. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  63873. */
  63874. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  63875. /**
  63876. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  63877. */
  63878. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  63879. }
  63880. /**
  63881. * Called by the particle System when the direction is computed for the created particle.
  63882. * @param worldMatrix is the world matrix of the particle system
  63883. * @param directionToUpdate is the direction vector to update with the result
  63884. * @param particle is the particle we are computed the direction for
  63885. */
  63886. PointParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  63887. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  63888. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  63889. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  63890. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  63891. };
  63892. /**
  63893. * Called by the particle System when the position is computed for the created particle.
  63894. * @param worldMatrix is the world matrix of the particle system
  63895. * @param positionToUpdate is the position vector to update with the result
  63896. * @param particle is the particle we are computed the position for
  63897. */
  63898. PointParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  63899. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0, 0, 0, worldMatrix, positionToUpdate);
  63900. };
  63901. /**
  63902. * Clones the current emitter and returns a copy of it
  63903. * @returns the new emitter
  63904. */
  63905. PointParticleEmitter.prototype.clone = function () {
  63906. var newOne = new PointParticleEmitter();
  63907. BABYLON.Tools.DeepCopy(this, newOne);
  63908. return newOne;
  63909. };
  63910. /**
  63911. * Called by the GPUParticleSystem to setup the update shader
  63912. * @param effect defines the update shader
  63913. */
  63914. PointParticleEmitter.prototype.applyToShader = function (effect) {
  63915. effect.setVector3("direction1", this.direction1);
  63916. effect.setVector3("direction2", this.direction2);
  63917. };
  63918. /**
  63919. * Returns a string to use to update the GPU particles update shader
  63920. * @returns a string containng the defines string
  63921. */
  63922. PointParticleEmitter.prototype.getEffectDefines = function () {
  63923. return "#define POINTEMITTER";
  63924. };
  63925. /**
  63926. * Returns the string "PointParticleEmitter"
  63927. * @returns a string containing the class name
  63928. */
  63929. PointParticleEmitter.prototype.getClassName = function () {
  63930. return "PointParticleEmitter";
  63931. };
  63932. /**
  63933. * Serializes the particle system to a JSON object.
  63934. * @returns the JSON object
  63935. */
  63936. PointParticleEmitter.prototype.serialize = function () {
  63937. var serializationObject = {};
  63938. serializationObject.type = this.getClassName();
  63939. serializationObject.direction1 = this.direction1.asArray();
  63940. serializationObject.direction2 = this.direction2.asArray();
  63941. return serializationObject;
  63942. };
  63943. /**
  63944. * Parse properties from a JSON object
  63945. * @param serializationObject defines the JSON object
  63946. */
  63947. PointParticleEmitter.prototype.parse = function (serializationObject) {
  63948. BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
  63949. BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  63950. };
  63951. return PointParticleEmitter;
  63952. }());
  63953. BABYLON.PointParticleEmitter = PointParticleEmitter;
  63954. })(BABYLON || (BABYLON = {}));
  63955. //# sourceMappingURL=babylon.pointParticleEmitter.js.map
  63956. var BABYLON;
  63957. (function (BABYLON) {
  63958. // Adds the parsers to the scene parsers.
  63959. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedData, scene, container, rootUrl) {
  63960. var individualParser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);
  63961. if (!individualParser) {
  63962. return;
  63963. }
  63964. // Particles Systems
  63965. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  63966. for (var index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  63967. var parsedParticleSystem = parsedData.particleSystems[index];
  63968. container.particleSystems.push(individualParser(parsedParticleSystem, scene, rootUrl));
  63969. }
  63970. }
  63971. });
  63972. BABYLON.AbstractScene.AddIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedParticleSystem, scene, rootUrl) {
  63973. if (parsedParticleSystem.activeParticleCount) {
  63974. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  63975. return ps;
  63976. }
  63977. else {
  63978. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  63979. return ps;
  63980. }
  63981. });
  63982. BABYLON.Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  63983. if (uniformsNames === void 0) { uniformsNames = []; }
  63984. if (samplers === void 0) { samplers = []; }
  63985. if (defines === void 0) { defines = ""; }
  63986. var attributesNamesOrOptions = BABYLON.ParticleSystem._GetAttributeNamesOrOptions();
  63987. var effectCreationOption = BABYLON.ParticleSystem._GetEffectCreationOptions();
  63988. if (defines.indexOf(" BILLBOARD") === -1) {
  63989. defines += "\n#define BILLBOARD\n";
  63990. }
  63991. if (samplers.indexOf("diffuseSampler") === -1) {
  63992. samplers.push("diffuseSampler");
  63993. }
  63994. return this.createEffect({
  63995. vertex: "particles",
  63996. fragmentElement: fragmentName
  63997. }, attributesNamesOrOptions, effectCreationOption.concat(uniformsNames), samplers, defines, fallbacks, onCompiled, onError);
  63998. };
  63999. BABYLON.Mesh.prototype.getEmittedParticleSystems = function () {
  64000. var results = new Array();
  64001. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  64002. var particleSystem = this.getScene().particleSystems[index];
  64003. if (particleSystem.emitter === this) {
  64004. results.push(particleSystem);
  64005. }
  64006. }
  64007. return results;
  64008. };
  64009. BABYLON.Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  64010. var results = new Array();
  64011. var descendants = this.getDescendants();
  64012. descendants.push(this);
  64013. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  64014. var particleSystem = this.getScene().particleSystems[index];
  64015. var emitter = particleSystem.emitter;
  64016. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  64017. results.push(particleSystem);
  64018. }
  64019. }
  64020. return results;
  64021. };
  64022. })(BABYLON || (BABYLON = {}));
  64023. //# sourceMappingURL=babylon.particleSystemComponent.js.map
  64024. var BABYLON;
  64025. (function (BABYLON) {
  64026. /**
  64027. * Type of sub emitter
  64028. */
  64029. var SubEmitterType;
  64030. (function (SubEmitterType) {
  64031. /**
  64032. * Attached to the particle over it's lifetime
  64033. */
  64034. SubEmitterType[SubEmitterType["ATTACHED"] = 0] = "ATTACHED";
  64035. /**
  64036. * Created when the particle dies
  64037. */
  64038. SubEmitterType[SubEmitterType["END"] = 1] = "END";
  64039. })(SubEmitterType = BABYLON.SubEmitterType || (BABYLON.SubEmitterType = {}));
  64040. /**
  64041. * Sub emitter class used to emit particles from an existing particle
  64042. */
  64043. var SubEmitter = /** @class */ (function () {
  64044. /**
  64045. * Creates a sub emitter
  64046. * @param particleSystem the particle system to be used by the sub emitter
  64047. */
  64048. function SubEmitter(
  64049. /**
  64050. * the particle system to be used by the sub emitter
  64051. */
  64052. particleSystem) {
  64053. this.particleSystem = particleSystem;
  64054. /**
  64055. * Type of the submitter (Default: END)
  64056. */
  64057. this.type = SubEmitterType.END;
  64058. /**
  64059. * 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)
  64060. * Note: This only is supported when using an emitter of type Mesh
  64061. */
  64062. this.inheritDirection = false;
  64063. /**
  64064. * How much of the attached particles speed should be added to the sub emitted particle (default: 0)
  64065. */
  64066. this.inheritedVelocityAmount = 0;
  64067. // Create mesh as emitter to support rotation
  64068. if (!particleSystem.emitter || !particleSystem.emitter.dispose) {
  64069. particleSystem.emitter = new BABYLON.AbstractMesh("SubemitterSystemEmitter", particleSystem.getScene());
  64070. }
  64071. // Automatically dispose of subemitter when system is disposed
  64072. particleSystem.onDisposeObservable.add(function () {
  64073. if (particleSystem.emitter && particleSystem.emitter.dispose) {
  64074. particleSystem.emitter.dispose();
  64075. }
  64076. });
  64077. }
  64078. /**
  64079. * Clones the sub emitter
  64080. * @returns the cloned sub emitter
  64081. */
  64082. SubEmitter.prototype.clone = function () {
  64083. // Clone particle system
  64084. var emitter = this.particleSystem.emitter;
  64085. if (!emitter) {
  64086. emitter = new BABYLON.Vector3();
  64087. }
  64088. else if (emitter instanceof BABYLON.Vector3) {
  64089. emitter = emitter.clone();
  64090. }
  64091. else if (emitter instanceof BABYLON.AbstractMesh) {
  64092. emitter = new BABYLON.Mesh("", emitter.getScene());
  64093. emitter.isVisible = false;
  64094. }
  64095. var clone = new SubEmitter(this.particleSystem.clone("", emitter));
  64096. // Clone properties
  64097. clone.type = this.type;
  64098. clone.inheritDirection = this.inheritDirection;
  64099. clone.inheritedVelocityAmount = this.inheritedVelocityAmount;
  64100. clone.particleSystem._disposeEmitterOnDispose = true;
  64101. clone.particleSystem.disposeOnStop = true;
  64102. return clone;
  64103. };
  64104. /**
  64105. * Serialize current object to a JSON object
  64106. * @returns the serialized object
  64107. */
  64108. SubEmitter.prototype.serialize = function () {
  64109. var serializationObject = {};
  64110. serializationObject.type = this.type;
  64111. serializationObject.inheritDirection = this.inheritDirection;
  64112. serializationObject.inheritedVelocityAmount = this.inheritedVelocityAmount;
  64113. serializationObject.particleSystem = this.particleSystem.serialize();
  64114. return serializationObject;
  64115. };
  64116. /**
  64117. * Creates a new SubEmitter from a serialized JSON version
  64118. * @param serializationObject defines the JSON object to read from
  64119. * @param scene defines the hosting scene
  64120. * @param rootUrl defines the rootUrl for data loading
  64121. * @returns a new SubEmitter
  64122. */
  64123. SubEmitter.Parse = function (serializationObject, scene, rootUrl) {
  64124. var system = serializationObject.particleSystem;
  64125. var subEmitter = new SubEmitter(BABYLON.ParticleSystem.Parse(system, scene, rootUrl));
  64126. subEmitter.type = serializationObject.type;
  64127. subEmitter.inheritDirection = serializationObject.inheritDirection;
  64128. subEmitter.inheritedVelocityAmount = serializationObject.inheritedVelocityAmount;
  64129. subEmitter.particleSystem._isSubEmitter = true;
  64130. return subEmitter;
  64131. };
  64132. /** Release associated resources */
  64133. SubEmitter.prototype.dispose = function () {
  64134. this.particleSystem.dispose();
  64135. };
  64136. return SubEmitter;
  64137. }());
  64138. BABYLON.SubEmitter = SubEmitter;
  64139. })(BABYLON || (BABYLON = {}));
  64140. //# sourceMappingURL=babylon.subEmitter.js.map
  64141. var BABYLON;
  64142. (function (BABYLON) {
  64143. /**
  64144. * The ShaderMaterial object has the necessary methods to pass data from your scene to the Vertex and Fragment Shaders and returns a material that can be applied to any mesh.
  64145. *
  64146. * This returned material effects how the mesh will look based on the code in the shaders.
  64147. *
  64148. * @see http://doc.babylonjs.com/how_to/shader_material
  64149. */
  64150. var ShaderMaterial = /** @class */ (function (_super) {
  64151. __extends(ShaderMaterial, _super);
  64152. /**
  64153. * Instantiate a new shader material.
  64154. * The ShaderMaterial object has the necessary methods to pass data from your scene to the Vertex and Fragment Shaders and returns a material that can be applied to any mesh.
  64155. * This returned material effects how the mesh will look based on the code in the shaders.
  64156. * @see http://doc.babylonjs.com/how_to/shader_material
  64157. * @param name Define the name of the material in the scene
  64158. * @param scene Define the scene the material belongs to
  64159. * @param shaderPath Defines the route to the shader code in one of three ways:
  64160. * - object - { vertex: "custom", fragment: "custom" }, used with BABYLON.Effect.ShadersStore["customVertexShader"] and BABYLON.Effect.ShadersStore["customFragmentShader"]
  64161. * - object - { vertexElement: "vertexShaderCode", fragmentElement: "fragmentShaderCode" }, used with shader code in <script> tags
  64162. * - string - "./COMMON_NAME", used with external files COMMON_NAME.vertex.fx and COMMON_NAME.fragment.fx in index.html folder.
  64163. * @param options Define the options used to create the shader
  64164. */
  64165. function ShaderMaterial(name, scene, shaderPath, options) {
  64166. if (options === void 0) { options = {}; }
  64167. var _this = _super.call(this, name, scene) || this;
  64168. _this._textures = {};
  64169. _this._textureArrays = {};
  64170. _this._floats = {};
  64171. _this._ints = {};
  64172. _this._floatsArrays = {};
  64173. _this._colors3 = {};
  64174. _this._colors3Arrays = {};
  64175. _this._colors4 = {};
  64176. _this._vectors2 = {};
  64177. _this._vectors3 = {};
  64178. _this._vectors4 = {};
  64179. _this._matrices = {};
  64180. _this._matrices3x3 = {};
  64181. _this._matrices2x2 = {};
  64182. _this._vectors2Arrays = {};
  64183. _this._vectors3Arrays = {};
  64184. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  64185. _this._shaderPath = shaderPath;
  64186. _this._options = __assign({ needAlphaBlending: false, needAlphaTesting: false, attributes: ["position", "normal", "uv"], uniforms: ["worldViewProjection"], uniformBuffers: [], samplers: [], defines: [] }, options);
  64187. return _this;
  64188. }
  64189. /**
  64190. * Gets the current class name of the material e.g. "ShaderMaterial"
  64191. * Mainly use in serialization.
  64192. * @returns the class name
  64193. */
  64194. ShaderMaterial.prototype.getClassName = function () {
  64195. return "ShaderMaterial";
  64196. };
  64197. /**
  64198. * Specifies if the material will require alpha blending
  64199. * @returns a boolean specifying if alpha blending is needed
  64200. */
  64201. ShaderMaterial.prototype.needAlphaBlending = function () {
  64202. return (this.alpha < 1.0) || this._options.needAlphaBlending;
  64203. };
  64204. /**
  64205. * Specifies if this material should be rendered in alpha test mode
  64206. * @returns a boolean specifying if an alpha test is needed.
  64207. */
  64208. ShaderMaterial.prototype.needAlphaTesting = function () {
  64209. return this._options.needAlphaTesting;
  64210. };
  64211. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  64212. if (this._options.uniforms.indexOf(uniformName) === -1) {
  64213. this._options.uniforms.push(uniformName);
  64214. }
  64215. };
  64216. /**
  64217. * Set a texture in the shader.
  64218. * @param name Define the name of the uniform samplers as defined in the shader
  64219. * @param texture Define the texture to bind to this sampler
  64220. * @return the material itself allowing "fluent" like uniform updates
  64221. */
  64222. ShaderMaterial.prototype.setTexture = function (name, texture) {
  64223. if (this._options.samplers.indexOf(name) === -1) {
  64224. this._options.samplers.push(name);
  64225. }
  64226. this._textures[name] = texture;
  64227. return this;
  64228. };
  64229. /**
  64230. * Set a texture array in the shader.
  64231. * @param name Define the name of the uniform sampler array as defined in the shader
  64232. * @param textures Define the list of textures to bind to this sampler
  64233. * @return the material itself allowing "fluent" like uniform updates
  64234. */
  64235. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  64236. if (this._options.samplers.indexOf(name) === -1) {
  64237. this._options.samplers.push(name);
  64238. }
  64239. this._checkUniform(name);
  64240. this._textureArrays[name] = textures;
  64241. return this;
  64242. };
  64243. /**
  64244. * Set a float in the shader.
  64245. * @param name Define the name of the uniform as defined in the shader
  64246. * @param value Define the value to give to the uniform
  64247. * @return the material itself allowing "fluent" like uniform updates
  64248. */
  64249. ShaderMaterial.prototype.setFloat = function (name, value) {
  64250. this._checkUniform(name);
  64251. this._floats[name] = value;
  64252. return this;
  64253. };
  64254. /**
  64255. * Set a int in the shader.
  64256. * @param name Define the name of the uniform as defined in the shader
  64257. * @param value Define the value to give to the uniform
  64258. * @return the material itself allowing "fluent" like uniform updates
  64259. */
  64260. ShaderMaterial.prototype.setInt = function (name, value) {
  64261. this._checkUniform(name);
  64262. this._ints[name] = value;
  64263. return this;
  64264. };
  64265. /**
  64266. * Set an array of floats in the shader.
  64267. * @param name Define the name of the uniform as defined in the shader
  64268. * @param value Define the value to give to the uniform
  64269. * @return the material itself allowing "fluent" like uniform updates
  64270. */
  64271. ShaderMaterial.prototype.setFloats = function (name, value) {
  64272. this._checkUniform(name);
  64273. this._floatsArrays[name] = value;
  64274. return this;
  64275. };
  64276. /**
  64277. * Set a vec3 in the shader from a Color3.
  64278. * @param name Define the name of the uniform as defined in the shader
  64279. * @param value Define the value to give to the uniform
  64280. * @return the material itself allowing "fluent" like uniform updates
  64281. */
  64282. ShaderMaterial.prototype.setColor3 = function (name, value) {
  64283. this._checkUniform(name);
  64284. this._colors3[name] = value;
  64285. return this;
  64286. };
  64287. /**
  64288. * Set a vec3 array in the shader from a Color3 array.
  64289. * @param name Define the name of the uniform as defined in the shader
  64290. * @param value Define the value to give to the uniform
  64291. * @return the material itself allowing "fluent" like uniform updates
  64292. */
  64293. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  64294. this._checkUniform(name);
  64295. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  64296. color.toArray(arr, arr.length);
  64297. return arr;
  64298. }, []);
  64299. return this;
  64300. };
  64301. /**
  64302. * Set a vec4 in the shader from a Color4.
  64303. * @param name Define the name of the uniform as defined in the shader
  64304. * @param value Define the value to give to the uniform
  64305. * @return the material itself allowing "fluent" like uniform updates
  64306. */
  64307. ShaderMaterial.prototype.setColor4 = function (name, value) {
  64308. this._checkUniform(name);
  64309. this._colors4[name] = value;
  64310. return this;
  64311. };
  64312. /**
  64313. * Set a vec2 in the shader from a Vector2.
  64314. * @param name Define the name of the uniform as defined in the shader
  64315. * @param value Define the value to give to the uniform
  64316. * @return the material itself allowing "fluent" like uniform updates
  64317. */
  64318. ShaderMaterial.prototype.setVector2 = function (name, value) {
  64319. this._checkUniform(name);
  64320. this._vectors2[name] = value;
  64321. return this;
  64322. };
  64323. /**
  64324. * Set a vec3 in the shader from a Vector3.
  64325. * @param name Define the name of the uniform as defined in the shader
  64326. * @param value Define the value to give to the uniform
  64327. * @return the material itself allowing "fluent" like uniform updates
  64328. */
  64329. ShaderMaterial.prototype.setVector3 = function (name, value) {
  64330. this._checkUniform(name);
  64331. this._vectors3[name] = value;
  64332. return this;
  64333. };
  64334. /**
  64335. * Set a vec4 in the shader from a Vector4.
  64336. * @param name Define the name of the uniform as defined in the shader
  64337. * @param value Define the value to give to the uniform
  64338. * @return the material itself allowing "fluent" like uniform updates
  64339. */
  64340. ShaderMaterial.prototype.setVector4 = function (name, value) {
  64341. this._checkUniform(name);
  64342. this._vectors4[name] = value;
  64343. return this;
  64344. };
  64345. /**
  64346. * Set a mat4 in the shader from a Matrix.
  64347. * @param name Define the name of the uniform as defined in the shader
  64348. * @param value Define the value to give to the uniform
  64349. * @return the material itself allowing "fluent" like uniform updates
  64350. */
  64351. ShaderMaterial.prototype.setMatrix = function (name, value) {
  64352. this._checkUniform(name);
  64353. this._matrices[name] = value;
  64354. return this;
  64355. };
  64356. /**
  64357. * Set a mat3 in the shader from a Float32Array.
  64358. * @param name Define the name of the uniform as defined in the shader
  64359. * @param value Define the value to give to the uniform
  64360. * @return the material itself allowing "fluent" like uniform updates
  64361. */
  64362. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  64363. this._checkUniform(name);
  64364. this._matrices3x3[name] = value;
  64365. return this;
  64366. };
  64367. /**
  64368. * Set a mat2 in the shader from a Float32Array.
  64369. * @param name Define the name of the uniform as defined in the shader
  64370. * @param value Define the value to give to the uniform
  64371. * @return the material itself allowing "fluent" like uniform updates
  64372. */
  64373. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  64374. this._checkUniform(name);
  64375. this._matrices2x2[name] = value;
  64376. return this;
  64377. };
  64378. /**
  64379. * Set a vec2 array in the shader from a number array.
  64380. * @param name Define the name of the uniform as defined in the shader
  64381. * @param value Define the value to give to the uniform
  64382. * @return the material itself allowing "fluent" like uniform updates
  64383. */
  64384. ShaderMaterial.prototype.setArray2 = function (name, value) {
  64385. this._checkUniform(name);
  64386. this._vectors2Arrays[name] = value;
  64387. return this;
  64388. };
  64389. /**
  64390. * Set a vec3 array in the shader from a number array.
  64391. * @param name Define the name of the uniform as defined in the shader
  64392. * @param value Define the value to give to the uniform
  64393. * @return the material itself allowing "fluent" like uniform updates
  64394. */
  64395. ShaderMaterial.prototype.setArray3 = function (name, value) {
  64396. this._checkUniform(name);
  64397. this._vectors3Arrays[name] = value;
  64398. return this;
  64399. };
  64400. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  64401. if (!mesh) {
  64402. return true;
  64403. }
  64404. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  64405. return false;
  64406. }
  64407. return false;
  64408. };
  64409. /**
  64410. * Checks if the material is ready to render the requested mesh
  64411. * @param mesh Define the mesh to render
  64412. * @param useInstances Define whether or not the material is used with instances
  64413. * @returns true if ready, otherwise false
  64414. */
  64415. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  64416. var scene = this.getScene();
  64417. var engine = scene.getEngine();
  64418. if (!this.checkReadyOnEveryCall) {
  64419. if (this._renderId === scene.getRenderId()) {
  64420. if (this._checkCache(scene, mesh, useInstances)) {
  64421. return true;
  64422. }
  64423. }
  64424. }
  64425. // Instances
  64426. var defines = [];
  64427. var attribs = [];
  64428. var fallbacks = new BABYLON.EffectFallbacks();
  64429. for (var index = 0; index < this._options.defines.length; index++) {
  64430. defines.push(this._options.defines[index]);
  64431. }
  64432. for (var index = 0; index < this._options.attributes.length; index++) {
  64433. attribs.push(this._options.attributes[index]);
  64434. }
  64435. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  64436. attribs.push(BABYLON.VertexBuffer.ColorKind);
  64437. defines.push("#define VERTEXCOLOR");
  64438. }
  64439. if (useInstances) {
  64440. defines.push("#define INSTANCES");
  64441. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  64442. }
  64443. // Bones
  64444. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  64445. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  64446. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  64447. if (mesh.numBoneInfluencers > 4) {
  64448. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  64449. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  64450. }
  64451. var skeleton = mesh.skeleton;
  64452. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  64453. fallbacks.addCPUSkinningFallback(0, mesh);
  64454. if (skeleton.isUsingTextureForMatrices) {
  64455. defines.push("#define BONETEXTURE");
  64456. if (this._options.uniforms.indexOf("boneTextureWidth") === -1) {
  64457. this._options.uniforms.push("boneTextureWidth");
  64458. }
  64459. if (this._options.samplers.indexOf("boneSampler") === -1) {
  64460. this._options.samplers.push("boneSampler");
  64461. }
  64462. }
  64463. else {
  64464. defines.push("#define BonesPerMesh " + (skeleton.bones.length + 1));
  64465. if (this._options.uniforms.indexOf("mBones") === -1) {
  64466. this._options.uniforms.push("mBones");
  64467. }
  64468. }
  64469. }
  64470. else {
  64471. defines.push("#define NUM_BONE_INFLUENCERS 0");
  64472. }
  64473. // Textures
  64474. for (var name in this._textures) {
  64475. if (!this._textures[name].isReady()) {
  64476. return false;
  64477. }
  64478. }
  64479. // Alpha test
  64480. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  64481. defines.push("#define ALPHATEST");
  64482. }
  64483. var previousEffect = this._effect;
  64484. var join = defines.join("\n");
  64485. this._effect = engine.createEffect(this._shaderPath, {
  64486. attributes: attribs,
  64487. uniformsNames: this._options.uniforms,
  64488. uniformBuffersNames: this._options.uniformBuffers,
  64489. samplers: this._options.samplers,
  64490. defines: join,
  64491. fallbacks: fallbacks,
  64492. onCompiled: this.onCompiled,
  64493. onError: this.onError
  64494. }, engine);
  64495. if (!this._effect.isReady()) {
  64496. return false;
  64497. }
  64498. if (previousEffect !== this._effect) {
  64499. scene.resetCachedMaterial();
  64500. }
  64501. this._renderId = scene.getRenderId();
  64502. return true;
  64503. };
  64504. /**
  64505. * Binds the world matrix to the material
  64506. * @param world defines the world transformation matrix
  64507. */
  64508. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  64509. var scene = this.getScene();
  64510. if (!this._effect) {
  64511. return;
  64512. }
  64513. if (this._options.uniforms.indexOf("world") !== -1) {
  64514. this._effect.setMatrix("world", world);
  64515. }
  64516. if (this._options.uniforms.indexOf("worldView") !== -1) {
  64517. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  64518. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  64519. }
  64520. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  64521. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  64522. }
  64523. };
  64524. /**
  64525. * Binds the material to the mesh
  64526. * @param world defines the world transformation matrix
  64527. * @param mesh defines the mesh to bind the material to
  64528. */
  64529. ShaderMaterial.prototype.bind = function (world, mesh) {
  64530. // Std values
  64531. this.bindOnlyWorldMatrix(world);
  64532. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  64533. if (this._options.uniforms.indexOf("view") !== -1) {
  64534. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  64535. }
  64536. if (this._options.uniforms.indexOf("projection") !== -1) {
  64537. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  64538. }
  64539. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  64540. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  64541. }
  64542. // Bones
  64543. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  64544. var name;
  64545. // Texture
  64546. for (name in this._textures) {
  64547. this._effect.setTexture(name, this._textures[name]);
  64548. }
  64549. // Texture arrays
  64550. for (name in this._textureArrays) {
  64551. this._effect.setTextureArray(name, this._textureArrays[name]);
  64552. }
  64553. // Int
  64554. for (name in this._ints) {
  64555. this._effect.setInt(name, this._ints[name]);
  64556. }
  64557. // Float
  64558. for (name in this._floats) {
  64559. this._effect.setFloat(name, this._floats[name]);
  64560. }
  64561. // Floats
  64562. for (name in this._floatsArrays) {
  64563. this._effect.setArray(name, this._floatsArrays[name]);
  64564. }
  64565. // Color3
  64566. for (name in this._colors3) {
  64567. this._effect.setColor3(name, this._colors3[name]);
  64568. }
  64569. for (name in this._colors3Arrays) {
  64570. this._effect.setArray3(name, this._colors3Arrays[name]);
  64571. }
  64572. // Color4
  64573. for (name in this._colors4) {
  64574. var color = this._colors4[name];
  64575. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  64576. }
  64577. // Vector2
  64578. for (name in this._vectors2) {
  64579. this._effect.setVector2(name, this._vectors2[name]);
  64580. }
  64581. // Vector3
  64582. for (name in this._vectors3) {
  64583. this._effect.setVector3(name, this._vectors3[name]);
  64584. }
  64585. // Vector4
  64586. for (name in this._vectors4) {
  64587. this._effect.setVector4(name, this._vectors4[name]);
  64588. }
  64589. // Matrix
  64590. for (name in this._matrices) {
  64591. this._effect.setMatrix(name, this._matrices[name]);
  64592. }
  64593. // Matrix 3x3
  64594. for (name in this._matrices3x3) {
  64595. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  64596. }
  64597. // Matrix 2x2
  64598. for (name in this._matrices2x2) {
  64599. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  64600. }
  64601. // Vector2Array
  64602. for (name in this._vectors2Arrays) {
  64603. this._effect.setArray2(name, this._vectors2Arrays[name]);
  64604. }
  64605. // Vector3Array
  64606. for (name in this._vectors3Arrays) {
  64607. this._effect.setArray3(name, this._vectors3Arrays[name]);
  64608. }
  64609. }
  64610. this._afterBind(mesh);
  64611. };
  64612. /**
  64613. * Gets the active textures from the material
  64614. * @returns an array of textures
  64615. */
  64616. ShaderMaterial.prototype.getActiveTextures = function () {
  64617. var activeTextures = _super.prototype.getActiveTextures.call(this);
  64618. for (var name in this._textures) {
  64619. activeTextures.push(this._textures[name]);
  64620. }
  64621. for (var name in this._textureArrays) {
  64622. var array = this._textureArrays[name];
  64623. for (var index = 0; index < array.length; index++) {
  64624. activeTextures.push(array[index]);
  64625. }
  64626. }
  64627. return activeTextures;
  64628. };
  64629. /**
  64630. * Specifies if the material uses a texture
  64631. * @param texture defines the texture to check against the material
  64632. * @returns a boolean specifying if the material uses the texture
  64633. */
  64634. ShaderMaterial.prototype.hasTexture = function (texture) {
  64635. if (_super.prototype.hasTexture.call(this, texture)) {
  64636. return true;
  64637. }
  64638. for (var name in this._textures) {
  64639. if (this._textures[name] === texture) {
  64640. return true;
  64641. }
  64642. }
  64643. for (var name in this._textureArrays) {
  64644. var array = this._textureArrays[name];
  64645. for (var index = 0; index < array.length; index++) {
  64646. if (array[index] === texture) {
  64647. return true;
  64648. }
  64649. }
  64650. }
  64651. return false;
  64652. };
  64653. /**
  64654. * Makes a duplicate of the material, and gives it a new name
  64655. * @param name defines the new name for the duplicated material
  64656. * @returns the cloned material
  64657. */
  64658. ShaderMaterial.prototype.clone = function (name) {
  64659. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  64660. return newShaderMaterial;
  64661. };
  64662. /**
  64663. * Disposes the material
  64664. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  64665. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  64666. * @param notBoundToMesh specifies if the material that is being disposed is known to be not bound to any mesh
  64667. */
  64668. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures, notBoundToMesh) {
  64669. if (forceDisposeTextures) {
  64670. var name;
  64671. for (name in this._textures) {
  64672. this._textures[name].dispose();
  64673. }
  64674. for (name in this._textureArrays) {
  64675. var array = this._textureArrays[name];
  64676. for (var index = 0; index < array.length; index++) {
  64677. array[index].dispose();
  64678. }
  64679. }
  64680. }
  64681. this._textures = {};
  64682. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures, notBoundToMesh);
  64683. };
  64684. /**
  64685. * Serializes this material in a JSON representation
  64686. * @returns the serialized material object
  64687. */
  64688. ShaderMaterial.prototype.serialize = function () {
  64689. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  64690. serializationObject.customType = "BABYLON.ShaderMaterial";
  64691. serializationObject.options = this._options;
  64692. serializationObject.shaderPath = this._shaderPath;
  64693. var name;
  64694. // Texture
  64695. serializationObject.textures = {};
  64696. for (name in this._textures) {
  64697. serializationObject.textures[name] = this._textures[name].serialize();
  64698. }
  64699. // Texture arrays
  64700. serializationObject.textureArrays = {};
  64701. for (name in this._textureArrays) {
  64702. serializationObject.textureArrays[name] = [];
  64703. var array = this._textureArrays[name];
  64704. for (var index = 0; index < array.length; index++) {
  64705. serializationObject.textureArrays[name].push(array[index].serialize());
  64706. }
  64707. }
  64708. // Float
  64709. serializationObject.floats = {};
  64710. for (name in this._floats) {
  64711. serializationObject.floats[name] = this._floats[name];
  64712. }
  64713. // Float s
  64714. serializationObject.FloatArrays = {};
  64715. for (name in this._floatsArrays) {
  64716. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  64717. }
  64718. // Color3
  64719. serializationObject.colors3 = {};
  64720. for (name in this._colors3) {
  64721. serializationObject.colors3[name] = this._colors3[name].asArray();
  64722. }
  64723. // Color3 array
  64724. serializationObject.colors3Arrays = {};
  64725. for (name in this._colors3Arrays) {
  64726. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  64727. }
  64728. // Color4
  64729. serializationObject.colors4 = {};
  64730. for (name in this._colors4) {
  64731. serializationObject.colors4[name] = this._colors4[name].asArray();
  64732. }
  64733. // Vector2
  64734. serializationObject.vectors2 = {};
  64735. for (name in this._vectors2) {
  64736. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  64737. }
  64738. // Vector3
  64739. serializationObject.vectors3 = {};
  64740. for (name in this._vectors3) {
  64741. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  64742. }
  64743. // Vector4
  64744. serializationObject.vectors4 = {};
  64745. for (name in this._vectors4) {
  64746. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  64747. }
  64748. // Matrix
  64749. serializationObject.matrices = {};
  64750. for (name in this._matrices) {
  64751. serializationObject.matrices[name] = this._matrices[name].asArray();
  64752. }
  64753. // Matrix 3x3
  64754. serializationObject.matrices3x3 = {};
  64755. for (name in this._matrices3x3) {
  64756. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  64757. }
  64758. // Matrix 2x2
  64759. serializationObject.matrices2x2 = {};
  64760. for (name in this._matrices2x2) {
  64761. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  64762. }
  64763. // Vector2Array
  64764. serializationObject.vectors2Arrays = {};
  64765. for (name in this._vectors2Arrays) {
  64766. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  64767. }
  64768. // Vector3Array
  64769. serializationObject.vectors3Arrays = {};
  64770. for (name in this._vectors3Arrays) {
  64771. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  64772. }
  64773. return serializationObject;
  64774. };
  64775. /**
  64776. * Creates a shader material from parsed shader material data
  64777. * @param source defines the JSON represnetation of the material
  64778. * @param scene defines the hosting scene
  64779. * @param rootUrl defines the root URL to use to load textures and relative dependencies
  64780. * @returns a new material
  64781. */
  64782. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  64783. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  64784. var name;
  64785. // Texture
  64786. for (name in source.textures) {
  64787. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  64788. }
  64789. // Texture arrays
  64790. for (name in source.textureArrays) {
  64791. var array = source.textureArrays[name];
  64792. var textureArray = new Array();
  64793. for (var index = 0; index < array.length; index++) {
  64794. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  64795. }
  64796. material.setTextureArray(name, textureArray);
  64797. }
  64798. // Float
  64799. for (name in source.floats) {
  64800. material.setFloat(name, source.floats[name]);
  64801. }
  64802. // Float s
  64803. for (name in source.floatsArrays) {
  64804. material.setFloats(name, source.floatsArrays[name]);
  64805. }
  64806. // Color3
  64807. for (name in source.colors3) {
  64808. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  64809. }
  64810. // Color3 arrays
  64811. for (name in source.colors3Arrays) {
  64812. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  64813. if (i % 3 === 0) {
  64814. arr.push([num]);
  64815. }
  64816. else {
  64817. arr[arr.length - 1].push(num);
  64818. }
  64819. return arr;
  64820. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  64821. material.setColor3Array(name, colors);
  64822. }
  64823. // Color4
  64824. for (name in source.colors4) {
  64825. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  64826. }
  64827. // Vector2
  64828. for (name in source.vectors2) {
  64829. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  64830. }
  64831. // Vector3
  64832. for (name in source.vectors3) {
  64833. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  64834. }
  64835. // Vector4
  64836. for (name in source.vectors4) {
  64837. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  64838. }
  64839. // Matrix
  64840. for (name in source.matrices) {
  64841. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  64842. }
  64843. // Matrix 3x3
  64844. for (name in source.matrices3x3) {
  64845. material.setMatrix3x3(name, source.matrices3x3[name]);
  64846. }
  64847. // Matrix 2x2
  64848. for (name in source.matrices2x2) {
  64849. material.setMatrix2x2(name, source.matrices2x2[name]);
  64850. }
  64851. // Vector2Array
  64852. for (name in source.vectors2Arrays) {
  64853. material.setArray2(name, source.vectors2Arrays[name]);
  64854. }
  64855. // Vector3Array
  64856. for (name in source.vectors3Arrays) {
  64857. material.setArray3(name, source.vectors3Arrays[name]);
  64858. }
  64859. return material;
  64860. };
  64861. return ShaderMaterial;
  64862. }(BABYLON.Material));
  64863. BABYLON.ShaderMaterial = ShaderMaterial;
  64864. })(BABYLON || (BABYLON = {}));
  64865. //# sourceMappingURL=babylon.shaderMaterial.js.map
  64866. var BABYLON;
  64867. (function (BABYLON) {
  64868. /**
  64869. * Mesh representing the gorund
  64870. */
  64871. var GroundMesh = /** @class */ (function (_super) {
  64872. __extends(GroundMesh, _super);
  64873. function GroundMesh(name, scene) {
  64874. var _this = _super.call(this, name, scene) || this;
  64875. /** If octree should be generated */
  64876. _this.generateOctree = false;
  64877. return _this;
  64878. }
  64879. /**
  64880. * "GroundMesh"
  64881. * @returns "GroundMesh"
  64882. */
  64883. GroundMesh.prototype.getClassName = function () {
  64884. return "GroundMesh";
  64885. };
  64886. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  64887. /**
  64888. * The minimum of x and y subdivisions
  64889. */
  64890. get: function () {
  64891. return Math.min(this._subdivisionsX, this._subdivisionsY);
  64892. },
  64893. enumerable: true,
  64894. configurable: true
  64895. });
  64896. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  64897. /**
  64898. * X subdivisions
  64899. */
  64900. get: function () {
  64901. return this._subdivisionsX;
  64902. },
  64903. enumerable: true,
  64904. configurable: true
  64905. });
  64906. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  64907. /**
  64908. * Y subdivisions
  64909. */
  64910. get: function () {
  64911. return this._subdivisionsY;
  64912. },
  64913. enumerable: true,
  64914. configurable: true
  64915. });
  64916. /**
  64917. * This function will update an octree to help to select the right submeshes for rendering, picking and collision computations.
  64918. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  64919. * @param chunksCount the number of subdivisions for x and y
  64920. * @param octreeBlocksSize (Default: 32)
  64921. */
  64922. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  64923. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  64924. this._subdivisionsX = chunksCount;
  64925. this._subdivisionsY = chunksCount;
  64926. this.subdivide(chunksCount);
  64927. // Call the octree system optimization if it is defined.
  64928. var thisAsAny = this;
  64929. if (thisAsAny.createOrUpdateSubmeshesOctree) {
  64930. thisAsAny.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  64931. }
  64932. };
  64933. /**
  64934. * Returns a height (y) value in the Worl system :
  64935. * the ground altitude at the coordinates (x, z) expressed in the World system.
  64936. * @param x x coordinate
  64937. * @param z z coordinate
  64938. * @returns the ground y position if (x, z) are outside the ground surface.
  64939. */
  64940. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  64941. var world = this.getWorldMatrix();
  64942. var invMat = BABYLON.Tmp.Matrix[5];
  64943. world.invertToRef(invMat);
  64944. var tmpVect = BABYLON.Tmp.Vector3[8];
  64945. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  64946. x = tmpVect.x;
  64947. z = tmpVect.z;
  64948. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  64949. return this.position.y;
  64950. }
  64951. if (!this._heightQuads || this._heightQuads.length == 0) {
  64952. this._initHeightQuads();
  64953. this._computeHeightQuads();
  64954. }
  64955. var facet = this._getFacetAt(x, z);
  64956. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  64957. // return y in the World system
  64958. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  64959. return tmpVect.y;
  64960. };
  64961. /**
  64962. * Returns a normalized vector (Vector3) orthogonal to the ground
  64963. * at the ground coordinates (x, z) expressed in the World system.
  64964. * @param x x coordinate
  64965. * @param z z coordinate
  64966. * @returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  64967. */
  64968. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  64969. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  64970. this.getNormalAtCoordinatesToRef(x, z, normal);
  64971. return normal;
  64972. };
  64973. /**
  64974. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  64975. * at the ground coordinates (x, z) expressed in the World system.
  64976. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  64977. * @param x x coordinate
  64978. * @param z z coordinate
  64979. * @param ref vector to store the result
  64980. * @returns the GroundMesh.
  64981. */
  64982. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  64983. var world = this.getWorldMatrix();
  64984. var tmpMat = BABYLON.Tmp.Matrix[5];
  64985. world.invertToRef(tmpMat);
  64986. var tmpVect = BABYLON.Tmp.Vector3[8];
  64987. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  64988. x = tmpVect.x;
  64989. z = tmpVect.z;
  64990. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  64991. return this;
  64992. }
  64993. if (!this._heightQuads || this._heightQuads.length == 0) {
  64994. this._initHeightQuads();
  64995. this._computeHeightQuads();
  64996. }
  64997. var facet = this._getFacetAt(x, z);
  64998. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  64999. return this;
  65000. };
  65001. /**
  65002. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  65003. * if the ground has been updated.
  65004. * This can be used in the render loop.
  65005. * @returns the GroundMesh.
  65006. */
  65007. GroundMesh.prototype.updateCoordinateHeights = function () {
  65008. if (!this._heightQuads || this._heightQuads.length == 0) {
  65009. this._initHeightQuads();
  65010. }
  65011. this._computeHeightQuads();
  65012. return this;
  65013. };
  65014. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  65015. GroundMesh.prototype._getFacetAt = function (x, z) {
  65016. // retrieve col and row from x, z coordinates in the ground local system
  65017. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  65018. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  65019. var quad = this._heightQuads[row * this._subdivisionsX + col];
  65020. var facet;
  65021. if (z < quad.slope.x * x + quad.slope.y) {
  65022. facet = quad.facet1;
  65023. }
  65024. else {
  65025. facet = quad.facet2;
  65026. }
  65027. return facet;
  65028. };
  65029. // Creates and populates the heightMap array with "facet" elements :
  65030. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  65031. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  65032. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  65033. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  65034. // Returns the GroundMesh.
  65035. GroundMesh.prototype._initHeightQuads = function () {
  65036. var subdivisionsX = this._subdivisionsX;
  65037. var subdivisionsY = this._subdivisionsY;
  65038. this._heightQuads = new Array();
  65039. for (var row = 0; row < subdivisionsY; row++) {
  65040. for (var col = 0; col < subdivisionsX; col++) {
  65041. 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) };
  65042. this._heightQuads[row * subdivisionsX + col] = quad;
  65043. }
  65044. }
  65045. return this;
  65046. };
  65047. // Compute each quad element values and update the the heightMap array :
  65048. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  65049. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  65050. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  65051. // Returns the GroundMesh.
  65052. GroundMesh.prototype._computeHeightQuads = function () {
  65053. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  65054. if (!positions) {
  65055. return this;
  65056. }
  65057. var v1 = BABYLON.Tmp.Vector3[3];
  65058. var v2 = BABYLON.Tmp.Vector3[2];
  65059. var v3 = BABYLON.Tmp.Vector3[1];
  65060. var v4 = BABYLON.Tmp.Vector3[0];
  65061. var v1v2 = BABYLON.Tmp.Vector3[4];
  65062. var v1v3 = BABYLON.Tmp.Vector3[5];
  65063. var v1v4 = BABYLON.Tmp.Vector3[6];
  65064. var norm1 = BABYLON.Tmp.Vector3[7];
  65065. var norm2 = BABYLON.Tmp.Vector3[8];
  65066. var i = 0;
  65067. var j = 0;
  65068. var k = 0;
  65069. var cd = 0; // 2D slope coefficient : z = cd * x + h
  65070. var h = 0;
  65071. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  65072. var d2 = 0;
  65073. var subdivisionsX = this._subdivisionsX;
  65074. var subdivisionsY = this._subdivisionsY;
  65075. for (var row = 0; row < subdivisionsY; row++) {
  65076. for (var col = 0; col < subdivisionsX; col++) {
  65077. i = col * 3;
  65078. j = row * (subdivisionsX + 1) * 3;
  65079. k = (row + 1) * (subdivisionsX + 1) * 3;
  65080. v1.x = positions[j + i];
  65081. v1.y = positions[j + i + 1];
  65082. v1.z = positions[j + i + 2];
  65083. v2.x = positions[j + i + 3];
  65084. v2.y = positions[j + i + 4];
  65085. v2.z = positions[j + i + 5];
  65086. v3.x = positions[k + i];
  65087. v3.y = positions[k + i + 1];
  65088. v3.z = positions[k + i + 2];
  65089. v4.x = positions[k + i + 3];
  65090. v4.y = positions[k + i + 4];
  65091. v4.z = positions[k + i + 5];
  65092. // 2D slope V1V4
  65093. cd = (v4.z - v1.z) / (v4.x - v1.x);
  65094. h = v1.z - cd * v1.x; // v1 belongs to the slope
  65095. // facet equations :
  65096. // we compute each facet normal vector
  65097. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  65098. // we compute the value d by applying the equation to v1 which belongs to the plane
  65099. // then we store the facet equation in a Vector4
  65100. v2.subtractToRef(v1, v1v2);
  65101. v3.subtractToRef(v1, v1v3);
  65102. v4.subtractToRef(v1, v1v4);
  65103. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  65104. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  65105. norm1.normalize();
  65106. norm2.normalize();
  65107. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  65108. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  65109. var quad = this._heightQuads[row * subdivisionsX + col];
  65110. quad.slope.copyFromFloats(cd, h);
  65111. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  65112. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  65113. }
  65114. }
  65115. return this;
  65116. };
  65117. /**
  65118. * Serializes this ground mesh
  65119. * @param serializationObject object to write serialization to
  65120. */
  65121. GroundMesh.prototype.serialize = function (serializationObject) {
  65122. _super.prototype.serialize.call(this, serializationObject);
  65123. serializationObject.subdivisionsX = this._subdivisionsX;
  65124. serializationObject.subdivisionsY = this._subdivisionsY;
  65125. serializationObject.minX = this._minX;
  65126. serializationObject.maxX = this._maxX;
  65127. serializationObject.minZ = this._minZ;
  65128. serializationObject.maxZ = this._maxZ;
  65129. serializationObject.width = this._width;
  65130. serializationObject.height = this._height;
  65131. };
  65132. /**
  65133. * Parses a serialized ground mesh
  65134. * @param parsedMesh the serialized mesh
  65135. * @param scene the scene to create the ground mesh in
  65136. * @returns the created ground mesh
  65137. */
  65138. GroundMesh.Parse = function (parsedMesh, scene) {
  65139. var result = new GroundMesh(parsedMesh.name, scene);
  65140. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  65141. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  65142. result._minX = parsedMesh.minX;
  65143. result._maxX = parsedMesh.maxX;
  65144. result._minZ = parsedMesh.minZ;
  65145. result._maxZ = parsedMesh.maxZ;
  65146. result._width = parsedMesh.width;
  65147. result._height = parsedMesh.height;
  65148. return result;
  65149. };
  65150. return GroundMesh;
  65151. }(BABYLON.Mesh));
  65152. BABYLON.GroundMesh = GroundMesh;
  65153. })(BABYLON || (BABYLON = {}));
  65154. //# sourceMappingURL=babylon.groundMesh.js.map
  65155. var BABYLON;
  65156. (function (BABYLON) {
  65157. /**
  65158. * Creates an instance based on a source mesh.
  65159. */
  65160. var InstancedMesh = /** @class */ (function (_super) {
  65161. __extends(InstancedMesh, _super);
  65162. function InstancedMesh(name, source) {
  65163. var _this = _super.call(this, name, source.getScene()) || this;
  65164. /** @hidden */
  65165. _this._indexInSourceMeshInstanceArray = -1;
  65166. source.addInstance(_this);
  65167. _this._sourceMesh = source;
  65168. _this.position.copyFrom(source.position);
  65169. _this.rotation.copyFrom(source.rotation);
  65170. _this.scaling.copyFrom(source.scaling);
  65171. if (source.rotationQuaternion) {
  65172. _this.rotationQuaternion = source.rotationQuaternion.clone();
  65173. }
  65174. _this.infiniteDistance = source.infiniteDistance;
  65175. _this.setPivotMatrix(source.getPivotMatrix());
  65176. _this.refreshBoundingInfo();
  65177. _this._syncSubMeshes();
  65178. return _this;
  65179. }
  65180. /**
  65181. * Returns the string "InstancedMesh".
  65182. */
  65183. InstancedMesh.prototype.getClassName = function () {
  65184. return "InstancedMesh";
  65185. };
  65186. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  65187. // Methods
  65188. /**
  65189. * If the source mesh receives shadows
  65190. */
  65191. get: function () {
  65192. return this._sourceMesh.receiveShadows;
  65193. },
  65194. enumerable: true,
  65195. configurable: true
  65196. });
  65197. Object.defineProperty(InstancedMesh.prototype, "material", {
  65198. /**
  65199. * The material of the source mesh
  65200. */
  65201. get: function () {
  65202. return this._sourceMesh.material;
  65203. },
  65204. enumerable: true,
  65205. configurable: true
  65206. });
  65207. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  65208. /**
  65209. * Visibility of the source mesh
  65210. */
  65211. get: function () {
  65212. return this._sourceMesh.visibility;
  65213. },
  65214. enumerable: true,
  65215. configurable: true
  65216. });
  65217. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  65218. /**
  65219. * Skeleton of the source mesh
  65220. */
  65221. get: function () {
  65222. return this._sourceMesh.skeleton;
  65223. },
  65224. enumerable: true,
  65225. configurable: true
  65226. });
  65227. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  65228. /**
  65229. * Rendering ground id of the source mesh
  65230. */
  65231. get: function () {
  65232. return this._sourceMesh.renderingGroupId;
  65233. },
  65234. set: function (value) {
  65235. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  65236. return;
  65237. }
  65238. //no-op with warning
  65239. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  65240. },
  65241. enumerable: true,
  65242. configurable: true
  65243. });
  65244. /**
  65245. * Returns the total number of vertices (integer).
  65246. */
  65247. InstancedMesh.prototype.getTotalVertices = function () {
  65248. return this._sourceMesh.getTotalVertices();
  65249. };
  65250. /**
  65251. * Returns a positive integer : the total number of indices in this mesh geometry.
  65252. * @returns the numner of indices or zero if the mesh has no geometry.
  65253. */
  65254. InstancedMesh.prototype.getTotalIndices = function () {
  65255. return this._sourceMesh.getTotalIndices();
  65256. };
  65257. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  65258. /**
  65259. * The source mesh of the instance
  65260. */
  65261. get: function () {
  65262. return this._sourceMesh;
  65263. },
  65264. enumerable: true,
  65265. configurable: true
  65266. });
  65267. /**
  65268. * Is this node ready to be used/rendered
  65269. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  65270. * @return {boolean} is it ready
  65271. */
  65272. InstancedMesh.prototype.isReady = function (completeCheck) {
  65273. if (completeCheck === void 0) { completeCheck = false; }
  65274. return this._sourceMesh.isReady(completeCheck, true);
  65275. };
  65276. /**
  65277. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  65278. * @param kind kind of verticies to retreive (eg. positons, normals, uvs, etc.)
  65279. * @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.
  65280. * @returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  65281. */
  65282. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  65283. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  65284. };
  65285. /**
  65286. * Sets the vertex data of the mesh geometry for the requested `kind`.
  65287. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  65288. * The `data` are either a numeric array either a Float32Array.
  65289. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  65290. * 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).
  65291. * Note that a new underlying VertexBuffer object is created each call.
  65292. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  65293. *
  65294. * Possible `kind` values :
  65295. * - BABYLON.VertexBuffer.PositionKind
  65296. * - BABYLON.VertexBuffer.UVKind
  65297. * - BABYLON.VertexBuffer.UV2Kind
  65298. * - BABYLON.VertexBuffer.UV3Kind
  65299. * - BABYLON.VertexBuffer.UV4Kind
  65300. * - BABYLON.VertexBuffer.UV5Kind
  65301. * - BABYLON.VertexBuffer.UV6Kind
  65302. * - BABYLON.VertexBuffer.ColorKind
  65303. * - BABYLON.VertexBuffer.MatricesIndicesKind
  65304. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  65305. * - BABYLON.VertexBuffer.MatricesWeightsKind
  65306. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  65307. *
  65308. * Returns the Mesh.
  65309. */
  65310. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  65311. if (this.sourceMesh) {
  65312. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  65313. }
  65314. return this.sourceMesh;
  65315. };
  65316. /**
  65317. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  65318. * If the mesh has no geometry, it is simply returned as it is.
  65319. * The `data` are either a numeric array either a Float32Array.
  65320. * No new underlying VertexBuffer object is created.
  65321. * 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.
  65322. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  65323. *
  65324. * Possible `kind` values :
  65325. * - BABYLON.VertexBuffer.PositionKind
  65326. * - BABYLON.VertexBuffer.UVKind
  65327. * - BABYLON.VertexBuffer.UV2Kind
  65328. * - BABYLON.VertexBuffer.UV3Kind
  65329. * - BABYLON.VertexBuffer.UV4Kind
  65330. * - BABYLON.VertexBuffer.UV5Kind
  65331. * - BABYLON.VertexBuffer.UV6Kind
  65332. * - BABYLON.VertexBuffer.ColorKind
  65333. * - BABYLON.VertexBuffer.MatricesIndicesKind
  65334. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  65335. * - BABYLON.VertexBuffer.MatricesWeightsKind
  65336. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  65337. *
  65338. * Returns the Mesh.
  65339. */
  65340. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  65341. if (this.sourceMesh) {
  65342. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  65343. }
  65344. return this.sourceMesh;
  65345. };
  65346. /**
  65347. * Sets the mesh indices.
  65348. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  65349. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  65350. * This method creates a new index buffer each call.
  65351. * Returns the Mesh.
  65352. */
  65353. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  65354. if (totalVertices === void 0) { totalVertices = null; }
  65355. if (this.sourceMesh) {
  65356. this.sourceMesh.setIndices(indices, totalVertices);
  65357. }
  65358. return this.sourceMesh;
  65359. };
  65360. /**
  65361. * Boolean : True if the mesh owns the requested kind of data.
  65362. */
  65363. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  65364. return this._sourceMesh.isVerticesDataPresent(kind);
  65365. };
  65366. /**
  65367. * Returns an array of indices (IndicesArray).
  65368. */
  65369. InstancedMesh.prototype.getIndices = function () {
  65370. return this._sourceMesh.getIndices();
  65371. };
  65372. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  65373. get: function () {
  65374. return this._sourceMesh._positions;
  65375. },
  65376. enumerable: true,
  65377. configurable: true
  65378. });
  65379. /**
  65380. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  65381. * This means the mesh underlying bounding box and sphere are recomputed.
  65382. * @param applySkeleton defines whether to apply the skeleton before computing the bounding info
  65383. * @returns the current mesh
  65384. */
  65385. InstancedMesh.prototype.refreshBoundingInfo = function (applySkeleton) {
  65386. if (applySkeleton === void 0) { applySkeleton = false; }
  65387. if (this._boundingInfo && this._boundingInfo.isLocked) {
  65388. return this;
  65389. }
  65390. var bias = this._sourceMesh.geometry ? this._sourceMesh.geometry.boundingBias : null;
  65391. this._refreshBoundingInfo(this._sourceMesh._getPositionData(applySkeleton), bias);
  65392. return this;
  65393. };
  65394. /** @hidden */
  65395. InstancedMesh.prototype._preActivate = function () {
  65396. if (this._currentLOD) {
  65397. this._currentLOD._preActivate();
  65398. }
  65399. return this;
  65400. };
  65401. /** @hidden */
  65402. InstancedMesh.prototype._activate = function (renderId) {
  65403. if (this._currentLOD) {
  65404. this._currentLOD._registerInstanceForRenderId(this, renderId);
  65405. }
  65406. return this;
  65407. };
  65408. /**
  65409. * Returns the current associated LOD AbstractMesh.
  65410. */
  65411. InstancedMesh.prototype.getLOD = function (camera) {
  65412. if (!camera) {
  65413. return this;
  65414. }
  65415. var boundingInfo = this.getBoundingInfo();
  65416. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  65417. if (this._currentLOD === this.sourceMesh) {
  65418. return this;
  65419. }
  65420. return this._currentLOD;
  65421. };
  65422. /** @hidden */
  65423. InstancedMesh.prototype._syncSubMeshes = function () {
  65424. this.releaseSubMeshes();
  65425. if (this._sourceMesh.subMeshes) {
  65426. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  65427. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  65428. }
  65429. }
  65430. return this;
  65431. };
  65432. /** @hidden */
  65433. InstancedMesh.prototype._generatePointsArray = function () {
  65434. return this._sourceMesh._generatePointsArray();
  65435. };
  65436. /**
  65437. * Creates a new InstancedMesh from the current mesh.
  65438. * - name (string) : the cloned mesh name
  65439. * - newParent (optional Node) : the optional Node to parent the clone to.
  65440. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  65441. *
  65442. * Returns the clone.
  65443. */
  65444. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  65445. var result = this._sourceMesh.createInstance(name);
  65446. // Deep copy
  65447. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  65448. // Bounding info
  65449. this.refreshBoundingInfo();
  65450. // Parent
  65451. if (newParent) {
  65452. result.parent = newParent;
  65453. }
  65454. if (!doNotCloneChildren) {
  65455. // Children
  65456. for (var index = 0; index < this.getScene().meshes.length; index++) {
  65457. var mesh = this.getScene().meshes[index];
  65458. if (mesh.parent === this) {
  65459. mesh.clone(mesh.name, result);
  65460. }
  65461. }
  65462. }
  65463. result.computeWorldMatrix(true);
  65464. return result;
  65465. };
  65466. /**
  65467. * Disposes the InstancedMesh.
  65468. * Returns nothing.
  65469. */
  65470. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  65471. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  65472. // Remove from mesh
  65473. this._sourceMesh.removeInstance(this);
  65474. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  65475. };
  65476. return InstancedMesh;
  65477. }(BABYLON.AbstractMesh));
  65478. BABYLON.InstancedMesh = InstancedMesh;
  65479. })(BABYLON || (BABYLON = {}));
  65480. //# sourceMappingURL=babylon.instancedMesh.js.map
  65481. var BABYLON;
  65482. (function (BABYLON) {
  65483. /**
  65484. * Line mesh
  65485. * @see https://doc.babylonjs.com/babylon101/parametric_shapes
  65486. */
  65487. var LinesMesh = /** @class */ (function (_super) {
  65488. __extends(LinesMesh, _super);
  65489. /**
  65490. * Creates a new LinesMesh
  65491. * @param name defines the name
  65492. * @param scene defines the hosting scene
  65493. * @param parent defines the parent mesh if any
  65494. * @param source defines the optional source LinesMesh used to clone data from
  65495. * @param doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  65496. * When false, achieved by calling a clone(), also passing False.
  65497. * This will make creation of children, recursive.
  65498. * @param useVertexColor defines if this LinesMesh supports vertex color
  65499. * @param useVertexAlpha defines if this LinesMesh supports vertex alpha
  65500. */
  65501. function LinesMesh(name, scene, parent, source, doNotCloneChildren,
  65502. /**
  65503. * If vertex color should be applied to the mesh
  65504. */
  65505. useVertexColor,
  65506. /**
  65507. * If vertex alpha should be applied to the mesh
  65508. */
  65509. useVertexAlpha) {
  65510. if (scene === void 0) { scene = null; }
  65511. if (parent === void 0) { parent = null; }
  65512. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  65513. _this.useVertexColor = useVertexColor;
  65514. _this.useVertexAlpha = useVertexAlpha;
  65515. /**
  65516. * Color of the line (Default: White)
  65517. */
  65518. _this.color = new BABYLON.Color3(1, 1, 1);
  65519. /**
  65520. * Alpha of the line (Default: 1)
  65521. */
  65522. _this.alpha = 1;
  65523. if (source) {
  65524. _this.color = source.color.clone();
  65525. _this.alpha = source.alpha;
  65526. _this.useVertexColor = source.useVertexColor;
  65527. _this.useVertexAlpha = source.useVertexAlpha;
  65528. }
  65529. _this.intersectionThreshold = 0.1;
  65530. var defines = [];
  65531. var options = {
  65532. attributes: [BABYLON.VertexBuffer.PositionKind, "world0", "world1", "world2", "world3"],
  65533. uniforms: ["world", "viewProjection"],
  65534. needAlphaBlending: true,
  65535. defines: defines
  65536. };
  65537. if (useVertexAlpha === false) {
  65538. options.needAlphaBlending = false;
  65539. }
  65540. if (!useVertexColor) {
  65541. options.uniforms.push("color");
  65542. }
  65543. else {
  65544. options.defines.push("#define VERTEXCOLOR");
  65545. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  65546. }
  65547. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  65548. return _this;
  65549. }
  65550. /**
  65551. * Returns the string "LineMesh"
  65552. */
  65553. LinesMesh.prototype.getClassName = function () {
  65554. return "LinesMesh";
  65555. };
  65556. Object.defineProperty(LinesMesh.prototype, "material", {
  65557. /**
  65558. * @hidden
  65559. */
  65560. get: function () {
  65561. return this._colorShader;
  65562. },
  65563. /**
  65564. * @hidden
  65565. */
  65566. set: function (value) {
  65567. // Do nothing
  65568. },
  65569. enumerable: true,
  65570. configurable: true
  65571. });
  65572. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  65573. /**
  65574. * @hidden
  65575. */
  65576. get: function () {
  65577. return false;
  65578. },
  65579. enumerable: true,
  65580. configurable: true
  65581. });
  65582. /** @hidden */
  65583. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  65584. if (!this._geometry) {
  65585. return this;
  65586. }
  65587. // VBOs
  65588. this._geometry._bind(this._colorShader.getEffect());
  65589. // Color
  65590. if (!this.useVertexColor) {
  65591. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  65592. }
  65593. return this;
  65594. };
  65595. /** @hidden */
  65596. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  65597. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  65598. return this;
  65599. }
  65600. var engine = this.getScene().getEngine();
  65601. // Draw order
  65602. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  65603. return this;
  65604. };
  65605. /**
  65606. * Disposes of the line mesh
  65607. * @param doNotRecurse If children should be disposed
  65608. */
  65609. LinesMesh.prototype.dispose = function (doNotRecurse) {
  65610. this._colorShader.dispose(false, false, true);
  65611. _super.prototype.dispose.call(this, doNotRecurse);
  65612. };
  65613. /**
  65614. * Returns a new LineMesh object cloned from the current one.
  65615. */
  65616. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  65617. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  65618. };
  65619. /**
  65620. * Creates a new InstancedLinesMesh object from the mesh model.
  65621. * @see http://doc.babylonjs.com/how_to/how_to_use_instances
  65622. * @param name defines the name of the new instance
  65623. * @returns a new InstancedLinesMesh
  65624. */
  65625. LinesMesh.prototype.createInstance = function (name) {
  65626. return new InstancedLinesMesh(name, this);
  65627. };
  65628. return LinesMesh;
  65629. }(BABYLON.Mesh));
  65630. BABYLON.LinesMesh = LinesMesh;
  65631. /**
  65632. * Creates an instance based on a source LinesMesh
  65633. */
  65634. var InstancedLinesMesh = /** @class */ (function (_super) {
  65635. __extends(InstancedLinesMesh, _super);
  65636. function InstancedLinesMesh(name, source) {
  65637. var _this = _super.call(this, name, source) || this;
  65638. _this.intersectionThreshold = source.intersectionThreshold;
  65639. return _this;
  65640. }
  65641. /**
  65642. * Returns the string "InstancedLinesMesh".
  65643. */
  65644. InstancedLinesMesh.prototype.getClassName = function () {
  65645. return "InstancedLinesMesh";
  65646. };
  65647. return InstancedLinesMesh;
  65648. }(BABYLON.InstancedMesh));
  65649. BABYLON.InstancedLinesMesh = InstancedLinesMesh;
  65650. })(BABYLON || (BABYLON = {}));
  65651. //# sourceMappingURL=babylon.linesMesh.js.map
  65652. var BABYLON;
  65653. (function (BABYLON) {
  65654. /**
  65655. * This class implement a typical dictionary using a string as key and the generic type T as value.
  65656. * The underlying implementation relies on an associative array to ensure the best performances.
  65657. * The value can be anything including 'null' but except 'undefined'
  65658. */
  65659. var StringDictionary = /** @class */ (function () {
  65660. function StringDictionary() {
  65661. this._count = 0;
  65662. this._data = {};
  65663. }
  65664. /**
  65665. * This will clear this dictionary and copy the content from the 'source' one.
  65666. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  65667. * @param source the dictionary to take the content from and copy to this dictionary
  65668. */
  65669. StringDictionary.prototype.copyFrom = function (source) {
  65670. var _this = this;
  65671. this.clear();
  65672. source.forEach(function (t, v) { return _this.add(t, v); });
  65673. };
  65674. /**
  65675. * Get a value based from its key
  65676. * @param key the given key to get the matching value from
  65677. * @return the value if found, otherwise undefined is returned
  65678. */
  65679. StringDictionary.prototype.get = function (key) {
  65680. var val = this._data[key];
  65681. if (val !== undefined) {
  65682. return val;
  65683. }
  65684. return undefined;
  65685. };
  65686. /**
  65687. * Get a value from its key or add it if it doesn't exist.
  65688. * This method will ensure you that a given key/data will be present in the dictionary.
  65689. * @param key the given key to get the matching value from
  65690. * @param factory the factory that will create the value if the key is not present in the dictionary.
  65691. * The factory will only be invoked if there's no data for the given key.
  65692. * @return the value corresponding to the key.
  65693. */
  65694. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  65695. var val = this.get(key);
  65696. if (val !== undefined) {
  65697. return val;
  65698. }
  65699. val = factory(key);
  65700. if (val) {
  65701. this.add(key, val);
  65702. }
  65703. return val;
  65704. };
  65705. /**
  65706. * Get a value from its key if present in the dictionary otherwise add it
  65707. * @param key the key to get the value from
  65708. * @param val if there's no such key/value pair in the dictionary add it with this value
  65709. * @return the value corresponding to the key
  65710. */
  65711. StringDictionary.prototype.getOrAdd = function (key, val) {
  65712. var curVal = this.get(key);
  65713. if (curVal !== undefined) {
  65714. return curVal;
  65715. }
  65716. this.add(key, val);
  65717. return val;
  65718. };
  65719. /**
  65720. * Check if there's a given key in the dictionary
  65721. * @param key the key to check for
  65722. * @return true if the key is present, false otherwise
  65723. */
  65724. StringDictionary.prototype.contains = function (key) {
  65725. return this._data[key] !== undefined;
  65726. };
  65727. /**
  65728. * Add a new key and its corresponding value
  65729. * @param key the key to add
  65730. * @param value the value corresponding to the key
  65731. * @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
  65732. */
  65733. StringDictionary.prototype.add = function (key, value) {
  65734. if (this._data[key] !== undefined) {
  65735. return false;
  65736. }
  65737. this._data[key] = value;
  65738. ++this._count;
  65739. return true;
  65740. };
  65741. /**
  65742. * Update a specific value associated to a key
  65743. * @param key defines the key to use
  65744. * @param value defines the value to store
  65745. * @returns true if the value was updated (or false if the key was not found)
  65746. */
  65747. StringDictionary.prototype.set = function (key, value) {
  65748. if (this._data[key] === undefined) {
  65749. return false;
  65750. }
  65751. this._data[key] = value;
  65752. return true;
  65753. };
  65754. /**
  65755. * Get the element of the given key and remove it from the dictionary
  65756. * @param key defines the key to search
  65757. * @returns the value associated with the key or null if not found
  65758. */
  65759. StringDictionary.prototype.getAndRemove = function (key) {
  65760. var val = this.get(key);
  65761. if (val !== undefined) {
  65762. delete this._data[key];
  65763. --this._count;
  65764. return val;
  65765. }
  65766. return null;
  65767. };
  65768. /**
  65769. * Remove a key/value from the dictionary.
  65770. * @param key the key to remove
  65771. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  65772. */
  65773. StringDictionary.prototype.remove = function (key) {
  65774. if (this.contains(key)) {
  65775. delete this._data[key];
  65776. --this._count;
  65777. return true;
  65778. }
  65779. return false;
  65780. };
  65781. /**
  65782. * Clear the whole content of the dictionary
  65783. */
  65784. StringDictionary.prototype.clear = function () {
  65785. this._data = {};
  65786. this._count = 0;
  65787. };
  65788. Object.defineProperty(StringDictionary.prototype, "count", {
  65789. /**
  65790. * Gets the current count
  65791. */
  65792. get: function () {
  65793. return this._count;
  65794. },
  65795. enumerable: true,
  65796. configurable: true
  65797. });
  65798. /**
  65799. * Execute a callback on each key/val of the dictionary.
  65800. * Note that you can remove any element in this dictionary in the callback implementation
  65801. * @param callback the callback to execute on a given key/value pair
  65802. */
  65803. StringDictionary.prototype.forEach = function (callback) {
  65804. for (var cur in this._data) {
  65805. var val = this._data[cur];
  65806. callback(cur, val);
  65807. }
  65808. };
  65809. /**
  65810. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  65811. * If the callback returns null or undefined the method will iterate to the next key/value pair
  65812. * Note that you can remove any element in this dictionary in the callback implementation
  65813. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  65814. * @returns the first item
  65815. */
  65816. StringDictionary.prototype.first = function (callback) {
  65817. for (var cur in this._data) {
  65818. var val = this._data[cur];
  65819. var res = callback(cur, val);
  65820. if (res) {
  65821. return res;
  65822. }
  65823. }
  65824. return null;
  65825. };
  65826. return StringDictionary;
  65827. }());
  65828. BABYLON.StringDictionary = StringDictionary;
  65829. })(BABYLON || (BABYLON = {}));
  65830. //# sourceMappingURL=babylon.stringDictionary.js.map
  65831. var BABYLON;
  65832. (function (BABYLON) {
  65833. var Debug;
  65834. (function (Debug) {
  65835. /**
  65836. * Class used to render a debug view of a given skeleton
  65837. * @see http://www.babylonjs-playground.com/#1BZJVJ#8
  65838. */
  65839. var SkeletonViewer = /** @class */ (function () {
  65840. /**
  65841. * Creates a new SkeletonViewer
  65842. * @param skeleton defines the skeleton to render
  65843. * @param mesh defines the mesh attached to the skeleton
  65844. * @param scene defines the hosting scene
  65845. * @param autoUpdateBonesMatrices defines a boolean indicating if bones matrices must be forced to update before rendering (true by default)
  65846. * @param renderingGroupId defines the rendering group id to use with the viewer
  65847. * @param utilityLayerRenderer defines an optional utility layer to render the helper on
  65848. */
  65849. function SkeletonViewer(
  65850. /** defines the skeleton to render */
  65851. skeleton,
  65852. /** defines the mesh attached to the skeleton */
  65853. mesh, scene,
  65854. /** defines a boolean indicating if bones matrices must be forced to update before rendering (true by default) */
  65855. autoUpdateBonesMatrices,
  65856. /** defines the rendering group id to use with the viewer */
  65857. renderingGroupId,
  65858. /** defines an optional utility layer to render the helper on */
  65859. utilityLayerRenderer) {
  65860. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  65861. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  65862. this.skeleton = skeleton;
  65863. this.mesh = mesh;
  65864. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  65865. this.renderingGroupId = renderingGroupId;
  65866. this.utilityLayerRenderer = utilityLayerRenderer;
  65867. /** Gets or sets the color used to render the skeleton */
  65868. this.color = BABYLON.Color3.White();
  65869. this._debugLines = new Array();
  65870. this._isEnabled = false;
  65871. this._scene = scene;
  65872. this.update();
  65873. this._renderFunction = this.update.bind(this);
  65874. }
  65875. Object.defineProperty(SkeletonViewer.prototype, "debugMesh", {
  65876. /**
  65877. * Returns the mesh used to render the bones
  65878. */
  65879. get: function () {
  65880. return this._debugMesh;
  65881. },
  65882. enumerable: true,
  65883. configurable: true
  65884. });
  65885. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  65886. get: function () {
  65887. return this._isEnabled;
  65888. },
  65889. /** Gets or sets a boolean indicating if the viewer is enabled */
  65890. set: function (value) {
  65891. if (this._isEnabled === value) {
  65892. return;
  65893. }
  65894. this._isEnabled = value;
  65895. if (value) {
  65896. this._scene.registerBeforeRender(this._renderFunction);
  65897. }
  65898. else {
  65899. this._scene.unregisterBeforeRender(this._renderFunction);
  65900. }
  65901. },
  65902. enumerable: true,
  65903. configurable: true
  65904. });
  65905. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  65906. if (x === void 0) { x = 0; }
  65907. if (y === void 0) { y = 0; }
  65908. if (z === void 0) { z = 0; }
  65909. var tmat = BABYLON.Tmp.Matrix[0];
  65910. var parentBone = bone.getParent();
  65911. tmat.copyFrom(bone.getLocalMatrix());
  65912. if (x !== 0 || y !== 0 || z !== 0) {
  65913. var tmat2 = BABYLON.Tmp.Matrix[1];
  65914. BABYLON.Matrix.IdentityToRef(tmat2);
  65915. tmat2.setTranslationFromFloats(x, y, z);
  65916. tmat2.multiplyToRef(tmat, tmat);
  65917. }
  65918. if (parentBone) {
  65919. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  65920. }
  65921. tmat.multiplyToRef(meshMat, tmat);
  65922. position.x = tmat.m[12];
  65923. position.y = tmat.m[13];
  65924. position.z = tmat.m[14];
  65925. };
  65926. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  65927. var len = bones.length;
  65928. var meshPos = this.mesh.position;
  65929. for (var i = 0; i < len; i++) {
  65930. var bone = bones[i];
  65931. var points = this._debugLines[i];
  65932. if (!points) {
  65933. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  65934. this._debugLines[i] = points;
  65935. }
  65936. this._getBonePosition(points[0], bone, meshMat);
  65937. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  65938. points[0].subtractInPlace(meshPos);
  65939. points[1].subtractInPlace(meshPos);
  65940. }
  65941. };
  65942. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  65943. var len = bones.length;
  65944. var boneNum = 0;
  65945. var meshPos = this.mesh.position;
  65946. for (var i = len - 1; i >= 0; i--) {
  65947. var childBone = bones[i];
  65948. var parentBone = childBone.getParent();
  65949. if (!parentBone) {
  65950. continue;
  65951. }
  65952. var points = this._debugLines[boneNum];
  65953. if (!points) {
  65954. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  65955. this._debugLines[boneNum] = points;
  65956. }
  65957. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  65958. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  65959. points[0].subtractInPlace(meshPos);
  65960. points[1].subtractInPlace(meshPos);
  65961. boneNum++;
  65962. }
  65963. };
  65964. /** Update the viewer to sync with current skeleton state */
  65965. SkeletonViewer.prototype.update = function () {
  65966. if (this.autoUpdateBonesMatrices) {
  65967. this.skeleton.computeAbsoluteTransforms();
  65968. }
  65969. if (this.skeleton.bones[0].length === undefined) {
  65970. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  65971. }
  65972. else {
  65973. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  65974. }
  65975. var targetScene = this.utilityLayerRenderer ? this.utilityLayerRenderer.utilityLayerScene : this._scene;
  65976. if (!this._debugMesh) {
  65977. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, targetScene);
  65978. this._debugMesh.renderingGroupId = this.renderingGroupId;
  65979. }
  65980. else {
  65981. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, targetScene);
  65982. }
  65983. this._debugMesh.position.copyFrom(this.mesh.position);
  65984. this._debugMesh.color = this.color;
  65985. };
  65986. /** Release associated resources */
  65987. SkeletonViewer.prototype.dispose = function () {
  65988. if (this._debugMesh) {
  65989. this.isEnabled = false;
  65990. this._debugMesh.dispose();
  65991. this._debugMesh = null;
  65992. }
  65993. };
  65994. return SkeletonViewer;
  65995. }());
  65996. Debug.SkeletonViewer = SkeletonViewer;
  65997. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  65998. })(BABYLON || (BABYLON = {}));
  65999. //# sourceMappingURL=babylon.skeletonViewer.js.map
  66000. /**
  66001. * Module Debug contains the (visual) components to debug a scene correctly
  66002. */
  66003. var BABYLON;
  66004. (function (BABYLON) {
  66005. var Debug;
  66006. (function (Debug) {
  66007. /**
  66008. * The Axes viewer will show 3 axes in a specific point in space
  66009. */
  66010. var AxesViewer = /** @class */ (function () {
  66011. /**
  66012. * Creates a new AxesViewer
  66013. * @param scene defines the hosting scene
  66014. * @param scaleLines defines a number used to scale line length (1 by default)
  66015. */
  66016. function AxesViewer(scene, scaleLines) {
  66017. if (scaleLines === void 0) { scaleLines = 1; }
  66018. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  66019. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  66020. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  66021. /**
  66022. * Gets or sets a number used to scale line length
  66023. */
  66024. this.scaleLines = 1;
  66025. this.scaleLines = scaleLines;
  66026. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  66027. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  66028. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  66029. this._xmesh.renderingGroupId = 2;
  66030. this._ymesh.renderingGroupId = 2;
  66031. this._zmesh.renderingGroupId = 2;
  66032. this._xmesh.material.checkReadyOnlyOnce = true;
  66033. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  66034. this._ymesh.material.checkReadyOnlyOnce = true;
  66035. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  66036. this._zmesh.material.checkReadyOnlyOnce = true;
  66037. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  66038. this.scene = scene;
  66039. }
  66040. /**
  66041. * Force the viewer to update
  66042. * @param position defines the position of the viewer
  66043. * @param xaxis defines the x axis of the viewer
  66044. * @param yaxis defines the y axis of the viewer
  66045. * @param zaxis defines the z axis of the viewer
  66046. */
  66047. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  66048. var scaleLines = this.scaleLines;
  66049. if (this._xmesh) {
  66050. this._xmesh.position.copyFrom(position);
  66051. }
  66052. if (this._ymesh) {
  66053. this._ymesh.position.copyFrom(position);
  66054. }
  66055. if (this._zmesh) {
  66056. this._zmesh.position.copyFrom(position);
  66057. }
  66058. var point2 = this._xline[1];
  66059. point2.x = xaxis.x * scaleLines;
  66060. point2.y = xaxis.y * scaleLines;
  66061. point2.z = xaxis.z * scaleLines;
  66062. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  66063. point2 = this._yline[1];
  66064. point2.x = yaxis.x * scaleLines;
  66065. point2.y = yaxis.y * scaleLines;
  66066. point2.z = yaxis.z * scaleLines;
  66067. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  66068. point2 = this._zline[1];
  66069. point2.x = zaxis.x * scaleLines;
  66070. point2.y = zaxis.y * scaleLines;
  66071. point2.z = zaxis.z * scaleLines;
  66072. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  66073. };
  66074. /** Releases resources */
  66075. AxesViewer.prototype.dispose = function () {
  66076. if (this._xmesh) {
  66077. this._xmesh.dispose();
  66078. }
  66079. if (this._ymesh) {
  66080. this._ymesh.dispose();
  66081. }
  66082. if (this._zmesh) {
  66083. this._zmesh.dispose();
  66084. }
  66085. this._xmesh = null;
  66086. this._ymesh = null;
  66087. this._zmesh = null;
  66088. this.scene = null;
  66089. };
  66090. return AxesViewer;
  66091. }());
  66092. Debug.AxesViewer = AxesViewer;
  66093. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  66094. })(BABYLON || (BABYLON = {}));
  66095. //# sourceMappingURL=babylon.axesViewer.js.map
  66096. var BABYLON;
  66097. (function (BABYLON) {
  66098. var Debug;
  66099. (function (Debug) {
  66100. /**
  66101. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  66102. * @see demo here: https://www.babylonjs-playground.com/#0DE8F4#8
  66103. */
  66104. var BoneAxesViewer = /** @class */ (function (_super) {
  66105. __extends(BoneAxesViewer, _super);
  66106. /**
  66107. * Creates a new BoneAxesViewer
  66108. * @param scene defines the hosting scene
  66109. * @param bone defines the target bone
  66110. * @param mesh defines the target mesh
  66111. * @param scaleLines defines a scaling factor for line length (1 by default)
  66112. */
  66113. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  66114. if (scaleLines === void 0) { scaleLines = 1; }
  66115. var _this = _super.call(this, scene, scaleLines) || this;
  66116. /** Gets current position */
  66117. _this.pos = BABYLON.Vector3.Zero();
  66118. /** Gets direction of X axis */
  66119. _this.xaxis = BABYLON.Vector3.Zero();
  66120. /** Gets direction of Y axis */
  66121. _this.yaxis = BABYLON.Vector3.Zero();
  66122. /** Gets direction of Z axis */
  66123. _this.zaxis = BABYLON.Vector3.Zero();
  66124. _this.mesh = mesh;
  66125. _this.bone = bone;
  66126. return _this;
  66127. }
  66128. /**
  66129. * Force the viewer to update
  66130. */
  66131. BoneAxesViewer.prototype.update = function () {
  66132. if (!this.mesh || !this.bone) {
  66133. return;
  66134. }
  66135. var bone = this.bone;
  66136. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  66137. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  66138. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  66139. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  66140. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  66141. };
  66142. /** Releases resources */
  66143. BoneAxesViewer.prototype.dispose = function () {
  66144. if (this.mesh) {
  66145. this.mesh = null;
  66146. this.bone = null;
  66147. _super.prototype.dispose.call(this);
  66148. }
  66149. };
  66150. return BoneAxesViewer;
  66151. }(Debug.AxesViewer));
  66152. Debug.BoneAxesViewer = BoneAxesViewer;
  66153. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  66154. })(BABYLON || (BABYLON = {}));
  66155. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  66156. var BABYLON;
  66157. (function (BABYLON) {
  66158. /**
  66159. * As raycast might be hard to debug, the RayHelper can help rendering the different rays
  66160. * in order to better appreciate the issue one might have.
  66161. * @see http://doc.babylonjs.com/babylon101/raycasts#debugging
  66162. */
  66163. var RayHelper = /** @class */ (function () {
  66164. /**
  66165. * Instantiate a new ray helper.
  66166. * As raycast might be hard to debug, the RayHelper can help rendering the different rays
  66167. * in order to better appreciate the issue one might have.
  66168. * @see http://doc.babylonjs.com/babylon101/raycasts#debugging
  66169. * @param ray Defines the ray we are currently tryin to visualize
  66170. */
  66171. function RayHelper(ray) {
  66172. this.ray = ray;
  66173. }
  66174. /**
  66175. * Helper function to create a colored helper in a scene in one line.
  66176. * @param ray Defines the ray we are currently tryin to visualize
  66177. * @param scene Defines the scene the ray is used in
  66178. * @param color Defines the color we want to see the ray in
  66179. * @returns The newly created ray helper.
  66180. */
  66181. RayHelper.CreateAndShow = function (ray, scene, color) {
  66182. var helper = new RayHelper(ray);
  66183. helper.show(scene, color);
  66184. return helper;
  66185. };
  66186. /**
  66187. * Shows the ray we are willing to debug.
  66188. * @param scene Defines the scene the ray needs to be rendered in
  66189. * @param color Defines the color the ray needs to be rendered in
  66190. */
  66191. RayHelper.prototype.show = function (scene, color) {
  66192. if (!this._renderFunction && this.ray) {
  66193. var ray = this.ray;
  66194. this._renderFunction = this._render.bind(this);
  66195. this._scene = scene;
  66196. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  66197. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  66198. if (this._renderFunction) {
  66199. this._scene.registerBeforeRender(this._renderFunction);
  66200. }
  66201. }
  66202. if (color && this._renderLine) {
  66203. this._renderLine.color.copyFrom(color);
  66204. }
  66205. };
  66206. /**
  66207. * Hides the ray we are debugging.
  66208. */
  66209. RayHelper.prototype.hide = function () {
  66210. if (this._renderFunction && this._scene) {
  66211. this._scene.unregisterBeforeRender(this._renderFunction);
  66212. this._scene = null;
  66213. this._renderFunction = null;
  66214. if (this._renderLine) {
  66215. this._renderLine.dispose();
  66216. this._renderLine = null;
  66217. }
  66218. this._renderPoints = [];
  66219. }
  66220. };
  66221. RayHelper.prototype._render = function () {
  66222. var ray = this.ray;
  66223. if (!ray) {
  66224. return;
  66225. }
  66226. var point = this._renderPoints[1];
  66227. var len = Math.min(ray.length, 1000000);
  66228. point.copyFrom(ray.direction);
  66229. point.scaleInPlace(len);
  66230. point.addInPlace(ray.origin);
  66231. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  66232. };
  66233. /**
  66234. * Attach a ray helper to a mesh so that we can easily see its orientation for instance or information like its normals.
  66235. * @param mesh Defines the mesh we want the helper attached to
  66236. * @param meshSpaceDirection Defines the direction of the Ray in mesh space (local space of the mesh node)
  66237. * @param meshSpaceOrigin Defines the origin of the Ray in mesh space (local space of the mesh node)
  66238. * @param length Defines the length of the ray
  66239. */
  66240. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  66241. this._attachedToMesh = mesh;
  66242. var ray = this.ray;
  66243. if (!ray) {
  66244. return;
  66245. }
  66246. if (!ray.direction) {
  66247. ray.direction = BABYLON.Vector3.Zero();
  66248. }
  66249. if (!ray.origin) {
  66250. ray.origin = BABYLON.Vector3.Zero();
  66251. }
  66252. if (length) {
  66253. ray.length = length;
  66254. }
  66255. if (!meshSpaceOrigin) {
  66256. meshSpaceOrigin = BABYLON.Vector3.Zero();
  66257. }
  66258. if (!meshSpaceDirection) {
  66259. // -1 so that this will work with Mesh.lookAt
  66260. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  66261. }
  66262. if (!this._meshSpaceDirection) {
  66263. this._meshSpaceDirection = meshSpaceDirection.clone();
  66264. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  66265. }
  66266. else {
  66267. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  66268. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  66269. }
  66270. if (!this._updateToMeshFunction) {
  66271. this._updateToMeshFunction = this._updateToMesh.bind(this);
  66272. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  66273. }
  66274. this._updateToMesh();
  66275. };
  66276. /**
  66277. * Detach the ray helper from the mesh it has previously been attached to.
  66278. */
  66279. RayHelper.prototype.detachFromMesh = function () {
  66280. if (this._attachedToMesh) {
  66281. if (this._updateToMeshFunction) {
  66282. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  66283. }
  66284. this._attachedToMesh = null;
  66285. this._updateToMeshFunction = null;
  66286. }
  66287. };
  66288. RayHelper.prototype._updateToMesh = function () {
  66289. var ray = this.ray;
  66290. if (!this._attachedToMesh || !ray) {
  66291. return;
  66292. }
  66293. if (this._attachedToMesh._isDisposed) {
  66294. this.detachFromMesh();
  66295. return;
  66296. }
  66297. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  66298. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  66299. };
  66300. /**
  66301. * Dispose the helper and release its associated resources.
  66302. */
  66303. RayHelper.prototype.dispose = function () {
  66304. this.hide();
  66305. this.detachFromMesh();
  66306. this.ray = null;
  66307. };
  66308. return RayHelper;
  66309. }());
  66310. BABYLON.RayHelper = RayHelper;
  66311. })(BABYLON || (BABYLON = {}));
  66312. //# sourceMappingURL=babylon.rayHelper.js.map
  66313. var BABYLON;
  66314. (function (BABYLON) {
  66315. Object.defineProperty(BABYLON.Scene.prototype, "debugLayer", {
  66316. get: function () {
  66317. if (!this._debugLayer) {
  66318. this._debugLayer = new DebugLayer(this);
  66319. }
  66320. return this._debugLayer;
  66321. },
  66322. enumerable: true,
  66323. configurable: true
  66324. });
  66325. /**
  66326. * The debug layer (aka Inspector) is the go to tool in order to better understand
  66327. * what is happening in your scene
  66328. * @see http://doc.babylonjs.com/features/playground_debuglayer
  66329. */
  66330. var DebugLayer = /** @class */ (function () {
  66331. /**
  66332. * Instantiates a new debug layer.
  66333. * The debug layer (aka Inspector) is the go to tool in order to better understand
  66334. * what is happening in your scene
  66335. * @see http://doc.babylonjs.com/features/playground_debuglayer
  66336. * @param scene Defines the scene to inspect
  66337. */
  66338. function DebugLayer(scene) {
  66339. var _this = this;
  66340. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  66341. /**
  66342. * Observable triggered when a property is changed through the inspector.
  66343. */
  66344. this.onPropertyChangedObservable = new BABYLON.Observable();
  66345. this._scene = scene;
  66346. this._scene.onDisposeObservable.add(function () {
  66347. // Debug layer
  66348. if (_this._scene._debugLayer) {
  66349. _this._scene._debugLayer.hide();
  66350. }
  66351. });
  66352. }
  66353. /** Creates the inspector window. */
  66354. DebugLayer.prototype._createInspector = function (config) {
  66355. if (config === void 0) { config = {}; }
  66356. var popup = config.popup || false;
  66357. var initialTab = config.initialTab || 0;
  66358. var parentElement = config.parentElement || null;
  66359. if (!this._inspector) {
  66360. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  66361. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  66362. } // else nothing to do as instance is already created
  66363. };
  66364. /**
  66365. * Get if the inspector is visible or not.
  66366. * @returns true if visible otherwise, false
  66367. */
  66368. DebugLayer.prototype.isVisible = function () {
  66369. if (!this._inspector) {
  66370. return false;
  66371. }
  66372. return true;
  66373. };
  66374. /**
  66375. * Hide the inspector and close its window.
  66376. */
  66377. DebugLayer.prototype.hide = function () {
  66378. if (this._inspector) {
  66379. try {
  66380. this._inspector.dispose();
  66381. }
  66382. catch (e) {
  66383. // If the inspector has been removed directly from the inspector tool
  66384. }
  66385. this.onPropertyChangedObservable.clear();
  66386. this._inspector = null;
  66387. }
  66388. };
  66389. /**
  66390. *
  66391. * Launch the debugLayer.
  66392. *
  66393. * initialTab:
  66394. * | Value | Tab Name |
  66395. * | --- | --- |
  66396. * | 0 | Scene |
  66397. * | 1 | Console |
  66398. * | 2 | Stats |
  66399. * | 3 | Textures |
  66400. * | 4 | Mesh |
  66401. * | 5 | Light |
  66402. * | 6 | Material |
  66403. * | 7 | GLTF |
  66404. * | 8 | GUI |
  66405. * | 9 | Physics |
  66406. * | 10 | Camera |
  66407. * | 11 | Audio |
  66408. *
  66409. * @param config Define the configuration of the inspector
  66410. */
  66411. DebugLayer.prototype.show = function (config) {
  66412. if (config === void 0) { config = {}; }
  66413. if (typeof this.BJSINSPECTOR == 'undefined') {
  66414. // Load inspector and add it to the DOM
  66415. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  66416. }
  66417. else {
  66418. // Otherwise creates the inspector
  66419. this._createInspector(config);
  66420. }
  66421. };
  66422. /**
  66423. * Gets the active tab
  66424. * @return the index of the active tab or -1 if the inspector is hidden
  66425. */
  66426. DebugLayer.prototype.getActiveTab = function () {
  66427. return this._inspector ? this._inspector.getActiveTabIndex() : -1;
  66428. };
  66429. /**
  66430. * Define the url to get the inspector script from.
  66431. * By default it uses the babylonjs CDN.
  66432. * @ignoreNaming
  66433. */
  66434. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  66435. return DebugLayer;
  66436. }());
  66437. BABYLON.DebugLayer = DebugLayer;
  66438. })(BABYLON || (BABYLON = {}));
  66439. //# sourceMappingURL=babylon.debugLayer.js.map
  66440. var BABYLON;
  66441. (function (BABYLON) {
  66442. var Debug;
  66443. (function (Debug) {
  66444. /**
  66445. * Used to show the physics impostor around the specific mesh
  66446. */
  66447. var PhysicsViewer = /** @class */ (function () {
  66448. /**
  66449. * Creates a new PhysicsViewer
  66450. * @param scene defines the hosting scene
  66451. */
  66452. function PhysicsViewer(scene) {
  66453. /** @hidden */
  66454. this._impostors = [];
  66455. /** @hidden */
  66456. this._meshes = [];
  66457. /** @hidden */
  66458. this._numMeshes = 0;
  66459. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  66460. var physicEngine = this._scene.getPhysicsEngine();
  66461. if (physicEngine) {
  66462. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  66463. }
  66464. }
  66465. /** @hidden */
  66466. PhysicsViewer.prototype._updateDebugMeshes = function () {
  66467. var plugin = this._physicsEnginePlugin;
  66468. for (var i = 0; i < this._numMeshes; i++) {
  66469. var impostor = this._impostors[i];
  66470. if (!impostor) {
  66471. continue;
  66472. }
  66473. if (impostor.isDisposed) {
  66474. this.hideImpostor(this._impostors[i--]);
  66475. }
  66476. else {
  66477. var mesh = this._meshes[i];
  66478. if (mesh && plugin) {
  66479. plugin.syncMeshWithImpostor(mesh, impostor);
  66480. }
  66481. }
  66482. }
  66483. };
  66484. /**
  66485. * Renders a specified physic impostor
  66486. * @param impostor defines the impostor to render
  66487. */
  66488. PhysicsViewer.prototype.showImpostor = function (impostor) {
  66489. if (!this._scene) {
  66490. return;
  66491. }
  66492. for (var i = 0; i < this._numMeshes; i++) {
  66493. if (this._impostors[i] == impostor) {
  66494. return;
  66495. }
  66496. }
  66497. var debugMesh = this._getDebugMesh(impostor, this._scene);
  66498. if (debugMesh) {
  66499. this._impostors[this._numMeshes] = impostor;
  66500. this._meshes[this._numMeshes] = debugMesh;
  66501. if (this._numMeshes === 0) {
  66502. this._renderFunction = this._updateDebugMeshes.bind(this);
  66503. this._scene.registerBeforeRender(this._renderFunction);
  66504. }
  66505. this._numMeshes++;
  66506. }
  66507. };
  66508. /**
  66509. * Hides a specified physic impostor
  66510. * @param impostor defines the impostor to hide
  66511. */
  66512. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  66513. if (!impostor || !this._scene) {
  66514. return;
  66515. }
  66516. var removed = false;
  66517. for (var i = 0; i < this._numMeshes; i++) {
  66518. if (this._impostors[i] == impostor) {
  66519. var mesh = this._meshes[i];
  66520. if (!mesh) {
  66521. continue;
  66522. }
  66523. this._scene.removeMesh(mesh);
  66524. mesh.dispose();
  66525. this._numMeshes--;
  66526. if (this._numMeshes > 0) {
  66527. this._meshes[i] = this._meshes[this._numMeshes];
  66528. this._impostors[i] = this._impostors[this._numMeshes];
  66529. this._meshes[this._numMeshes] = null;
  66530. this._impostors[this._numMeshes] = null;
  66531. }
  66532. else {
  66533. this._meshes[0] = null;
  66534. this._impostors[0] = null;
  66535. }
  66536. removed = true;
  66537. break;
  66538. }
  66539. }
  66540. if (removed && this._numMeshes === 0) {
  66541. this._scene.unregisterBeforeRender(this._renderFunction);
  66542. }
  66543. };
  66544. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  66545. if (!this._debugMaterial) {
  66546. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  66547. this._debugMaterial.wireframe = true;
  66548. }
  66549. return this._debugMaterial;
  66550. };
  66551. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  66552. if (!this._debugBoxMesh) {
  66553. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  66554. this._debugBoxMesh.renderingGroupId = 1;
  66555. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  66556. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  66557. scene.removeMesh(this._debugBoxMesh);
  66558. }
  66559. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  66560. };
  66561. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  66562. if (!this._debugSphereMesh) {
  66563. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  66564. this._debugSphereMesh.renderingGroupId = 1;
  66565. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  66566. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  66567. scene.removeMesh(this._debugSphereMesh);
  66568. }
  66569. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  66570. };
  66571. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  66572. var mesh = null;
  66573. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  66574. mesh = this._getDebugBoxMesh(scene);
  66575. impostor.getBoxSizeToRef(mesh.scaling);
  66576. }
  66577. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  66578. mesh = this._getDebugSphereMesh(scene);
  66579. var radius = impostor.getRadius();
  66580. mesh.scaling.x = radius * 2;
  66581. mesh.scaling.y = radius * 2;
  66582. mesh.scaling.z = radius * 2;
  66583. }
  66584. return mesh;
  66585. };
  66586. /** Releases all resources */
  66587. PhysicsViewer.prototype.dispose = function () {
  66588. for (var i = 0; i < this._numMeshes; i++) {
  66589. this.hideImpostor(this._impostors[i]);
  66590. }
  66591. if (this._debugBoxMesh) {
  66592. this._debugBoxMesh.dispose();
  66593. }
  66594. if (this._debugSphereMesh) {
  66595. this._debugSphereMesh.dispose();
  66596. }
  66597. if (this._debugMaterial) {
  66598. this._debugMaterial.dispose();
  66599. }
  66600. this._impostors.length = 0;
  66601. this._scene = null;
  66602. this._physicsEnginePlugin = null;
  66603. };
  66604. return PhysicsViewer;
  66605. }());
  66606. Debug.PhysicsViewer = PhysicsViewer;
  66607. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  66608. })(BABYLON || (BABYLON = {}));
  66609. //# sourceMappingURL=babylon.physicsViewer.js.map
  66610. var BABYLON;
  66611. (function (BABYLON) {
  66612. Object.defineProperty(BABYLON.Scene.prototype, "forceShowBoundingBoxes", {
  66613. get: function () {
  66614. return this._forceShowBoundingBoxes || false;
  66615. },
  66616. set: function (value) {
  66617. this._forceShowBoundingBoxes = value;
  66618. // Lazyly creates a BB renderer if needed.
  66619. if (value) {
  66620. this.getBoundingBoxRenderer();
  66621. }
  66622. },
  66623. enumerable: true,
  66624. configurable: true
  66625. });
  66626. BABYLON.Scene.prototype.getBoundingBoxRenderer = function () {
  66627. if (!this._boundingBoxRenderer) {
  66628. this._boundingBoxRenderer = new BoundingBoxRenderer(this);
  66629. }
  66630. return this._boundingBoxRenderer;
  66631. };
  66632. Object.defineProperty(BABYLON.AbstractMesh.prototype, "showBoundingBox", {
  66633. get: function () {
  66634. return this._showBoundingBox || false;
  66635. },
  66636. set: function (value) {
  66637. this._showBoundingBox = value;
  66638. // Lazyly creates a BB renderer if needed.
  66639. if (value) {
  66640. this.getScene().getBoundingBoxRenderer();
  66641. }
  66642. },
  66643. enumerable: true,
  66644. configurable: true
  66645. });
  66646. /**
  66647. * Component responsible of rendering the bounding box of the meshes in a scene.
  66648. * This is usually used through the mesh.showBoundingBox or the scene.forceShowBoundingBoxes properties
  66649. */
  66650. var BoundingBoxRenderer = /** @class */ (function () {
  66651. /**
  66652. * Instantiates a new bounding box renderer in a scene.
  66653. * @param scene the scene the renderer renders in
  66654. */
  66655. function BoundingBoxRenderer(scene) {
  66656. /**
  66657. * The component name helpfull to identify the component in the list of scene components.
  66658. */
  66659. this.name = BABYLON.SceneComponentConstants.NAME_BOUNDINGBOXRENDERER;
  66660. /**
  66661. * Color of the bounding box lines placed in front of an object
  66662. */
  66663. this.frontColor = new BABYLON.Color3(1, 1, 1);
  66664. /**
  66665. * Color of the bounding box lines placed behind an object
  66666. */
  66667. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  66668. /**
  66669. * Defines if the renderer should show the back lines or not
  66670. */
  66671. this.showBackLines = true;
  66672. /**
  66673. * @hidden
  66674. */
  66675. this.renderList = new BABYLON.SmartArray(32);
  66676. this._vertexBuffers = {};
  66677. this.scene = scene;
  66678. scene._addComponent(this);
  66679. }
  66680. /**
  66681. * Registers the component in a given scene
  66682. */
  66683. BoundingBoxRenderer.prototype.register = function () {
  66684. this.scene._beforeEvaluateActiveMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER, this, this.reset);
  66685. this.scene._activeMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER, this, this._activeMesh);
  66686. this.scene._evaluateSubMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER, this, this._evaluateSubMesh);
  66687. this.scene._afterRenderingGroupDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER, this, this.render);
  66688. };
  66689. BoundingBoxRenderer.prototype._evaluateSubMesh = function (mesh, subMesh) {
  66690. if (mesh.showSubMeshesBoundingBox) {
  66691. var boundingInfo = subMesh.getBoundingInfo();
  66692. if (boundingInfo !== null && boundingInfo !== undefined) {
  66693. boundingInfo.boundingBox._tag = mesh.renderingGroupId;
  66694. this.renderList.push(boundingInfo.boundingBox);
  66695. }
  66696. }
  66697. };
  66698. BoundingBoxRenderer.prototype._activeMesh = function (sourceMesh, mesh) {
  66699. if (sourceMesh.showBoundingBox || this.scene.forceShowBoundingBoxes) {
  66700. var boundingInfo = sourceMesh.getBoundingInfo();
  66701. boundingInfo.boundingBox._tag = mesh.renderingGroupId;
  66702. this.renderList.push(boundingInfo.boundingBox);
  66703. }
  66704. };
  66705. BoundingBoxRenderer.prototype._prepareRessources = function () {
  66706. if (this._colorShader) {
  66707. return;
  66708. }
  66709. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this.scene, "color", {
  66710. attributes: [BABYLON.VertexBuffer.PositionKind],
  66711. uniforms: ["world", "viewProjection", "color"]
  66712. });
  66713. var engine = this.scene.getEngine();
  66714. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  66715. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  66716. this._createIndexBuffer();
  66717. };
  66718. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  66719. var engine = this.scene.getEngine();
  66720. 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]);
  66721. };
  66722. /**
  66723. * Rebuilds the elements related to this component in case of
  66724. * context lost for instance.
  66725. */
  66726. BoundingBoxRenderer.prototype.rebuild = function () {
  66727. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  66728. if (vb) {
  66729. vb._rebuild();
  66730. }
  66731. this._createIndexBuffer();
  66732. };
  66733. /**
  66734. * @hidden
  66735. */
  66736. BoundingBoxRenderer.prototype.reset = function () {
  66737. this.renderList.reset();
  66738. };
  66739. /**
  66740. * Render the bounding boxes of a specific rendering group
  66741. * @param renderingGroupId defines the rendering group to render
  66742. */
  66743. BoundingBoxRenderer.prototype.render = function (renderingGroupId) {
  66744. if (this.renderList.length === 0) {
  66745. return;
  66746. }
  66747. this._prepareRessources();
  66748. if (!this._colorShader.isReady()) {
  66749. return;
  66750. }
  66751. var engine = this.scene.getEngine();
  66752. engine.setDepthWrite(false);
  66753. this._colorShader._preBind();
  66754. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  66755. var boundingBox = this.renderList.data[boundingBoxIndex];
  66756. if (boundingBox._tag !== renderingGroupId) {
  66757. continue;
  66758. }
  66759. var min = boundingBox.minimum;
  66760. var max = boundingBox.maximum;
  66761. var diff = max.subtract(min);
  66762. var median = min.add(diff.scale(0.5));
  66763. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  66764. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  66765. .multiply(boundingBox.getWorldMatrix());
  66766. // VBOs
  66767. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  66768. if (this.showBackLines) {
  66769. // Back
  66770. engine.setDepthFunctionToGreaterOrEqual();
  66771. this.scene.resetCachedMaterial();
  66772. this._colorShader.setColor4("color", this.backColor.toColor4());
  66773. this._colorShader.bind(worldMatrix);
  66774. // Draw order
  66775. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  66776. }
  66777. // Front
  66778. engine.setDepthFunctionToLess();
  66779. this.scene.resetCachedMaterial();
  66780. this._colorShader.setColor4("color", this.frontColor.toColor4());
  66781. this._colorShader.bind(worldMatrix);
  66782. // Draw order
  66783. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  66784. }
  66785. this._colorShader.unbind();
  66786. engine.setDepthFunctionToLessOrEqual();
  66787. engine.setDepthWrite(true);
  66788. };
  66789. /**
  66790. * In case of occlusion queries, we can render the occlusion bounding box through this method
  66791. * @param mesh Define the mesh to render the occlusion bounding box for
  66792. */
  66793. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  66794. this._prepareRessources();
  66795. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  66796. return;
  66797. }
  66798. var engine = this.scene.getEngine();
  66799. engine.setDepthWrite(false);
  66800. engine.setColorWrite(false);
  66801. this._colorShader._preBind();
  66802. var boundingBox = mesh._boundingInfo.boundingBox;
  66803. var min = boundingBox.minimum;
  66804. var max = boundingBox.maximum;
  66805. var diff = max.subtract(min);
  66806. var median = min.add(diff.scale(0.5));
  66807. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  66808. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  66809. .multiply(boundingBox.getWorldMatrix());
  66810. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  66811. engine.setDepthFunctionToLess();
  66812. this.scene.resetCachedMaterial();
  66813. this._colorShader.bind(worldMatrix);
  66814. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  66815. this._colorShader.unbind();
  66816. engine.setDepthFunctionToLessOrEqual();
  66817. engine.setDepthWrite(true);
  66818. engine.setColorWrite(true);
  66819. };
  66820. /**
  66821. * Dispose and release the resources attached to this renderer.
  66822. */
  66823. BoundingBoxRenderer.prototype.dispose = function () {
  66824. if (!this._colorShader) {
  66825. return;
  66826. }
  66827. this.renderList.dispose();
  66828. this._colorShader.dispose();
  66829. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  66830. if (buffer) {
  66831. buffer.dispose();
  66832. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  66833. }
  66834. this.scene.getEngine()._releaseBuffer(this._indexBuffer);
  66835. };
  66836. return BoundingBoxRenderer;
  66837. }());
  66838. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  66839. })(BABYLON || (BABYLON = {}));
  66840. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  66841. var BABYLON;
  66842. (function (BABYLON) {
  66843. BABYLON.Engine.prototype.createTransformFeedback = function () {
  66844. return this._gl.createTransformFeedback();
  66845. };
  66846. BABYLON.Engine.prototype.deleteTransformFeedback = function (value) {
  66847. this._gl.deleteTransformFeedback(value);
  66848. };
  66849. BABYLON.Engine.prototype.bindTransformFeedback = function (value) {
  66850. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  66851. };
  66852. BABYLON.Engine.prototype.beginTransformFeedback = function (usePoints) {
  66853. if (usePoints === void 0) { usePoints = true; }
  66854. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  66855. };
  66856. BABYLON.Engine.prototype.endTransformFeedback = function () {
  66857. this._gl.endTransformFeedback();
  66858. };
  66859. BABYLON.Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  66860. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  66861. };
  66862. BABYLON.Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  66863. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  66864. };
  66865. })(BABYLON || (BABYLON = {}));
  66866. //# sourceMappingURL=babylon.engine.transformFeedback.js.map
  66867. var BABYLON;
  66868. (function (BABYLON) {
  66869. /**
  66870. * This represents a GPU particle system in Babylon
  66871. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  66872. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  66873. */
  66874. var GPUParticleSystem = /** @class */ (function (_super) {
  66875. __extends(GPUParticleSystem, _super);
  66876. /**
  66877. * Instantiates a GPU particle system.
  66878. * 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.
  66879. * @param name The name of the particle system
  66880. * @param options The options used to create the system
  66881. * @param scene The scene the particle system belongs to
  66882. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  66883. */
  66884. function GPUParticleSystem(name, options, scene, isAnimationSheetEnabled) {
  66885. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  66886. var _this = _super.call(this, name) || this;
  66887. /**
  66888. * The layer mask we are rendering the particles through.
  66889. */
  66890. _this.layerMask = 0x0FFFFFFF;
  66891. _this._accumulatedCount = 0;
  66892. _this._targetIndex = 0;
  66893. _this._currentRenderId = -1;
  66894. _this._started = false;
  66895. _this._stopped = false;
  66896. _this._timeDelta = 0;
  66897. _this._actualFrame = 0;
  66898. _this._rawTextureWidth = 256;
  66899. /**
  66900. * An event triggered when the system is disposed.
  66901. */
  66902. _this.onDisposeObservable = new BABYLON.Observable();
  66903. /**
  66904. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  66905. * to override the particles.
  66906. */
  66907. _this.forceDepthWrite = false;
  66908. _this._preWarmDone = false;
  66909. _this._scene = scene || BABYLON.Engine.LastCreatedScene;
  66910. // Setup the default processing configuration to the scene.
  66911. _this._attachImageProcessingConfiguration(null);
  66912. _this._engine = _this._scene.getEngine();
  66913. if (!options.randomTextureSize) {
  66914. delete options.randomTextureSize;
  66915. }
  66916. var fullOptions = __assign({ capacity: 50000, randomTextureSize: _this._engine.getCaps().maxTextureSize }, options);
  66917. var optionsAsNumber = options;
  66918. if (isFinite(optionsAsNumber)) {
  66919. fullOptions.capacity = optionsAsNumber;
  66920. }
  66921. _this._capacity = fullOptions.capacity;
  66922. _this._activeCount = fullOptions.capacity;
  66923. _this._currentActiveCount = 0;
  66924. _this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  66925. _this._scene.particleSystems.push(_this);
  66926. _this._updateEffectOptions = {
  66927. attributes: ["position", "age", "life", "seed", "size", "color", "direction", "initialDirection", "angle", "cellIndex", "cellStartOffset", "noiseCoordinates1", "noiseCoordinates2"],
  66928. uniformsNames: ["currentCount", "timeDelta", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "scaleRange", "gravity", "emitPower",
  66929. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "coneAngle", "stopFactor",
  66930. "angleRange", "radiusRange", "cellInfos", "noiseStrength", "limitVelocityDamping"],
  66931. uniformBuffersNames: [],
  66932. samplers: ["randomSampler", "randomSampler2", "sizeGradientSampler", "angularSpeedGradientSampler", "velocityGradientSampler", "limitVelocityGradientSampler", "noiseSampler", "dragGradientSampler"],
  66933. defines: "",
  66934. fallbacks: null,
  66935. onCompiled: null,
  66936. onError: null,
  66937. indexParameters: null,
  66938. maxSimultaneousLights: 0,
  66939. transformFeedbackVaryings: []
  66940. };
  66941. _this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  66942. // Random data
  66943. var maxTextureSize = Math.min(_this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  66944. var d = [];
  66945. for (var i = 0; i < maxTextureSize; ++i) {
  66946. d.push(Math.random());
  66947. d.push(Math.random());
  66948. d.push(Math.random());
  66949. d.push(Math.random());
  66950. }
  66951. _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);
  66952. _this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  66953. _this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  66954. d = [];
  66955. for (var i = 0; i < maxTextureSize; ++i) {
  66956. d.push(Math.random());
  66957. d.push(Math.random());
  66958. d.push(Math.random());
  66959. d.push(Math.random());
  66960. }
  66961. _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);
  66962. _this._randomTexture2.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  66963. _this._randomTexture2.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  66964. _this._randomTextureSize = maxTextureSize;
  66965. return _this;
  66966. }
  66967. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  66968. /**
  66969. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  66970. */
  66971. get: function () {
  66972. if (!BABYLON.Engine.LastCreatedEngine) {
  66973. return false;
  66974. }
  66975. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  66976. },
  66977. enumerable: true,
  66978. configurable: true
  66979. });
  66980. /**
  66981. * Gets the maximum number of particles active at the same time.
  66982. * @returns The max number of active particles.
  66983. */
  66984. GPUParticleSystem.prototype.getCapacity = function () {
  66985. return this._capacity;
  66986. };
  66987. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  66988. /**
  66989. * Gets or set the number of active particles
  66990. */
  66991. get: function () {
  66992. return this._activeCount;
  66993. },
  66994. set: function (value) {
  66995. this._activeCount = Math.min(value, this._capacity);
  66996. },
  66997. enumerable: true,
  66998. configurable: true
  66999. });
  67000. /**
  67001. * Is this system ready to be used/rendered
  67002. * @return true if the system is ready
  67003. */
  67004. GPUParticleSystem.prototype.isReady = function () {
  67005. if (!this._updateEffect) {
  67006. this._recreateUpdateEffect();
  67007. this._recreateRenderEffect();
  67008. return false;
  67009. }
  67010. if (!this.emitter || !this._updateEffect.isReady() || !this._imageProcessingConfiguration.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  67011. return false;
  67012. }
  67013. return true;
  67014. };
  67015. /**
  67016. * Gets if the system has been started. (Note: this will still be true after stop is called)
  67017. * @returns True if it has been started, otherwise false.
  67018. */
  67019. GPUParticleSystem.prototype.isStarted = function () {
  67020. return this._started;
  67021. };
  67022. /**
  67023. * Starts the particle system and begins to emit
  67024. * @param delay defines the delay in milliseconds before starting the system (this.startDelay by default)
  67025. */
  67026. GPUParticleSystem.prototype.start = function (delay) {
  67027. var _this = this;
  67028. if (delay === void 0) { delay = this.startDelay; }
  67029. if (!this.targetStopDuration && this._hasTargetStopDurationDependantGradient()) {
  67030. throw "Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set";
  67031. }
  67032. if (delay) {
  67033. setTimeout(function () {
  67034. _this.start(0);
  67035. }, delay);
  67036. return;
  67037. }
  67038. this._started = true;
  67039. this._stopped = false;
  67040. this._preWarmDone = false;
  67041. // Animations
  67042. if (this.beginAnimationOnStart && this.animations && this.animations.length > 0) {
  67043. this.getScene().beginAnimation(this, this.beginAnimationFrom, this.beginAnimationTo, this.beginAnimationLoop);
  67044. }
  67045. };
  67046. /**
  67047. * Stops the particle system.
  67048. */
  67049. GPUParticleSystem.prototype.stop = function () {
  67050. this._stopped = true;
  67051. };
  67052. /**
  67053. * Remove all active particles
  67054. */
  67055. GPUParticleSystem.prototype.reset = function () {
  67056. this._releaseBuffers();
  67057. this._releaseVAOs();
  67058. this._currentActiveCount = 0;
  67059. this._targetIndex = 0;
  67060. };
  67061. /**
  67062. * Returns the string "GPUParticleSystem"
  67063. * @returns a string containing the class name
  67064. */
  67065. GPUParticleSystem.prototype.getClassName = function () {
  67066. return "GPUParticleSystem";
  67067. };
  67068. GPUParticleSystem.prototype._removeGradientAndTexture = function (gradient, gradients, texture) {
  67069. _super.prototype._removeGradientAndTexture.call(this, gradient, gradients, texture);
  67070. this._releaseBuffers();
  67071. return this;
  67072. };
  67073. /**
  67074. * Adds a new color gradient
  67075. * @param gradient defines the gradient to use (between 0 and 1)
  67076. * @param color1 defines the color to affect to the specified gradient
  67077. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  67078. * @returns the current particle system
  67079. */
  67080. GPUParticleSystem.prototype.addColorGradient = function (gradient, color1, color2) {
  67081. if (!this._colorGradients) {
  67082. this._colorGradients = [];
  67083. }
  67084. var colorGradient = new BABYLON.ColorGradient();
  67085. colorGradient.gradient = gradient;
  67086. colorGradient.color1 = color1;
  67087. this._colorGradients.push(colorGradient);
  67088. this._colorGradients.sort(function (a, b) {
  67089. if (a.gradient < b.gradient) {
  67090. return -1;
  67091. }
  67092. else if (a.gradient > b.gradient) {
  67093. return 1;
  67094. }
  67095. return 0;
  67096. });
  67097. if (this._colorGradientsTexture) {
  67098. this._colorGradientsTexture.dispose();
  67099. this._colorGradientsTexture = null;
  67100. }
  67101. this._releaseBuffers();
  67102. return this;
  67103. };
  67104. /**
  67105. * Remove a specific color gradient
  67106. * @param gradient defines the gradient to remove
  67107. * @returns the current particle system
  67108. */
  67109. GPUParticleSystem.prototype.removeColorGradient = function (gradient) {
  67110. this._removeGradientAndTexture(gradient, this._colorGradients, this._colorGradientsTexture);
  67111. this._colorGradientsTexture = null;
  67112. return this;
  67113. };
  67114. GPUParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor) {
  67115. var valueGradient = new BABYLON.FactorGradient();
  67116. valueGradient.gradient = gradient;
  67117. valueGradient.factor1 = factor;
  67118. factorGradients.push(valueGradient);
  67119. factorGradients.sort(function (a, b) {
  67120. if (a.gradient < b.gradient) {
  67121. return -1;
  67122. }
  67123. else if (a.gradient > b.gradient) {
  67124. return 1;
  67125. }
  67126. return 0;
  67127. });
  67128. this._releaseBuffers();
  67129. };
  67130. /**
  67131. * Adds a new size gradient
  67132. * @param gradient defines the gradient to use (between 0 and 1)
  67133. * @param factor defines the size factor to affect to the specified gradient
  67134. * @returns the current particle system
  67135. */
  67136. GPUParticleSystem.prototype.addSizeGradient = function (gradient, factor) {
  67137. if (!this._sizeGradients) {
  67138. this._sizeGradients = [];
  67139. }
  67140. this._addFactorGradient(this._sizeGradients, gradient, factor);
  67141. if (this._sizeGradientsTexture) {
  67142. this._sizeGradientsTexture.dispose();
  67143. this._sizeGradientsTexture = null;
  67144. }
  67145. this._releaseBuffers();
  67146. return this;
  67147. };
  67148. /**
  67149. * Remove a specific size gradient
  67150. * @param gradient defines the gradient to remove
  67151. * @returns the current particle system
  67152. */
  67153. GPUParticleSystem.prototype.removeSizeGradient = function (gradient) {
  67154. this._removeGradientAndTexture(gradient, this._sizeGradients, this._sizeGradientsTexture);
  67155. this._sizeGradientsTexture = null;
  67156. return this;
  67157. };
  67158. /**
  67159. * Adds a new angular speed gradient
  67160. * @param gradient defines the gradient to use (between 0 and 1)
  67161. * @param factor defines the angular speed to affect to the specified gradient
  67162. * @returns the current particle system
  67163. */
  67164. GPUParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor) {
  67165. if (!this._angularSpeedGradients) {
  67166. this._angularSpeedGradients = [];
  67167. }
  67168. this._addFactorGradient(this._angularSpeedGradients, gradient, factor);
  67169. if (this._angularSpeedGradientsTexture) {
  67170. this._angularSpeedGradientsTexture.dispose();
  67171. this._angularSpeedGradientsTexture = null;
  67172. }
  67173. this._releaseBuffers();
  67174. return this;
  67175. };
  67176. /**
  67177. * Remove a specific angular speed gradient
  67178. * @param gradient defines the gradient to remove
  67179. * @returns the current particle system
  67180. */
  67181. GPUParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  67182. this._removeGradientAndTexture(gradient, this._angularSpeedGradients, this._angularSpeedGradientsTexture);
  67183. this._angularSpeedGradientsTexture = null;
  67184. return this;
  67185. };
  67186. /**
  67187. * Adds a new velocity gradient
  67188. * @param gradient defines the gradient to use (between 0 and 1)
  67189. * @param factor defines the velocity to affect to the specified gradient
  67190. * @returns the current particle system
  67191. */
  67192. GPUParticleSystem.prototype.addVelocityGradient = function (gradient, factor) {
  67193. if (!this._velocityGradients) {
  67194. this._velocityGradients = [];
  67195. }
  67196. this._addFactorGradient(this._velocityGradients, gradient, factor);
  67197. if (this._velocityGradientsTexture) {
  67198. this._velocityGradientsTexture.dispose();
  67199. this._velocityGradientsTexture = null;
  67200. }
  67201. this._releaseBuffers();
  67202. return this;
  67203. };
  67204. /**
  67205. * Remove a specific velocity gradient
  67206. * @param gradient defines the gradient to remove
  67207. * @returns the current particle system
  67208. */
  67209. GPUParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  67210. this._removeGradientAndTexture(gradient, this._velocityGradients, this._velocityGradientsTexture);
  67211. this._velocityGradientsTexture = null;
  67212. return this;
  67213. };
  67214. /**
  67215. * Adds a new limit velocity gradient
  67216. * @param gradient defines the gradient to use (between 0 and 1)
  67217. * @param factor defines the limit velocity value to affect to the specified gradient
  67218. * @returns the current particle system
  67219. */
  67220. GPUParticleSystem.prototype.addLimitVelocityGradient = function (gradient, factor) {
  67221. if (!this._limitVelocityGradients) {
  67222. this._limitVelocityGradients = [];
  67223. }
  67224. this._addFactorGradient(this._limitVelocityGradients, gradient, factor);
  67225. if (this._limitVelocityGradientsTexture) {
  67226. this._limitVelocityGradientsTexture.dispose();
  67227. this._limitVelocityGradientsTexture = null;
  67228. }
  67229. this._releaseBuffers();
  67230. return this;
  67231. };
  67232. /**
  67233. * Remove a specific limit velocity gradient
  67234. * @param gradient defines the gradient to remove
  67235. * @returns the current particle system
  67236. */
  67237. GPUParticleSystem.prototype.removeLimitVelocityGradient = function (gradient) {
  67238. this._removeGradientAndTexture(gradient, this._limitVelocityGradients, this._limitVelocityGradientsTexture);
  67239. this._limitVelocityGradientsTexture = null;
  67240. return this;
  67241. };
  67242. /**
  67243. * Adds a new drag gradient
  67244. * @param gradient defines the gradient to use (between 0 and 1)
  67245. * @param factor defines the drag value to affect to the specified gradient
  67246. * @returns the current particle system
  67247. */
  67248. GPUParticleSystem.prototype.addDragGradient = function (gradient, factor) {
  67249. if (!this._dragGradients) {
  67250. this._dragGradients = [];
  67251. }
  67252. this._addFactorGradient(this._dragGradients, gradient, factor);
  67253. if (this._dragGradientsTexture) {
  67254. this._dragGradientsTexture.dispose();
  67255. this._dragGradientsTexture = null;
  67256. }
  67257. this._releaseBuffers();
  67258. return this;
  67259. };
  67260. /**
  67261. * Remove a specific drag gradient
  67262. * @param gradient defines the gradient to remove
  67263. * @returns the current particle system
  67264. */
  67265. GPUParticleSystem.prototype.removeDragGradient = function (gradient) {
  67266. this._removeGradientAndTexture(gradient, this._dragGradients, this._dragGradientsTexture);
  67267. this._dragGradientsTexture = null;
  67268. return this;
  67269. };
  67270. /**
  67271. * Not supported by GPUParticleSystem
  67272. * @param gradient defines the gradient to use (between 0 and 1)
  67273. * @param factor defines the emit rate value to affect to the specified gradient
  67274. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  67275. * @returns the current particle system
  67276. */
  67277. GPUParticleSystem.prototype.addEmitRateGradient = function (gradient, factor, factor2) {
  67278. // Do nothing as emit rate is not supported by GPUParticleSystem
  67279. return this;
  67280. };
  67281. /**
  67282. * Not supported by GPUParticleSystem
  67283. * @param gradient defines the gradient to remove
  67284. * @returns the current particle system
  67285. */
  67286. GPUParticleSystem.prototype.removeEmitRateGradient = function (gradient) {
  67287. // Do nothing as emit rate is not supported by GPUParticleSystem
  67288. return this;
  67289. };
  67290. /**
  67291. * Not supported by GPUParticleSystem
  67292. * @param gradient defines the gradient to use (between 0 and 1)
  67293. * @param factor defines the start size value to affect to the specified gradient
  67294. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  67295. * @returns the current particle system
  67296. */
  67297. GPUParticleSystem.prototype.addStartSizeGradient = function (gradient, factor, factor2) {
  67298. // Do nothing as start size is not supported by GPUParticleSystem
  67299. return this;
  67300. };
  67301. /**
  67302. * Not supported by GPUParticleSystem
  67303. * @param gradient defines the gradient to remove
  67304. * @returns the current particle system
  67305. */
  67306. GPUParticleSystem.prototype.removeStartSizeGradient = function (gradient) {
  67307. // Do nothing as start size is not supported by GPUParticleSystem
  67308. return this;
  67309. };
  67310. /**
  67311. * Not supported by GPUParticleSystem
  67312. * @param gradient defines the gradient to use (between 0 and 1)
  67313. * @param min defines the color remap minimal range
  67314. * @param max defines the color remap maximal range
  67315. * @returns the current particle system
  67316. */
  67317. GPUParticleSystem.prototype.addColorRemapGradient = function (gradient, min, max) {
  67318. // Do nothing as start size is not supported by GPUParticleSystem
  67319. return this;
  67320. };
  67321. /**
  67322. * Not supported by GPUParticleSystem
  67323. * @param gradient defines the gradient to remove
  67324. * @returns the current particle system
  67325. */
  67326. GPUParticleSystem.prototype.removeColorRemapGradient = function (gradient) {
  67327. // Do nothing as start size is not supported by GPUParticleSystem
  67328. return this;
  67329. };
  67330. /**
  67331. * Not supported by GPUParticleSystem
  67332. * @param gradient defines the gradient to use (between 0 and 1)
  67333. * @param min defines the alpha remap minimal range
  67334. * @param max defines the alpha remap maximal range
  67335. * @returns the current particle system
  67336. */
  67337. GPUParticleSystem.prototype.addAlphaRemapGradient = function (gradient, min, max) {
  67338. // Do nothing as start size is not supported by GPUParticleSystem
  67339. return this;
  67340. };
  67341. /**
  67342. * Not supported by GPUParticleSystem
  67343. * @param gradient defines the gradient to remove
  67344. * @returns the current particle system
  67345. */
  67346. GPUParticleSystem.prototype.removeAlphaRemapGradient = function (gradient) {
  67347. // Do nothing as start size is not supported by GPUParticleSystem
  67348. return this;
  67349. };
  67350. /**
  67351. * Not supported by GPUParticleSystem
  67352. * @param gradient defines the gradient to use (between 0 and 1)
  67353. * @param color defines the color to affect to the specified gradient
  67354. * @returns the current particle system
  67355. */
  67356. GPUParticleSystem.prototype.addRampGradient = function (gradient, color) {
  67357. //Not supported by GPUParticleSystem
  67358. return this;
  67359. };
  67360. /**
  67361. * Not supported by GPUParticleSystem
  67362. * @param gradient defines the gradient to remove
  67363. * @returns the current particle system
  67364. */
  67365. GPUParticleSystem.prototype.removeRampGradient = function (gradient) {
  67366. //Not supported by GPUParticleSystem
  67367. return this;
  67368. };
  67369. /**
  67370. * Not supported by GPUParticleSystem
  67371. * @returns the list of ramp gradients
  67372. */
  67373. GPUParticleSystem.prototype.getRampGradients = function () {
  67374. return null;
  67375. };
  67376. Object.defineProperty(GPUParticleSystem.prototype, "useRampGradients", {
  67377. /**
  67378. * Not supported by GPUParticleSystem
  67379. * Gets or sets a boolean indicating that ramp gradients must be used
  67380. * @see http://doc.babylonjs.com/babylon101/particles#ramp-gradients
  67381. */
  67382. get: function () {
  67383. //Not supported by GPUParticleSystem
  67384. return false;
  67385. },
  67386. set: function (value) {
  67387. //Not supported by GPUParticleSystem
  67388. },
  67389. enumerable: true,
  67390. configurable: true
  67391. });
  67392. /**
  67393. * Not supported by GPUParticleSystem
  67394. * @param gradient defines the gradient to use (between 0 and 1)
  67395. * @param factor defines the life time factor to affect to the specified gradient
  67396. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  67397. * @returns the current particle system
  67398. */
  67399. GPUParticleSystem.prototype.addLifeTimeGradient = function (gradient, factor, factor2) {
  67400. //Not supported by GPUParticleSystem
  67401. return this;
  67402. };
  67403. /**
  67404. * Not supported by GPUParticleSystem
  67405. * @param gradient defines the gradient to remove
  67406. * @returns the current particle system
  67407. */
  67408. GPUParticleSystem.prototype.removeLifeTimeGradient = function (gradient) {
  67409. //Not supported by GPUParticleSystem
  67410. return this;
  67411. };
  67412. GPUParticleSystem.prototype._reset = function () {
  67413. this._releaseBuffers();
  67414. };
  67415. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  67416. var updateVertexBuffers = {};
  67417. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  67418. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  67419. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  67420. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 4);
  67421. updateVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3);
  67422. var offset = 12;
  67423. if (!this._colorGradientsTexture) {
  67424. updateVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4);
  67425. offset += 4;
  67426. }
  67427. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", offset, 3);
  67428. offset += 3;
  67429. if (!this._isBillboardBased) {
  67430. updateVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3);
  67431. offset += 3;
  67432. }
  67433. if (this._angularSpeedGradientsTexture) {
  67434. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1);
  67435. offset += 1;
  67436. }
  67437. else {
  67438. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 2);
  67439. offset += 2;
  67440. }
  67441. if (this._isAnimationSheetEnabled) {
  67442. updateVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1);
  67443. offset += 1;
  67444. if (this.spriteRandomStartCell) {
  67445. updateVertexBuffers["cellStartOffset"] = source.createVertexBuffer("cellStartOffset", offset, 1);
  67446. offset += 1;
  67447. }
  67448. }
  67449. if (this.noiseTexture) {
  67450. updateVertexBuffers["noiseCoordinates1"] = source.createVertexBuffer("noiseCoordinates1", offset, 3);
  67451. offset += 3;
  67452. updateVertexBuffers["noiseCoordinates2"] = source.createVertexBuffer("noiseCoordinates2", offset, 3);
  67453. offset += 3;
  67454. }
  67455. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  67456. this._engine.bindArrayBuffer(null);
  67457. return vao;
  67458. };
  67459. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  67460. var renderVertexBuffers = {};
  67461. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  67462. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  67463. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  67464. renderVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3, this._attributesStrideSize, true);
  67465. var offset = 12;
  67466. if (!this._colorGradientsTexture) {
  67467. renderVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4, this._attributesStrideSize, true);
  67468. offset += 4;
  67469. }
  67470. if (this.billboardMode === BABYLON.ParticleSystem.BILLBOARDMODE_STRETCHED) {
  67471. renderVertexBuffers["direction"] = source.createVertexBuffer("direction", offset, 3, this._attributesStrideSize, true);
  67472. }
  67473. offset += 3; // Direction
  67474. if (!this._isBillboardBased) {
  67475. renderVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3, this._attributesStrideSize, true);
  67476. offset += 3;
  67477. }
  67478. renderVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1, this._attributesStrideSize, true);
  67479. if (this._angularSpeedGradientsTexture) {
  67480. offset++;
  67481. }
  67482. else {
  67483. offset += 2;
  67484. }
  67485. if (this._isAnimationSheetEnabled) {
  67486. renderVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1, this._attributesStrideSize, true);
  67487. offset += 1;
  67488. if (this.spriteRandomStartCell) {
  67489. renderVertexBuffers["cellStartOffset"] = source.createVertexBuffer("cellStartOffset", offset, 1, this._attributesStrideSize, true);
  67490. offset += 1;
  67491. }
  67492. }
  67493. if (this.noiseTexture) {
  67494. renderVertexBuffers["noiseCoordinates1"] = source.createVertexBuffer("noiseCoordinates1", offset, 3, this._attributesStrideSize, true);
  67495. offset += 3;
  67496. renderVertexBuffers["noiseCoordinates2"] = source.createVertexBuffer("noiseCoordinates2", offset, 3, this._attributesStrideSize, true);
  67497. offset += 3;
  67498. }
  67499. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  67500. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  67501. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  67502. this._engine.bindArrayBuffer(null);
  67503. return vao;
  67504. };
  67505. GPUParticleSystem.prototype._initialize = function (force) {
  67506. if (force === void 0) { force = false; }
  67507. if (this._buffer0 && !force) {
  67508. return;
  67509. }
  67510. var engine = this._scene.getEngine();
  67511. var data = new Array();
  67512. this._attributesStrideSize = 21;
  67513. this._targetIndex = 0;
  67514. if (!this.isBillboardBased) {
  67515. this._attributesStrideSize += 3;
  67516. }
  67517. if (this._colorGradientsTexture) {
  67518. this._attributesStrideSize -= 4;
  67519. }
  67520. if (this._angularSpeedGradientsTexture) {
  67521. this._attributesStrideSize -= 1;
  67522. }
  67523. if (this._isAnimationSheetEnabled) {
  67524. this._attributesStrideSize += 1;
  67525. if (this.spriteRandomStartCell) {
  67526. this._attributesStrideSize += 1;
  67527. }
  67528. }
  67529. if (this.noiseTexture) {
  67530. this._attributesStrideSize += 6;
  67531. }
  67532. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  67533. // position
  67534. data.push(0.0);
  67535. data.push(0.0);
  67536. data.push(0.0);
  67537. // Age and life
  67538. data.push(0.0); // create the particle as a dead one to create a new one at start
  67539. data.push(0.0);
  67540. // Seed
  67541. data.push(Math.random());
  67542. data.push(Math.random());
  67543. data.push(Math.random());
  67544. data.push(Math.random());
  67545. // Size
  67546. data.push(0.0);
  67547. data.push(0.0);
  67548. data.push(0.0);
  67549. if (!this._colorGradientsTexture) {
  67550. // color
  67551. data.push(0.0);
  67552. data.push(0.0);
  67553. data.push(0.0);
  67554. data.push(0.0);
  67555. }
  67556. // direction
  67557. data.push(0.0);
  67558. data.push(0.0);
  67559. data.push(0.0);
  67560. if (!this.isBillboardBased) {
  67561. // initialDirection
  67562. data.push(0.0);
  67563. data.push(0.0);
  67564. data.push(0.0);
  67565. }
  67566. // angle
  67567. data.push(0.0);
  67568. if (!this._angularSpeedGradientsTexture) {
  67569. data.push(0.0);
  67570. }
  67571. if (this._isAnimationSheetEnabled) {
  67572. data.push(0.0);
  67573. if (this.spriteRandomStartCell) {
  67574. data.push(0.0);
  67575. }
  67576. }
  67577. if (this.noiseTexture) { // Random coordinates for reading into noise texture
  67578. data.push(Math.random());
  67579. data.push(Math.random());
  67580. data.push(Math.random());
  67581. data.push(Math.random());
  67582. data.push(Math.random());
  67583. data.push(Math.random());
  67584. }
  67585. }
  67586. // Sprite data
  67587. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  67588. -0.5, 0.5, 0, 1,
  67589. -0.5, -0.5, 0, 0,
  67590. 0.5, -0.5, 1, 0]);
  67591. // Buffers
  67592. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  67593. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  67594. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  67595. // Update VAO
  67596. this._updateVAO = [];
  67597. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  67598. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  67599. // Render VAO
  67600. this._renderVAO = [];
  67601. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  67602. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  67603. // Links
  67604. this._sourceBuffer = this._buffer0;
  67605. this._targetBuffer = this._buffer1;
  67606. };
  67607. /** @hidden */
  67608. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  67609. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  67610. if (this._isBillboardBased) {
  67611. defines += "\n#define BILLBOARD";
  67612. }
  67613. if (this._colorGradientsTexture) {
  67614. defines += "\n#define COLORGRADIENTS";
  67615. }
  67616. if (this._sizeGradientsTexture) {
  67617. defines += "\n#define SIZEGRADIENTS";
  67618. }
  67619. if (this._angularSpeedGradientsTexture) {
  67620. defines += "\n#define ANGULARSPEEDGRADIENTS";
  67621. }
  67622. if (this._velocityGradientsTexture) {
  67623. defines += "\n#define VELOCITYGRADIENTS";
  67624. }
  67625. if (this._limitVelocityGradientsTexture) {
  67626. defines += "\n#define LIMITVELOCITYGRADIENTS";
  67627. }
  67628. if (this._dragGradientsTexture) {
  67629. defines += "\n#define DRAGGRADIENTS";
  67630. }
  67631. if (this.isAnimationSheetEnabled) {
  67632. defines += "\n#define ANIMATESHEET";
  67633. if (this.spriteRandomStartCell) {
  67634. defines += "\n#define ANIMATESHEETRANDOMSTART";
  67635. }
  67636. }
  67637. if (this.noiseTexture) {
  67638. defines += "\n#define NOISE";
  67639. }
  67640. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  67641. return;
  67642. }
  67643. this._updateEffectOptions.transformFeedbackVaryings = ["outPosition", "outAge", "outLife", "outSeed", "outSize"];
  67644. if (!this._colorGradientsTexture) {
  67645. this._updateEffectOptions.transformFeedbackVaryings.push("outColor");
  67646. }
  67647. this._updateEffectOptions.transformFeedbackVaryings.push("outDirection");
  67648. if (!this._isBillboardBased) {
  67649. this._updateEffectOptions.transformFeedbackVaryings.push("outInitialDirection");
  67650. }
  67651. this._updateEffectOptions.transformFeedbackVaryings.push("outAngle");
  67652. if (this.isAnimationSheetEnabled) {
  67653. this._updateEffectOptions.transformFeedbackVaryings.push("outCellIndex");
  67654. if (this.spriteRandomStartCell) {
  67655. this._updateEffectOptions.transformFeedbackVaryings.push("outCellStartOffset");
  67656. }
  67657. }
  67658. if (this.noiseTexture) {
  67659. this._updateEffectOptions.transformFeedbackVaryings.push("outNoiseCoordinates1");
  67660. this._updateEffectOptions.transformFeedbackVaryings.push("outNoiseCoordinates2");
  67661. }
  67662. this._updateEffectOptions.defines = defines;
  67663. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  67664. };
  67665. /** @hidden */
  67666. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  67667. var defines = "";
  67668. if (this._scene.clipPlane) {
  67669. defines = "\n#define CLIPPLANE";
  67670. }
  67671. if (this._scene.clipPlane2) {
  67672. defines = "\n#define CLIPPLANE2";
  67673. }
  67674. if (this._scene.clipPlane3) {
  67675. defines = "\n#define CLIPPLANE3";
  67676. }
  67677. if (this._scene.clipPlane4) {
  67678. defines = "\n#define CLIPPLANE4";
  67679. }
  67680. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_MULTIPLY) {
  67681. defines = "\n#define BLENDMULTIPLYMODE";
  67682. }
  67683. if (this._isBillboardBased) {
  67684. defines += "\n#define BILLBOARD";
  67685. switch (this.billboardMode) {
  67686. case BABYLON.ParticleSystem.BILLBOARDMODE_Y:
  67687. defines += "\n#define BILLBOARDY";
  67688. break;
  67689. case BABYLON.ParticleSystem.BILLBOARDMODE_STRETCHED:
  67690. defines += "\n#define BILLBOARDSTRETCHED";
  67691. break;
  67692. case BABYLON.ParticleSystem.BILLBOARDMODE_ALL:
  67693. default:
  67694. break;
  67695. }
  67696. }
  67697. if (this._colorGradientsTexture) {
  67698. defines += "\n#define COLORGRADIENTS";
  67699. }
  67700. if (this.isAnimationSheetEnabled) {
  67701. defines += "\n#define ANIMATESHEET";
  67702. }
  67703. if (this._imageProcessingConfiguration) {
  67704. this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines);
  67705. defines += "\n" + this._imageProcessingConfigurationDefines.toString();
  67706. }
  67707. if (this._renderEffect && this._renderEffect.defines === defines) {
  67708. return;
  67709. }
  67710. var uniforms = ["view", "projection", "colorDead", "invView", "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "sheetInfos", "translationPivot", "eyePosition"];
  67711. var samplers = ["textureSampler", "colorGradientSampler"];
  67712. if (BABYLON.ImageProcessingConfiguration) {
  67713. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._imageProcessingConfigurationDefines);
  67714. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._imageProcessingConfigurationDefines);
  67715. }
  67716. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv", "direction", "initialDirection", "angle", "cellIndex"], uniforms, samplers, this._scene.getEngine(), defines);
  67717. };
  67718. /**
  67719. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  67720. * @param preWarm defines if we are in the pre-warmimg phase
  67721. */
  67722. GPUParticleSystem.prototype.animate = function (preWarm) {
  67723. if (preWarm === void 0) { preWarm = false; }
  67724. this._timeDelta = this.updateSpeed * (preWarm ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  67725. this._actualFrame += this._timeDelta;
  67726. if (!this._stopped) {
  67727. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  67728. this.stop();
  67729. }
  67730. }
  67731. };
  67732. GPUParticleSystem.prototype._createFactorGradientTexture = function (factorGradients, textureName) {
  67733. var texture = this[textureName];
  67734. if (!factorGradients || !factorGradients.length || texture) {
  67735. return;
  67736. }
  67737. var data = new Float32Array(this._rawTextureWidth);
  67738. for (var x = 0; x < this._rawTextureWidth; x++) {
  67739. var ratio = x / this._rawTextureWidth;
  67740. BABYLON.Tools.GetCurrentGradient(ratio, factorGradients, function (currentGradient, nextGradient, scale) {
  67741. data[x] = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  67742. });
  67743. }
  67744. this[textureName] = BABYLON.RawTexture.CreateRTexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  67745. };
  67746. GPUParticleSystem.prototype._createSizeGradientTexture = function () {
  67747. this._createFactorGradientTexture(this._sizeGradients, "_sizeGradientsTexture");
  67748. };
  67749. GPUParticleSystem.prototype._createAngularSpeedGradientTexture = function () {
  67750. this._createFactorGradientTexture(this._angularSpeedGradients, "_angularSpeedGradientsTexture");
  67751. };
  67752. GPUParticleSystem.prototype._createVelocityGradientTexture = function () {
  67753. this._createFactorGradientTexture(this._velocityGradients, "_velocityGradientsTexture");
  67754. };
  67755. GPUParticleSystem.prototype._createLimitVelocityGradientTexture = function () {
  67756. this._createFactorGradientTexture(this._limitVelocityGradients, "_limitVelocityGradientsTexture");
  67757. };
  67758. GPUParticleSystem.prototype._createDragGradientTexture = function () {
  67759. this._createFactorGradientTexture(this._dragGradients, "_dragGradientsTexture");
  67760. };
  67761. GPUParticleSystem.prototype._createColorGradientTexture = function () {
  67762. if (!this._colorGradients || !this._colorGradients.length || this._colorGradientsTexture) {
  67763. return;
  67764. }
  67765. var data = new Uint8Array(this._rawTextureWidth * 4);
  67766. var tmpColor = BABYLON.Tmp.Color4[0];
  67767. for (var x = 0; x < this._rawTextureWidth; x++) {
  67768. var ratio = x / this._rawTextureWidth;
  67769. BABYLON.Tools.GetCurrentGradient(ratio, this._colorGradients, function (currentGradient, nextGradient, scale) {
  67770. BABYLON.Color4.LerpToRef(currentGradient.color1, nextGradient.color1, scale, tmpColor);
  67771. data[x * 4] = tmpColor.r * 255;
  67772. data[x * 4 + 1] = tmpColor.g * 255;
  67773. data[x * 4 + 2] = tmpColor.b * 255;
  67774. data[x * 4 + 3] = tmpColor.a * 255;
  67775. });
  67776. }
  67777. this._colorGradientsTexture = BABYLON.RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  67778. };
  67779. /**
  67780. * Renders the particle system in its current state
  67781. * @param preWarm defines if the system should only update the particles but not render them
  67782. * @returns the current number of particles
  67783. */
  67784. GPUParticleSystem.prototype.render = function (preWarm) {
  67785. if (preWarm === void 0) { preWarm = false; }
  67786. if (!this._started) {
  67787. return 0;
  67788. }
  67789. this._createColorGradientTexture();
  67790. this._createSizeGradientTexture();
  67791. this._createAngularSpeedGradientTexture();
  67792. this._createVelocityGradientTexture();
  67793. this._createLimitVelocityGradientTexture();
  67794. this._createDragGradientTexture();
  67795. this._recreateUpdateEffect();
  67796. this._recreateRenderEffect();
  67797. if (!this.isReady()) {
  67798. return 0;
  67799. }
  67800. if (!preWarm) {
  67801. if (!this._preWarmDone && this.preWarmCycles) {
  67802. for (var index = 0; index < this.preWarmCycles; index++) {
  67803. this.animate(true);
  67804. this.render(true);
  67805. }
  67806. this._preWarmDone = true;
  67807. }
  67808. if (this._currentRenderId === this._scene.getFrameId()) {
  67809. return 0;
  67810. }
  67811. this._currentRenderId = this._scene.getFrameId();
  67812. }
  67813. // Get everything ready to render
  67814. this._initialize();
  67815. this._accumulatedCount += this.emitRate * this._timeDelta;
  67816. if (this._accumulatedCount > 1) {
  67817. var intPart = this._accumulatedCount | 0;
  67818. this._accumulatedCount -= intPart;
  67819. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + intPart);
  67820. }
  67821. if (!this._currentActiveCount) {
  67822. return 0;
  67823. }
  67824. // Enable update effect
  67825. this._engine.enableEffect(this._updateEffect);
  67826. this._engine.setState(false);
  67827. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  67828. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  67829. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  67830. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  67831. this._updateEffect.setTexture("randomSampler2", this._randomTexture2);
  67832. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  67833. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  67834. if (!this._colorGradientsTexture) {
  67835. this._updateEffect.setDirectColor4("color1", this.color1);
  67836. this._updateEffect.setDirectColor4("color2", this.color2);
  67837. }
  67838. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  67839. this._updateEffect.setFloat4("scaleRange", this.minScaleX, this.maxScaleX, this.minScaleY, this.maxScaleY);
  67840. this._updateEffect.setFloat4("angleRange", this.minAngularSpeed, this.maxAngularSpeed, this.minInitialRotation, this.maxInitialRotation);
  67841. this._updateEffect.setVector3("gravity", this.gravity);
  67842. if (this._sizeGradientsTexture) {
  67843. this._updateEffect.setTexture("sizeGradientSampler", this._sizeGradientsTexture);
  67844. }
  67845. if (this._angularSpeedGradientsTexture) {
  67846. this._updateEffect.setTexture("angularSpeedGradientSampler", this._angularSpeedGradientsTexture);
  67847. }
  67848. if (this._velocityGradientsTexture) {
  67849. this._updateEffect.setTexture("velocityGradientSampler", this._velocityGradientsTexture);
  67850. }
  67851. if (this._limitVelocityGradientsTexture) {
  67852. this._updateEffect.setTexture("limitVelocityGradientSampler", this._limitVelocityGradientsTexture);
  67853. this._updateEffect.setFloat("limitVelocityDamping", this.limitVelocityDamping);
  67854. }
  67855. if (this._dragGradientsTexture) {
  67856. this._updateEffect.setTexture("dragGradientSampler", this._dragGradientsTexture);
  67857. }
  67858. if (this.particleEmitterType) {
  67859. this.particleEmitterType.applyToShader(this._updateEffect);
  67860. }
  67861. if (this._isAnimationSheetEnabled) {
  67862. this._updateEffect.setFloat3("cellInfos", this.startSpriteCellID, this.endSpriteCellID, this.spriteCellChangeSpeed);
  67863. }
  67864. if (this.noiseTexture) {
  67865. this._updateEffect.setTexture("noiseSampler", this.noiseTexture);
  67866. this._updateEffect.setVector3("noiseStrength", this.noiseStrength);
  67867. }
  67868. var emitterWM;
  67869. if (this.emitter.position) {
  67870. var emitterMesh = this.emitter;
  67871. emitterWM = emitterMesh.getWorldMatrix();
  67872. }
  67873. else {
  67874. var emitterPosition = this.emitter;
  67875. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  67876. }
  67877. this._updateEffect.setMatrix("emitterWM", emitterWM);
  67878. // Bind source VAO
  67879. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  67880. // Update
  67881. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  67882. this._engine.setRasterizerState(false);
  67883. this._engine.beginTransformFeedback(true);
  67884. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  67885. this._engine.endTransformFeedback();
  67886. this._engine.setRasterizerState(true);
  67887. this._engine.bindTransformFeedbackBuffer(null);
  67888. if (!preWarm) {
  67889. // Enable render effect
  67890. this._engine.enableEffect(this._renderEffect);
  67891. var viewMatrix = this._scene.getViewMatrix();
  67892. this._renderEffect.setMatrix("view", viewMatrix);
  67893. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  67894. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  67895. this._renderEffect.setVector2("translationPivot", this.translationPivot);
  67896. if (this._colorGradientsTexture) {
  67897. this._renderEffect.setTexture("colorGradientSampler", this._colorGradientsTexture);
  67898. }
  67899. else {
  67900. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  67901. }
  67902. if (this._isAnimationSheetEnabled && this.particleTexture) {
  67903. var baseSize = this.particleTexture.getBaseSize();
  67904. this._renderEffect.setFloat3("sheetInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  67905. }
  67906. if (this._isBillboardBased) {
  67907. var camera = this._scene.activeCamera;
  67908. this._renderEffect.setVector3("eyePosition", camera.globalPosition);
  67909. }
  67910. if (this._scene.clipPlane || this._scene.clipPlane2 || this._scene.clipPlane3 || this._scene.clipPlane4) {
  67911. var invView = viewMatrix.clone();
  67912. invView.invert();
  67913. this._renderEffect.setMatrix("invView", invView);
  67914. BABYLON.MaterialHelper.BindClipPlane(this._renderEffect, this._scene);
  67915. }
  67916. // image processing
  67917. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  67918. this._imageProcessingConfiguration.bind(this._renderEffect);
  67919. }
  67920. // Draw order
  67921. switch (this.blendMode) {
  67922. case BABYLON.ParticleSystem.BLENDMODE_ADD:
  67923. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  67924. break;
  67925. case BABYLON.ParticleSystem.BLENDMODE_ONEONE:
  67926. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  67927. break;
  67928. case BABYLON.ParticleSystem.BLENDMODE_STANDARD:
  67929. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  67930. break;
  67931. case BABYLON.ParticleSystem.BLENDMODE_MULTIPLY:
  67932. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_MULTIPLY);
  67933. break;
  67934. }
  67935. if (this.forceDepthWrite) {
  67936. this._engine.setDepthWrite(true);
  67937. }
  67938. // Bind source VAO
  67939. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  67940. // Render
  67941. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  67942. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  67943. }
  67944. // Switch VAOs
  67945. this._targetIndex++;
  67946. if (this._targetIndex === 2) {
  67947. this._targetIndex = 0;
  67948. }
  67949. // Switch buffers
  67950. var tmpBuffer = this._sourceBuffer;
  67951. this._sourceBuffer = this._targetBuffer;
  67952. this._targetBuffer = tmpBuffer;
  67953. return this._currentActiveCount;
  67954. };
  67955. /**
  67956. * Rebuilds the particle system
  67957. */
  67958. GPUParticleSystem.prototype.rebuild = function () {
  67959. this._initialize(true);
  67960. };
  67961. GPUParticleSystem.prototype._releaseBuffers = function () {
  67962. if (this._buffer0) {
  67963. this._buffer0.dispose();
  67964. this._buffer0 = null;
  67965. }
  67966. if (this._buffer1) {
  67967. this._buffer1.dispose();
  67968. this._buffer1 = null;
  67969. }
  67970. if (this._spriteBuffer) {
  67971. this._spriteBuffer.dispose();
  67972. this._spriteBuffer = null;
  67973. }
  67974. };
  67975. GPUParticleSystem.prototype._releaseVAOs = function () {
  67976. if (!this._updateVAO) {
  67977. return;
  67978. }
  67979. for (var index = 0; index < this._updateVAO.length; index++) {
  67980. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  67981. }
  67982. this._updateVAO = [];
  67983. for (var index = 0; index < this._renderVAO.length; index++) {
  67984. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  67985. }
  67986. this._renderVAO = [];
  67987. };
  67988. /**
  67989. * Disposes the particle system and free the associated resources
  67990. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  67991. */
  67992. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  67993. if (disposeTexture === void 0) { disposeTexture = true; }
  67994. var index = this._scene.particleSystems.indexOf(this);
  67995. if (index > -1) {
  67996. this._scene.particleSystems.splice(index, 1);
  67997. }
  67998. this._releaseBuffers();
  67999. this._releaseVAOs();
  68000. if (this._colorGradientsTexture) {
  68001. this._colorGradientsTexture.dispose();
  68002. this._colorGradientsTexture = null;
  68003. }
  68004. if (this._sizeGradientsTexture) {
  68005. this._sizeGradientsTexture.dispose();
  68006. this._sizeGradientsTexture = null;
  68007. }
  68008. if (this._angularSpeedGradientsTexture) {
  68009. this._angularSpeedGradientsTexture.dispose();
  68010. this._angularSpeedGradientsTexture = null;
  68011. }
  68012. if (this._velocityGradientsTexture) {
  68013. this._velocityGradientsTexture.dispose();
  68014. this._velocityGradientsTexture = null;
  68015. }
  68016. if (this._limitVelocityGradientsTexture) {
  68017. this._limitVelocityGradientsTexture.dispose();
  68018. this._limitVelocityGradientsTexture = null;
  68019. }
  68020. if (this._dragGradientsTexture) {
  68021. this._dragGradientsTexture.dispose();
  68022. this._dragGradientsTexture = null;
  68023. }
  68024. if (this._randomTexture) {
  68025. this._randomTexture.dispose();
  68026. this._randomTexture = null;
  68027. }
  68028. if (this._randomTexture2) {
  68029. this._randomTexture2.dispose();
  68030. this._randomTexture2 = null;
  68031. }
  68032. if (disposeTexture && this.particleTexture) {
  68033. this.particleTexture.dispose();
  68034. this.particleTexture = null;
  68035. }
  68036. if (disposeTexture && this.noiseTexture) {
  68037. this.noiseTexture.dispose();
  68038. this.noiseTexture = null;
  68039. }
  68040. // Callback
  68041. this.onDisposeObservable.notifyObservers(this);
  68042. this.onDisposeObservable.clear();
  68043. };
  68044. /**
  68045. * Clones the particle system.
  68046. * @param name The name of the cloned object
  68047. * @param newEmitter The new emitter to use
  68048. * @returns the cloned particle system
  68049. */
  68050. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  68051. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  68052. BABYLON.Tools.DeepCopy(this, result);
  68053. if (newEmitter === undefined) {
  68054. newEmitter = this.emitter;
  68055. }
  68056. result.emitter = newEmitter;
  68057. if (this.particleTexture) {
  68058. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  68059. }
  68060. return result;
  68061. };
  68062. /**
  68063. * Serializes the particle system to a JSON object.
  68064. * @returns the JSON object
  68065. */
  68066. GPUParticleSystem.prototype.serialize = function () {
  68067. var serializationObject = {};
  68068. BABYLON.ParticleSystem._Serialize(serializationObject, this);
  68069. serializationObject.activeParticleCount = this.activeParticleCount;
  68070. return serializationObject;
  68071. };
  68072. /**
  68073. * Parses a JSON object to create a GPU particle system.
  68074. * @param parsedParticleSystem The JSON object to parse
  68075. * @param scene The scene to create the particle system in
  68076. * @param rootUrl The root url to use to load external dependencies like texture
  68077. * @param doNotStart Ignore the preventAutoStart attribute and does not start
  68078. * @returns the parsed GPU particle system
  68079. */
  68080. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl, doNotStart) {
  68081. if (doNotStart === void 0) { doNotStart = false; }
  68082. var name = parsedParticleSystem.name;
  68083. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  68084. if (parsedParticleSystem.activeParticleCount) {
  68085. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  68086. }
  68087. BABYLON.ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  68088. // Auto start
  68089. if (parsedParticleSystem.preventAutoStart) {
  68090. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  68091. }
  68092. if (!doNotStart && !particleSystem.preventAutoStart) {
  68093. particleSystem.start();
  68094. }
  68095. return particleSystem;
  68096. };
  68097. return GPUParticleSystem;
  68098. }(BABYLON.BaseParticleSystem));
  68099. BABYLON.GPUParticleSystem = GPUParticleSystem;
  68100. })(BABYLON || (BABYLON = {}));
  68101. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  68102. var BABYLON;
  68103. (function (BABYLON) {
  68104. /**
  68105. * Represents one particle of a solid particle system.
  68106. */
  68107. var SolidParticle = /** @class */ (function () {
  68108. /**
  68109. * Creates a Solid Particle object.
  68110. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  68111. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  68112. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  68113. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  68114. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  68115. * @param shapeId (integer) is the model shape identifier in the SPS.
  68116. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  68117. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  68118. */
  68119. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  68120. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  68121. /**
  68122. * particle global index
  68123. */
  68124. this.idx = 0;
  68125. /**
  68126. * The color of the particle
  68127. */
  68128. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  68129. /**
  68130. * The world space position of the particle.
  68131. */
  68132. this.position = BABYLON.Vector3.Zero();
  68133. /**
  68134. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  68135. */
  68136. this.rotation = BABYLON.Vector3.Zero();
  68137. /**
  68138. * The scaling of the particle.
  68139. */
  68140. this.scaling = BABYLON.Vector3.One();
  68141. /**
  68142. * The uvs of the particle.
  68143. */
  68144. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  68145. /**
  68146. * The current speed of the particle.
  68147. */
  68148. this.velocity = BABYLON.Vector3.Zero();
  68149. /**
  68150. * The pivot point in the particle local space.
  68151. */
  68152. this.pivot = BABYLON.Vector3.Zero();
  68153. /**
  68154. * Must the particle be translated from its pivot point in its local space ?
  68155. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  68156. * Default : false
  68157. */
  68158. this.translateFromPivot = false;
  68159. /**
  68160. * Is the particle active or not ?
  68161. */
  68162. this.alive = true;
  68163. /**
  68164. * Is the particle visible or not ?
  68165. */
  68166. this.isVisible = true;
  68167. /**
  68168. * Index of this particle in the global "positions" array (Internal use)
  68169. * @hidden
  68170. */
  68171. this._pos = 0;
  68172. /**
  68173. * @hidden Index of this particle in the global "indices" array (Internal use)
  68174. */
  68175. this._ind = 0;
  68176. /**
  68177. * ModelShape id of this particle
  68178. */
  68179. this.shapeId = 0;
  68180. /**
  68181. * Index of the particle in its shape id (Internal use)
  68182. */
  68183. this.idxInShape = 0;
  68184. /**
  68185. * @hidden Still set as invisible in order to skip useless computations (Internal use)
  68186. */
  68187. this._stillInvisible = false;
  68188. /**
  68189. * @hidden Last computed particle rotation matrix
  68190. */
  68191. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  68192. /**
  68193. * Parent particle Id, if any.
  68194. * Default null.
  68195. */
  68196. this.parentId = null;
  68197. /**
  68198. * @hidden Internal global position in the SPS.
  68199. */
  68200. this._globalPosition = BABYLON.Vector3.Zero();
  68201. this.idx = particleIndex;
  68202. this._pos = positionIndex;
  68203. this._ind = indiceIndex;
  68204. this._model = model;
  68205. this.shapeId = shapeId;
  68206. this.idxInShape = idxInShape;
  68207. this._sps = sps;
  68208. if (modelBoundingInfo) {
  68209. this._modelBoundingInfo = modelBoundingInfo;
  68210. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  68211. }
  68212. }
  68213. Object.defineProperty(SolidParticle.prototype, "scale", {
  68214. /**
  68215. * Legacy support, changed scale to scaling
  68216. */
  68217. get: function () {
  68218. return this.scaling;
  68219. },
  68220. /**
  68221. * Legacy support, changed scale to scaling
  68222. */
  68223. set: function (scale) {
  68224. this.scaling = scale;
  68225. },
  68226. enumerable: true,
  68227. configurable: true
  68228. });
  68229. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  68230. /**
  68231. * Legacy support, changed quaternion to rotationQuaternion
  68232. */
  68233. get: function () {
  68234. return this.rotationQuaternion;
  68235. },
  68236. /**
  68237. * Legacy support, changed quaternion to rotationQuaternion
  68238. */
  68239. set: function (q) {
  68240. this.rotationQuaternion = q;
  68241. },
  68242. enumerable: true,
  68243. configurable: true
  68244. });
  68245. /**
  68246. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  68247. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  68248. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  68249. * @returns true if it intersects
  68250. */
  68251. SolidParticle.prototype.intersectsMesh = function (target) {
  68252. if (!this._boundingInfo || !target._boundingInfo) {
  68253. return false;
  68254. }
  68255. if (this._sps._bSphereOnly) {
  68256. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  68257. }
  68258. return this._boundingInfo.intersects(target._boundingInfo, false);
  68259. };
  68260. /**
  68261. * get the rotation matrix of the particle
  68262. * @hidden
  68263. */
  68264. SolidParticle.prototype.getRotationMatrix = function (m) {
  68265. var quaternion;
  68266. if (this.rotationQuaternion) {
  68267. quaternion = this.rotationQuaternion;
  68268. }
  68269. else {
  68270. quaternion = BABYLON.Tmp.Quaternion[0];
  68271. var rotation = this.rotation;
  68272. BABYLON.Quaternion.RotationYawPitchRollToRef(rotation.y, rotation.x, rotation.z, quaternion);
  68273. }
  68274. quaternion.toRotationMatrix(m);
  68275. };
  68276. return SolidParticle;
  68277. }());
  68278. BABYLON.SolidParticle = SolidParticle;
  68279. /**
  68280. * Represents the shape of the model used by one particle of a solid particle system.
  68281. * SPS internal tool, don't use it manually.
  68282. */
  68283. var ModelShape = /** @class */ (function () {
  68284. /**
  68285. * 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.
  68286. * SPS internal tool, don't use it manually.
  68287. * @hidden
  68288. */
  68289. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  68290. /**
  68291. * length of the shape in the model indices array (internal use)
  68292. * @hidden
  68293. */
  68294. this._indicesLength = 0;
  68295. this.shapeID = id;
  68296. this._shape = shape;
  68297. this._indicesLength = indicesLength;
  68298. this._shapeUV = shapeUV;
  68299. this._positionFunction = posFunction;
  68300. this._vertexFunction = vtxFunction;
  68301. }
  68302. return ModelShape;
  68303. }());
  68304. BABYLON.ModelShape = ModelShape;
  68305. /**
  68306. * Represents a Depth Sorted Particle in the solid particle system.
  68307. */
  68308. var DepthSortedParticle = /** @class */ (function () {
  68309. function DepthSortedParticle() {
  68310. /**
  68311. * Index of the particle in the "indices" array
  68312. */
  68313. this.ind = 0;
  68314. /**
  68315. * Length of the particle shape in the "indices" array
  68316. */
  68317. this.indicesLength = 0;
  68318. /**
  68319. * Squared distance from the particle to the camera
  68320. */
  68321. this.sqDistance = 0.0;
  68322. }
  68323. return DepthSortedParticle;
  68324. }());
  68325. BABYLON.DepthSortedParticle = DepthSortedParticle;
  68326. })(BABYLON || (BABYLON = {}));
  68327. //# sourceMappingURL=babylon.solidParticle.js.map
  68328. var BABYLON;
  68329. (function (BABYLON) {
  68330. var depthSortFunction = function (p1, p2) { return p2.sqDistance - p1.sqDistance; };
  68331. /**
  68332. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  68333. *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.
  68334. * The SPS is also a particle system. It provides some methods to manage the particles.
  68335. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  68336. *
  68337. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  68338. */
  68339. var SolidParticleSystem = /** @class */ (function () {
  68340. /**
  68341. * Creates a SPS (Solid Particle System) object.
  68342. * @param name (String) is the SPS name, this will be the underlying mesh name.
  68343. * @param scene (Scene) is the scene in which the SPS is added.
  68344. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  68345. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  68346. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  68347. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  68348. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  68349. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  68350. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  68351. */
  68352. function SolidParticleSystem(name, scene, options) {
  68353. /**
  68354. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  68355. * Example : var p = SPS.particles[i];
  68356. */
  68357. this.particles = new Array();
  68358. /**
  68359. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  68360. */
  68361. this.nbParticles = 0;
  68362. /**
  68363. * If the particles must ever face the camera (default false). Useful for planar particles.
  68364. */
  68365. this.billboard = false;
  68366. /**
  68367. * Recompute normals when adding a shape
  68368. */
  68369. this.recomputeNormals = true;
  68370. /**
  68371. * This a counter ofr your own usage. It's not set by any SPS functions.
  68372. */
  68373. this.counter = 0;
  68374. /**
  68375. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  68376. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  68377. */
  68378. this.vars = {};
  68379. /**
  68380. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  68381. * @hidden
  68382. */
  68383. this._bSphereOnly = false;
  68384. /**
  68385. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  68386. * @hidden
  68387. */
  68388. this._bSphereRadiusFactor = 1.0;
  68389. this._positions = new Array();
  68390. this._indices = new Array();
  68391. this._normals = new Array();
  68392. this._colors = new Array();
  68393. this._uvs = new Array();
  68394. this._index = 0; // indices index
  68395. this._updatable = true;
  68396. this._pickable = false;
  68397. this._isVisibilityBoxLocked = false;
  68398. this._alwaysVisible = false;
  68399. this._depthSort = false;
  68400. this._shapeCounter = 0;
  68401. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  68402. this._color = new BABYLON.Color4(0, 0, 0, 0);
  68403. this._computeParticleColor = true;
  68404. this._computeParticleTexture = true;
  68405. this._computeParticleRotation = true;
  68406. this._computeParticleVertex = false;
  68407. this._computeBoundingBox = false;
  68408. this._depthSortParticles = true;
  68409. this._mustUnrotateFixedNormals = false;
  68410. this._particlesIntersect = false;
  68411. this._needs32Bits = false;
  68412. this.name = name;
  68413. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  68414. this._camera = scene.activeCamera;
  68415. this._pickable = options ? options.isPickable : false;
  68416. this._depthSort = options ? options.enableDepthSort : false;
  68417. this._particlesIntersect = options ? options.particleIntersection : false;
  68418. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  68419. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  68420. if (options && options.updatable !== undefined) {
  68421. this._updatable = options.updatable;
  68422. }
  68423. else {
  68424. this._updatable = true;
  68425. }
  68426. if (this._pickable) {
  68427. this.pickedParticles = [];
  68428. }
  68429. if (this._depthSort) {
  68430. this.depthSortedParticles = [];
  68431. }
  68432. }
  68433. /**
  68434. * Builds the SPS underlying mesh. Returns a standard Mesh.
  68435. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  68436. * @returns the created mesh
  68437. */
  68438. SolidParticleSystem.prototype.buildMesh = function () {
  68439. if (this.nbParticles === 0) {
  68440. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  68441. this.addShape(triangle, 1);
  68442. triangle.dispose();
  68443. }
  68444. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  68445. this._positions32 = new Float32Array(this._positions);
  68446. this._uvs32 = new Float32Array(this._uvs);
  68447. this._colors32 = new Float32Array(this._colors);
  68448. if (this.recomputeNormals) {
  68449. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  68450. }
  68451. this._normals32 = new Float32Array(this._normals);
  68452. this._fixedNormal32 = new Float32Array(this._normals);
  68453. if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction
  68454. this._unrotateFixedNormals();
  68455. }
  68456. var vertexData = new BABYLON.VertexData();
  68457. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  68458. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  68459. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  68460. if (this._uvs32.length > 0) {
  68461. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  68462. }
  68463. if (this._colors32.length > 0) {
  68464. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  68465. }
  68466. var mesh = new BABYLON.Mesh(this.name, this._scene);
  68467. vertexData.applyToMesh(mesh, this._updatable);
  68468. this.mesh = mesh;
  68469. this.mesh.isPickable = this._pickable;
  68470. // free memory
  68471. if (!this._depthSort) {
  68472. this._indices = null;
  68473. }
  68474. this._positions = null;
  68475. this._normals = null;
  68476. this._uvs = null;
  68477. this._colors = null;
  68478. if (!this._updatable) {
  68479. this.particles.length = 0;
  68480. }
  68481. return mesh;
  68482. };
  68483. /**
  68484. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  68485. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  68486. * Thus the particles generated from `digest()` have their property `position` set yet.
  68487. * @param mesh ( Mesh ) is the mesh to be digested
  68488. * @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
  68489. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  68490. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  68491. * @returns the current SPS
  68492. */
  68493. SolidParticleSystem.prototype.digest = function (mesh, options) {
  68494. var size = (options && options.facetNb) || 1;
  68495. var number = (options && options.number) || 0;
  68496. var delta = (options && options.delta) || 0;
  68497. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  68498. var meshInd = mesh.getIndices();
  68499. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  68500. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  68501. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  68502. var f = 0; // facet counter
  68503. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  68504. // compute size from number
  68505. if (number) {
  68506. number = (number > totalFacets) ? totalFacets : number;
  68507. size = Math.round(totalFacets / number);
  68508. delta = 0;
  68509. }
  68510. else {
  68511. size = (size > totalFacets) ? totalFacets : size;
  68512. }
  68513. var facetPos = []; // submesh positions
  68514. var facetInd = []; // submesh indices
  68515. var facetUV = []; // submesh UV
  68516. var facetCol = []; // submesh colors
  68517. var barycenter = BABYLON.Vector3.Zero();
  68518. var sizeO = size;
  68519. while (f < totalFacets) {
  68520. size = sizeO + Math.floor((1 + delta) * Math.random());
  68521. if (f > totalFacets - size) {
  68522. size = totalFacets - f;
  68523. }
  68524. // reset temp arrays
  68525. facetPos.length = 0;
  68526. facetInd.length = 0;
  68527. facetUV.length = 0;
  68528. facetCol.length = 0;
  68529. // iterate over "size" facets
  68530. var fi = 0;
  68531. for (var j = f * 3; j < (f + size) * 3; j++) {
  68532. facetInd.push(fi);
  68533. var i = meshInd[j];
  68534. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  68535. if (meshUV) {
  68536. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  68537. }
  68538. if (meshCol) {
  68539. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  68540. }
  68541. fi++;
  68542. }
  68543. // create a model shape for each single particle
  68544. var idx = this.nbParticles;
  68545. var shape = this._posToShape(facetPos);
  68546. var shapeUV = this._uvsToShapeUV(facetUV);
  68547. // compute the barycenter of the shape
  68548. var v;
  68549. for (v = 0; v < shape.length; v++) {
  68550. barycenter.addInPlace(shape[v]);
  68551. }
  68552. barycenter.scaleInPlace(1 / shape.length);
  68553. // shift the shape from its barycenter to the origin
  68554. for (v = 0; v < shape.length; v++) {
  68555. shape[v].subtractInPlace(barycenter);
  68556. }
  68557. var bInfo;
  68558. if (this._particlesIntersect) {
  68559. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  68560. }
  68561. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  68562. // add the particle in the SPS
  68563. var currentPos = this._positions.length;
  68564. var currentInd = this._indices.length;
  68565. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  68566. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  68567. // initialize the particle position
  68568. this.particles[this.nbParticles].position.addInPlace(barycenter);
  68569. this._index += shape.length;
  68570. idx++;
  68571. this.nbParticles++;
  68572. this._shapeCounter++;
  68573. f += size;
  68574. }
  68575. return this;
  68576. };
  68577. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  68578. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  68579. var index = 0;
  68580. var idx = 0;
  68581. var tmpNormal = BABYLON.Tmp.Vector3[0];
  68582. var quaternion = BABYLON.Tmp.Quaternion[0];
  68583. var invertedRotMatrix = BABYLON.Tmp.Matrix[0];
  68584. for (var p = 0; p < this.particles.length; p++) {
  68585. var particle = this.particles[p];
  68586. var shape = particle._model._shape;
  68587. // computing the inverse of the rotation matrix from the quaternion
  68588. // is equivalent to computing the matrix of the inverse quaternion, i.e of the conjugate quaternion
  68589. if (particle.rotationQuaternion) {
  68590. particle.rotationQuaternion.conjugateToRef(quaternion);
  68591. }
  68592. else {
  68593. var rotation = particle.rotation;
  68594. BABYLON.Quaternion.RotationYawPitchRollToRef(rotation.y, rotation.x, rotation.z, quaternion);
  68595. quaternion.conjugateInPlace();
  68596. }
  68597. quaternion.toRotationMatrix(invertedRotMatrix);
  68598. for (var pt = 0; pt < shape.length; pt++) {
  68599. idx = index + pt * 3;
  68600. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], invertedRotMatrix, tmpNormal);
  68601. tmpNormal.toArray(this._fixedNormal32, idx);
  68602. }
  68603. index = idx + 3;
  68604. }
  68605. };
  68606. //reset copy
  68607. SolidParticleSystem.prototype._resetCopy = function () {
  68608. var copy = this._copy;
  68609. copy.position.setAll(0);
  68610. copy.rotation.setAll(0);
  68611. copy.rotationQuaternion = null;
  68612. copy.scaling.setAll(1);
  68613. copy.uvs.copyFromFloats(0.0, 0.0, 1.0, 1.0);
  68614. copy.color = null;
  68615. copy.translateFromPivot = false;
  68616. };
  68617. // _meshBuilder : inserts the shape model in the global SPS mesh
  68618. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  68619. var i;
  68620. var u = 0;
  68621. var c = 0;
  68622. var n = 0;
  68623. this._resetCopy();
  68624. var copy = this._copy;
  68625. if (options && options.positionFunction) { // call to custom positionFunction
  68626. options.positionFunction(copy, idx, idxInShape);
  68627. this._mustUnrotateFixedNormals = true;
  68628. }
  68629. var rotMatrix = BABYLON.Tmp.Matrix[0];
  68630. var tmpVertex = BABYLON.Tmp.Vector3[0];
  68631. var tmpRotated = BABYLON.Tmp.Vector3[1];
  68632. var pivotBackTranslation = BABYLON.Tmp.Vector3[2];
  68633. var scaledPivot = BABYLON.Tmp.Vector3[3];
  68634. copy.getRotationMatrix(rotMatrix);
  68635. copy.pivot.multiplyToRef(copy.scaling, scaledPivot);
  68636. if (copy.translateFromPivot) {
  68637. pivotBackTranslation.setAll(0.0);
  68638. }
  68639. else {
  68640. pivotBackTranslation.copyFrom(scaledPivot);
  68641. }
  68642. for (i = 0; i < shape.length; i++) {
  68643. tmpVertex.copyFrom(shape[i]);
  68644. if (options && options.vertexFunction) {
  68645. options.vertexFunction(copy, tmpVertex, i);
  68646. }
  68647. tmpVertex.multiplyInPlace(copy.scaling).subtractInPlace(scaledPivot);
  68648. BABYLON.Vector3.TransformCoordinatesToRef(tmpVertex, rotMatrix, tmpRotated);
  68649. tmpRotated.addInPlace(pivotBackTranslation).addInPlace(copy.position);
  68650. positions.push(tmpRotated.x, tmpRotated.y, tmpRotated.z);
  68651. if (meshUV) {
  68652. var copyUvs = copy.uvs;
  68653. uvs.push((copyUvs.z - copyUvs.x) * meshUV[u] + copyUvs.x, (copyUvs.w - copyUvs.y) * meshUV[u + 1] + copyUvs.y);
  68654. u += 2;
  68655. }
  68656. if (copy.color) {
  68657. this._color = copy.color;
  68658. }
  68659. else {
  68660. var color = this._color;
  68661. if (meshCol && meshCol[c] !== undefined) {
  68662. color.r = meshCol[c];
  68663. color.g = meshCol[c + 1];
  68664. color.b = meshCol[c + 2];
  68665. color.a = meshCol[c + 3];
  68666. }
  68667. else {
  68668. color.r = 1.0;
  68669. color.g = 1.0;
  68670. color.b = 1.0;
  68671. color.a = 1.0;
  68672. }
  68673. }
  68674. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  68675. c += 4;
  68676. if (!this.recomputeNormals && meshNor) {
  68677. tmpVertex.x = meshNor[n];
  68678. tmpVertex.y = meshNor[n + 1];
  68679. tmpVertex.z = meshNor[n + 2];
  68680. BABYLON.Vector3.TransformNormalToRef(tmpVertex, rotMatrix, tmpVertex);
  68681. normals.push(tmpVertex.x, tmpVertex.y, tmpVertex.z);
  68682. n += 3;
  68683. }
  68684. }
  68685. for (i = 0; i < meshInd.length; i++) {
  68686. var current_ind = p + meshInd[i];
  68687. indices.push(current_ind);
  68688. if (current_ind > 65535) {
  68689. this._needs32Bits = true;
  68690. }
  68691. }
  68692. if (this._pickable) {
  68693. var nbfaces = meshInd.length / 3;
  68694. for (i = 0; i < nbfaces; i++) {
  68695. this.pickedParticles.push({ idx: idx, faceId: i });
  68696. }
  68697. }
  68698. if (this._depthSort) {
  68699. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  68700. }
  68701. return copy;
  68702. };
  68703. // returns a shape array from positions array
  68704. SolidParticleSystem.prototype._posToShape = function (positions) {
  68705. var shape = [];
  68706. for (var i = 0; i < positions.length; i += 3) {
  68707. shape.push(BABYLON.Vector3.FromArray(positions, i));
  68708. }
  68709. return shape;
  68710. };
  68711. // returns a shapeUV array from a Vector4 uvs
  68712. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  68713. var shapeUV = [];
  68714. if (uvs) {
  68715. for (var i = 0; i < uvs.length; i++) {
  68716. shapeUV.push(uvs[i]);
  68717. }
  68718. }
  68719. return shapeUV;
  68720. };
  68721. // adds a new particle object in the particles array
  68722. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  68723. if (bInfo === void 0) { bInfo = null; }
  68724. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  68725. this.particles.push(sp);
  68726. return sp;
  68727. };
  68728. /**
  68729. * Adds some particles to the SPS from the model shape. Returns the shape id.
  68730. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  68731. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  68732. * @param nb (positive integer) the number of particles to be created from this model
  68733. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  68734. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  68735. * @returns the number of shapes in the system
  68736. */
  68737. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  68738. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  68739. var meshInd = mesh.getIndices();
  68740. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  68741. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  68742. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  68743. var bbInfo;
  68744. if (this._particlesIntersect) {
  68745. bbInfo = mesh.getBoundingInfo();
  68746. }
  68747. var shape = this._posToShape(meshPos);
  68748. var shapeUV = this._uvsToShapeUV(meshUV);
  68749. var posfunc = options ? options.positionFunction : null;
  68750. var vtxfunc = options ? options.vertexFunction : null;
  68751. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  68752. // particles
  68753. var sp;
  68754. var currentCopy;
  68755. var idx = this.nbParticles;
  68756. for (var i = 0; i < nb; i++) {
  68757. var currentPos = this._positions.length;
  68758. var currentInd = this._indices.length;
  68759. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  68760. if (this._updatable) {
  68761. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  68762. sp.position.copyFrom(currentCopy.position);
  68763. sp.rotation.copyFrom(currentCopy.rotation);
  68764. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  68765. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  68766. }
  68767. if (currentCopy.color && sp.color) {
  68768. sp.color.copyFrom(currentCopy.color);
  68769. }
  68770. sp.scaling.copyFrom(currentCopy.scaling);
  68771. sp.uvs.copyFrom(currentCopy.uvs);
  68772. }
  68773. this._index += shape.length;
  68774. idx++;
  68775. }
  68776. this.nbParticles += nb;
  68777. this._shapeCounter++;
  68778. return this._shapeCounter - 1;
  68779. };
  68780. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  68781. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  68782. this._resetCopy();
  68783. var copy = this._copy;
  68784. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  68785. particle._model._positionFunction(copy, particle.idx, particle.idxInShape);
  68786. }
  68787. var rotMatrix = BABYLON.Tmp.Matrix[0];
  68788. var tmpVertex = BABYLON.Tmp.Vector3[0];
  68789. var tmpRotated = BABYLON.Tmp.Vector3[1];
  68790. var pivotBackTranslation = BABYLON.Tmp.Vector3[2];
  68791. var scaledPivot = BABYLON.Tmp.Vector3[3];
  68792. copy.getRotationMatrix(rotMatrix);
  68793. particle.pivot.multiplyToRef(particle.scaling, scaledPivot);
  68794. if (copy.translateFromPivot) {
  68795. pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  68796. }
  68797. else {
  68798. pivotBackTranslation.copyFrom(scaledPivot);
  68799. }
  68800. var shape = particle._model._shape;
  68801. for (var pt = 0; pt < shape.length; pt++) {
  68802. tmpVertex.copyFrom(shape[pt]);
  68803. if (particle._model._vertexFunction) {
  68804. particle._model._vertexFunction(copy, tmpVertex, pt); // recall to stored vertexFunction
  68805. }
  68806. tmpVertex.multiplyInPlace(copy.scaling).subtractInPlace(scaledPivot);
  68807. BABYLON.Vector3.TransformCoordinatesToRef(tmpVertex, rotMatrix, tmpRotated);
  68808. tmpRotated.addInPlace(pivotBackTranslation).addInPlace(copy.position).toArray(this._positions32, particle._pos + pt * 3);
  68809. }
  68810. particle.position.setAll(0.0);
  68811. particle.rotation.setAll(0.0);
  68812. particle.rotationQuaternion = null;
  68813. particle.scaling.setAll(1.0);
  68814. particle.uvs.setAll(0.0);
  68815. particle.pivot.setAll(0.0);
  68816. particle.translateFromPivot = false;
  68817. particle.parentId = null;
  68818. };
  68819. /**
  68820. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  68821. * @returns the SPS.
  68822. */
  68823. SolidParticleSystem.prototype.rebuildMesh = function () {
  68824. for (var p = 0; p < this.particles.length; p++) {
  68825. this._rebuildParticle(this.particles[p]);
  68826. }
  68827. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  68828. return this;
  68829. };
  68830. /**
  68831. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  68832. * This method calls `updateParticle()` for each particle of the SPS.
  68833. * For an animated SPS, it is usually called within the render loop.
  68834. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  68835. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  68836. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  68837. * @returns the SPS.
  68838. */
  68839. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  68840. if (start === void 0) { start = 0; }
  68841. if (end === void 0) { end = this.nbParticles - 1; }
  68842. if (update === void 0) { update = true; }
  68843. if (!this._updatable) {
  68844. return this;
  68845. }
  68846. // custom beforeUpdate
  68847. this.beforeUpdateParticles(start, end, update);
  68848. var rotMatrix = BABYLON.Tmp.Matrix[0];
  68849. var invertedMatrix = BABYLON.Tmp.Matrix[1];
  68850. var mesh = this.mesh;
  68851. var colors32 = this._colors32;
  68852. var positions32 = this._positions32;
  68853. var normals32 = this._normals32;
  68854. var uvs32 = this._uvs32;
  68855. var indices32 = this._indices32;
  68856. var indices = this._indices;
  68857. var fixedNormal32 = this._fixedNormal32;
  68858. var tempVectors = BABYLON.Tmp.Vector3;
  68859. var camAxisX = tempVectors[5].copyFromFloats(1.0, 0.0, 0.0);
  68860. var camAxisY = tempVectors[6].copyFromFloats(0.0, 1.0, 0.0);
  68861. var camAxisZ = tempVectors[7].copyFromFloats(0.0, 0.0, 1.0);
  68862. var minimum = tempVectors[8].setAll(Number.MAX_VALUE);
  68863. var maximum = tempVectors[9].setAll(-Number.MAX_VALUE);
  68864. var camInvertedPosition = tempVectors[10].setAll(0);
  68865. // cases when the World Matrix is to be computed first
  68866. if (this.billboard || this._depthSort) {
  68867. this.mesh.computeWorldMatrix(true);
  68868. this.mesh._worldMatrix.invertToRef(invertedMatrix);
  68869. }
  68870. // if the particles will always face the camera
  68871. if (this.billboard) {
  68872. // compute the camera position and un-rotate it by the current mesh rotation
  68873. var tmpVertex = tempVectors[0];
  68874. this._camera.getDirectionToRef(BABYLON.Axis.Z, tmpVertex);
  68875. BABYLON.Vector3.TransformNormalToRef(tmpVertex, invertedMatrix, camAxisZ);
  68876. camAxisZ.normalize();
  68877. // same for camera up vector extracted from the cam view matrix
  68878. var view = this._camera.getViewMatrix(true);
  68879. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], invertedMatrix, camAxisY);
  68880. BABYLON.Vector3.CrossToRef(camAxisY, camAxisZ, camAxisX);
  68881. camAxisY.normalize();
  68882. camAxisX.normalize();
  68883. }
  68884. // if depthSort, compute the camera global position in the mesh local system
  68885. if (this._depthSort) {
  68886. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, invertedMatrix, camInvertedPosition); // then un-rotate the camera
  68887. }
  68888. BABYLON.Matrix.IdentityToRef(rotMatrix);
  68889. var idx = 0; // current position index in the global array positions32
  68890. var index = 0; // position start index in the global array positions32 of the current particle
  68891. var colidx = 0; // current color index in the global array colors32
  68892. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  68893. var uvidx = 0; // current uv index in the global array uvs32
  68894. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  68895. var pt = 0; // current index in the particle model shape
  68896. if (this.mesh.isFacetDataEnabled) {
  68897. this._computeBoundingBox = true;
  68898. }
  68899. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  68900. if (this._computeBoundingBox) {
  68901. if (start != 0 || end != this.nbParticles - 1) { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  68902. var boundingInfo = this.mesh._boundingInfo;
  68903. if (boundingInfo) {
  68904. minimum.copyFrom(boundingInfo.minimum);
  68905. maximum.copyFrom(boundingInfo.maximum);
  68906. }
  68907. }
  68908. }
  68909. // particle loop
  68910. index = this.particles[start]._pos;
  68911. var vpos = (index / 3) | 0;
  68912. colorIndex = vpos * 4;
  68913. uvIndex = vpos * 2;
  68914. for (var p = start; p <= end; p++) {
  68915. var particle = this.particles[p];
  68916. // call to custom user function to update the particle properties
  68917. this.updateParticle(particle);
  68918. var shape = particle._model._shape;
  68919. var shapeUV = particle._model._shapeUV;
  68920. var particleRotationMatrix = particle._rotationMatrix;
  68921. var particlePosition = particle.position;
  68922. var particleRotation = particle.rotation;
  68923. var particleScaling = particle.scaling;
  68924. var particleGlobalPosition = particle._globalPosition;
  68925. // camera-particle distance for depth sorting
  68926. if (this._depthSort && this._depthSortParticles) {
  68927. var dsp = this.depthSortedParticles[p];
  68928. dsp.ind = particle._ind;
  68929. dsp.indicesLength = particle._model._indicesLength;
  68930. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(particle.position, camInvertedPosition);
  68931. }
  68932. // skip the computations for inactive or already invisible particles
  68933. if (!particle.alive || (particle._stillInvisible && !particle.isVisible)) {
  68934. // increment indexes for the next particle
  68935. pt = shape.length;
  68936. index += pt * 3;
  68937. colorIndex += pt * 4;
  68938. uvIndex += pt * 2;
  68939. continue;
  68940. }
  68941. if (particle.isVisible) {
  68942. particle._stillInvisible = false; // un-mark permanent invisibility
  68943. var scaledPivot = tempVectors[12];
  68944. particle.pivot.multiplyToRef(particleScaling, scaledPivot);
  68945. // particle rotation matrix
  68946. if (this.billboard) {
  68947. particleRotation.x = 0.0;
  68948. particleRotation.y = 0.0;
  68949. }
  68950. if (this._computeParticleRotation || this.billboard) {
  68951. particle.getRotationMatrix(rotMatrix);
  68952. }
  68953. var particleHasParent = (particle.parentId !== null);
  68954. if (particleHasParent) {
  68955. var parent_1 = this.particles[particle.parentId];
  68956. var parentRotationMatrix = parent_1._rotationMatrix;
  68957. var parentGlobalPosition = parent_1._globalPosition;
  68958. var rotatedY = particlePosition.x * parentRotationMatrix[1] + particlePosition.y * parentRotationMatrix[4] + particlePosition.z * parentRotationMatrix[7];
  68959. var rotatedX = particlePosition.x * parentRotationMatrix[0] + particlePosition.y * parentRotationMatrix[3] + particlePosition.z * parentRotationMatrix[6];
  68960. var rotatedZ = particlePosition.x * parentRotationMatrix[2] + particlePosition.y * parentRotationMatrix[5] + particlePosition.z * parentRotationMatrix[8];
  68961. particleGlobalPosition.x = parentGlobalPosition.x + rotatedX;
  68962. particleGlobalPosition.y = parentGlobalPosition.y + rotatedY;
  68963. particleGlobalPosition.z = parentGlobalPosition.z + rotatedZ;
  68964. if (this._computeParticleRotation || this.billboard) {
  68965. var rotMatrixValues = rotMatrix.m;
  68966. particleRotationMatrix[0] = rotMatrixValues[0] * parentRotationMatrix[0] + rotMatrixValues[1] * parentRotationMatrix[3] + rotMatrixValues[2] * parentRotationMatrix[6];
  68967. particleRotationMatrix[1] = rotMatrixValues[0] * parentRotationMatrix[1] + rotMatrixValues[1] * parentRotationMatrix[4] + rotMatrixValues[2] * parentRotationMatrix[7];
  68968. particleRotationMatrix[2] = rotMatrixValues[0] * parentRotationMatrix[2] + rotMatrixValues[1] * parentRotationMatrix[5] + rotMatrixValues[2] * parentRotationMatrix[8];
  68969. particleRotationMatrix[3] = rotMatrixValues[4] * parentRotationMatrix[0] + rotMatrixValues[5] * parentRotationMatrix[3] + rotMatrixValues[6] * parentRotationMatrix[6];
  68970. particleRotationMatrix[4] = rotMatrixValues[4] * parentRotationMatrix[1] + rotMatrixValues[5] * parentRotationMatrix[4] + rotMatrixValues[6] * parentRotationMatrix[7];
  68971. particleRotationMatrix[5] = rotMatrixValues[4] * parentRotationMatrix[2] + rotMatrixValues[5] * parentRotationMatrix[5] + rotMatrixValues[6] * parentRotationMatrix[8];
  68972. particleRotationMatrix[6] = rotMatrixValues[8] * parentRotationMatrix[0] + rotMatrixValues[9] * parentRotationMatrix[3] + rotMatrixValues[10] * parentRotationMatrix[6];
  68973. particleRotationMatrix[7] = rotMatrixValues[8] * parentRotationMatrix[1] + rotMatrixValues[9] * parentRotationMatrix[4] + rotMatrixValues[10] * parentRotationMatrix[7];
  68974. particleRotationMatrix[8] = rotMatrixValues[8] * parentRotationMatrix[2] + rotMatrixValues[9] * parentRotationMatrix[5] + rotMatrixValues[10] * parentRotationMatrix[8];
  68975. }
  68976. }
  68977. else {
  68978. particleGlobalPosition.x = particlePosition.x;
  68979. particleGlobalPosition.y = particlePosition.y;
  68980. particleGlobalPosition.z = particlePosition.z;
  68981. if (this._computeParticleRotation || this.billboard) {
  68982. var rotMatrixValues = rotMatrix.m;
  68983. particleRotationMatrix[0] = rotMatrixValues[0];
  68984. particleRotationMatrix[1] = rotMatrixValues[1];
  68985. particleRotationMatrix[2] = rotMatrixValues[2];
  68986. particleRotationMatrix[3] = rotMatrixValues[4];
  68987. particleRotationMatrix[4] = rotMatrixValues[5];
  68988. particleRotationMatrix[5] = rotMatrixValues[6];
  68989. particleRotationMatrix[6] = rotMatrixValues[8];
  68990. particleRotationMatrix[7] = rotMatrixValues[9];
  68991. particleRotationMatrix[8] = rotMatrixValues[10];
  68992. }
  68993. }
  68994. var pivotBackTranslation = tempVectors[11];
  68995. if (particle.translateFromPivot) {
  68996. pivotBackTranslation.setAll(0.0);
  68997. }
  68998. else {
  68999. pivotBackTranslation.copyFrom(scaledPivot);
  69000. }
  69001. // particle vertex loop
  69002. for (pt = 0; pt < shape.length; pt++) {
  69003. idx = index + pt * 3;
  69004. colidx = colorIndex + pt * 4;
  69005. uvidx = uvIndex + pt * 2;
  69006. var tmpVertex = tempVectors[0];
  69007. tmpVertex.copyFrom(shape[pt]);
  69008. if (this._computeParticleVertex) {
  69009. this.updateParticleVertex(particle, tmpVertex, pt);
  69010. }
  69011. // positions
  69012. var vertexX = tmpVertex.x * particleScaling.x - scaledPivot.x;
  69013. var vertexY = tmpVertex.y * particleScaling.y - scaledPivot.y;
  69014. var vertexZ = tmpVertex.z * particleScaling.z - scaledPivot.z;
  69015. var rotatedX = vertexX * particleRotationMatrix[0] + vertexY * particleRotationMatrix[3] + vertexZ * particleRotationMatrix[6];
  69016. var rotatedY = vertexX * particleRotationMatrix[1] + vertexY * particleRotationMatrix[4] + vertexZ * particleRotationMatrix[7];
  69017. var rotatedZ = vertexX * particleRotationMatrix[2] + vertexY * particleRotationMatrix[5] + vertexZ * particleRotationMatrix[8];
  69018. rotatedX += pivotBackTranslation.x;
  69019. rotatedY += pivotBackTranslation.y;
  69020. rotatedZ += pivotBackTranslation.z;
  69021. var px = positions32[idx] = particleGlobalPosition.x + camAxisX.x * rotatedX + camAxisY.x * rotatedY + camAxisZ.x * rotatedZ;
  69022. var py = positions32[idx + 1] = particleGlobalPosition.y + camAxisX.y * rotatedX + camAxisY.y * rotatedY + camAxisZ.y * rotatedZ;
  69023. var pz = positions32[idx + 2] = particleGlobalPosition.z + camAxisX.z * rotatedX + camAxisY.z * rotatedY + camAxisZ.z * rotatedZ;
  69024. if (this._computeBoundingBox) {
  69025. minimum.minimizeInPlaceFromFloats(px, py, pz);
  69026. maximum.maximizeInPlaceFromFloats(px, py, pz);
  69027. }
  69028. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  69029. if (!this._computeParticleVertex) {
  69030. var normalx = fixedNormal32[idx];
  69031. var normaly = fixedNormal32[idx + 1];
  69032. var normalz = fixedNormal32[idx + 2];
  69033. var rotatedx = normalx * particleRotationMatrix[0] + normaly * particleRotationMatrix[3] + normalz * particleRotationMatrix[6];
  69034. var rotatedy = normalx * particleRotationMatrix[1] + normaly * particleRotationMatrix[4] + normalz * particleRotationMatrix[7];
  69035. var rotatedz = normalx * particleRotationMatrix[2] + normaly * particleRotationMatrix[5] + normalz * particleRotationMatrix[8];
  69036. normals32[idx] = camAxisX.x * rotatedx + camAxisY.x * rotatedy + camAxisZ.x * rotatedz;
  69037. normals32[idx + 1] = camAxisX.y * rotatedx + camAxisY.y * rotatedy + camAxisZ.y * rotatedz;
  69038. normals32[idx + 2] = camAxisX.z * rotatedx + camAxisY.z * rotatedy + camAxisZ.z * rotatedz;
  69039. }
  69040. if (this._computeParticleColor && particle.color) {
  69041. var color = particle.color;
  69042. var colors32_1 = this._colors32;
  69043. colors32_1[colidx] = color.r;
  69044. colors32_1[colidx + 1] = color.g;
  69045. colors32_1[colidx + 2] = color.b;
  69046. colors32_1[colidx + 3] = color.a;
  69047. }
  69048. if (this._computeParticleTexture) {
  69049. var uvs = particle.uvs;
  69050. uvs32[uvidx] = shapeUV[pt * 2] * (uvs.z - uvs.x) + uvs.x;
  69051. uvs32[uvidx + 1] = shapeUV[pt * 2 + 1] * (uvs.w - uvs.y) + uvs.y;
  69052. }
  69053. }
  69054. }
  69055. // particle just set invisible : scaled to zero and positioned at the origin
  69056. else {
  69057. particle._stillInvisible = true; // mark the particle as invisible
  69058. for (pt = 0; pt < shape.length; pt++) {
  69059. idx = index + pt * 3;
  69060. colidx = colorIndex + pt * 4;
  69061. uvidx = uvIndex + pt * 2;
  69062. positions32[idx] = positions32[idx + 1] = positions32[idx + 2] = 0;
  69063. normals32[idx] = normals32[idx + 1] = normals32[idx + 2] = 0;
  69064. if (this._computeParticleColor && particle.color) {
  69065. var color = particle.color;
  69066. colors32[colidx] = color.r;
  69067. colors32[colidx + 1] = color.g;
  69068. colors32[colidx + 2] = color.b;
  69069. colors32[colidx + 3] = color.a;
  69070. }
  69071. if (this._computeParticleTexture) {
  69072. var uvs = particle.uvs;
  69073. uvs32[uvidx] = shapeUV[pt * 2] * (uvs.z - uvs.x) + uvs.x;
  69074. uvs32[uvidx + 1] = shapeUV[pt * 2 + 1] * (uvs.w - uvs.y) + uvs.y;
  69075. }
  69076. }
  69077. }
  69078. // if the particle intersections must be computed : update the bbInfo
  69079. if (this._particlesIntersect) {
  69080. var bInfo = particle._boundingInfo;
  69081. var bBox = bInfo.boundingBox;
  69082. var bSphere = bInfo.boundingSphere;
  69083. var modelBoundingInfo = particle._modelBoundingInfo;
  69084. if (!this._bSphereOnly) {
  69085. // place, scale and rotate the particle bbox within the SPS local system, then update it
  69086. var modelBoundingInfoVectors = modelBoundingInfo.boundingBox.vectors;
  69087. var tempMin = tempVectors[1];
  69088. var tempMax = tempVectors[2];
  69089. tempMin.setAll(Number.MAX_VALUE);
  69090. tempMax.setAll(-Number.MAX_VALUE);
  69091. for (var b = 0; b < 8; b++) {
  69092. var scaledX = modelBoundingInfoVectors[b].x * particleScaling.x;
  69093. var scaledY = modelBoundingInfoVectors[b].y * particleScaling.y;
  69094. var scaledZ = modelBoundingInfoVectors[b].z * particleScaling.z;
  69095. var rotatedX = scaledX * particleRotationMatrix[0] + scaledY * particleRotationMatrix[3] + scaledZ * particleRotationMatrix[6];
  69096. var rotatedY = scaledX * particleRotationMatrix[1] + scaledY * particleRotationMatrix[4] + scaledZ * particleRotationMatrix[7];
  69097. var rotatedZ = scaledX * particleRotationMatrix[2] + scaledY * particleRotationMatrix[5] + scaledZ * particleRotationMatrix[8];
  69098. var x = particlePosition.x + camAxisX.x * rotatedX + camAxisY.x * rotatedY + camAxisZ.x * rotatedZ;
  69099. var y = particlePosition.y + camAxisX.y * rotatedX + camAxisY.y * rotatedY + camAxisZ.y * rotatedZ;
  69100. var z = particlePosition.z + camAxisX.z * rotatedX + camAxisY.z * rotatedY + camAxisZ.z * rotatedZ;
  69101. tempMin.minimizeInPlaceFromFloats(x, y, z);
  69102. tempMax.maximizeInPlaceFromFloats(x, y, z);
  69103. }
  69104. bBox.reConstruct(tempMin, tempMax, mesh._worldMatrix);
  69105. }
  69106. // place and scale the particle bouding sphere in the SPS local system, then update it
  69107. var minBbox = modelBoundingInfo.minimum.multiplyToRef(particleScaling, tempVectors[1]);
  69108. var maxBbox = modelBoundingInfo.maximum.multiplyToRef(particleScaling, tempVectors[2]);
  69109. var bSphereCenter = maxBbox.addToRef(minBbox, tempVectors[3]).scaleInPlace(0.5);
  69110. var halfDiag = maxBbox.subtractToRef(minBbox, tempVectors[4]).scaleInPlace(0.5 * this._bSphereRadiusFactor);
  69111. var bSphereMinBbox = bSphereCenter.subtractToRef(halfDiag, tempVectors[1]);
  69112. var bSphereMaxBbox = bSphereCenter.addToRef(halfDiag, tempVectors[2]);
  69113. bSphere.reConstruct(bSphereMinBbox, bSphereMaxBbox, mesh._worldMatrix);
  69114. }
  69115. // increment indexes for the next particle
  69116. index = idx + 3;
  69117. colorIndex = colidx + 4;
  69118. uvIndex = uvidx + 2;
  69119. }
  69120. // if the VBO must be updated
  69121. if (update) {
  69122. if (this._computeParticleColor) {
  69123. mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors32, false, false);
  69124. }
  69125. if (this._computeParticleTexture) {
  69126. mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs32, false, false);
  69127. }
  69128. mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions32, false, false);
  69129. if (!mesh.areNormalsFrozen || mesh.isFacetDataEnabled) {
  69130. if (this._computeParticleVertex || mesh.isFacetDataEnabled) {
  69131. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  69132. var params = mesh.isFacetDataEnabled ? mesh.getFacetDataParameters() : null;
  69133. BABYLON.VertexData.ComputeNormals(positions32, indices32, normals32, params);
  69134. for (var i = 0; i < normals32.length; i++) {
  69135. fixedNormal32[i] = normals32[i];
  69136. }
  69137. }
  69138. if (!mesh.areNormalsFrozen) {
  69139. mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals32, false, false);
  69140. }
  69141. }
  69142. if (this._depthSort && this._depthSortParticles) {
  69143. var depthSortedParticles = this.depthSortedParticles;
  69144. depthSortedParticles.sort(depthSortFunction);
  69145. var dspl = depthSortedParticles.length;
  69146. var sid = 0;
  69147. for (var sorted = 0; sorted < dspl; sorted++) {
  69148. var lind = depthSortedParticles[sorted].indicesLength;
  69149. var sind = depthSortedParticles[sorted].ind;
  69150. for (var i = 0; i < lind; i++) {
  69151. indices32[sid] = indices[sind + i];
  69152. sid++;
  69153. }
  69154. }
  69155. mesh.updateIndices(indices32);
  69156. }
  69157. }
  69158. if (this._computeBoundingBox) {
  69159. if (mesh._boundingInfo) {
  69160. mesh._boundingInfo.reConstruct(minimum, maximum, mesh._worldMatrix);
  69161. }
  69162. else {
  69163. mesh._boundingInfo = new BABYLON.BoundingInfo(minimum, maximum, mesh._worldMatrix);
  69164. }
  69165. }
  69166. this.afterUpdateParticles(start, end, update);
  69167. return this;
  69168. };
  69169. /**
  69170. * Disposes the SPS.
  69171. */
  69172. SolidParticleSystem.prototype.dispose = function () {
  69173. this.mesh.dispose();
  69174. this.vars = null;
  69175. // drop references to internal big arrays for the GC
  69176. this._positions = null;
  69177. this._indices = null;
  69178. this._normals = null;
  69179. this._uvs = null;
  69180. this._colors = null;
  69181. this._indices32 = null;
  69182. this._positions32 = null;
  69183. this._normals32 = null;
  69184. this._fixedNormal32 = null;
  69185. this._uvs32 = null;
  69186. this._colors32 = null;
  69187. this.pickedParticles = null;
  69188. };
  69189. /**
  69190. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  69191. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  69192. * @returns the SPS.
  69193. */
  69194. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  69195. if (!this._isVisibilityBoxLocked) {
  69196. this.mesh.refreshBoundingInfo();
  69197. }
  69198. return this;
  69199. };
  69200. /**
  69201. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  69202. * @param size the size (float) of the visibility box
  69203. * note : this doesn't lock the SPS mesh bounding box.
  69204. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  69205. */
  69206. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  69207. var vis = size / 2;
  69208. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  69209. };
  69210. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  69211. /**
  69212. * Gets whether the SPS as always visible or not
  69213. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  69214. */
  69215. get: function () {
  69216. return this._alwaysVisible;
  69217. },
  69218. /**
  69219. * Sets the SPS as always visible or not
  69220. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  69221. */
  69222. set: function (val) {
  69223. this._alwaysVisible = val;
  69224. this.mesh.alwaysSelectAsActiveMesh = val;
  69225. },
  69226. enumerable: true,
  69227. configurable: true
  69228. });
  69229. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  69230. /**
  69231. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  69232. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  69233. */
  69234. get: function () {
  69235. return this._isVisibilityBoxLocked;
  69236. },
  69237. /**
  69238. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  69239. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  69240. */
  69241. set: function (val) {
  69242. this._isVisibilityBoxLocked = val;
  69243. var boundingInfo = this.mesh.getBoundingInfo();
  69244. boundingInfo.isLocked = val;
  69245. },
  69246. enumerable: true,
  69247. configurable: true
  69248. });
  69249. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  69250. /**
  69251. * Gets if `setParticles()` computes the particle rotations or not.
  69252. * Default value : true. The SPS is faster when it's set to false.
  69253. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  69254. */
  69255. get: function () {
  69256. return this._computeParticleRotation;
  69257. },
  69258. /**
  69259. * Tells to `setParticles()` to compute the particle rotations or not.
  69260. * Default value : true. The SPS is faster when it's set to false.
  69261. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  69262. */
  69263. set: function (val) {
  69264. this._computeParticleRotation = val;
  69265. },
  69266. enumerable: true,
  69267. configurable: true
  69268. });
  69269. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  69270. /**
  69271. * Gets if `setParticles()` computes the particle colors or not.
  69272. * Default value : true. The SPS is faster when it's set to false.
  69273. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  69274. */
  69275. get: function () {
  69276. return this._computeParticleColor;
  69277. },
  69278. /**
  69279. * Tells to `setParticles()` to compute the particle colors or not.
  69280. * Default value : true. The SPS is faster when it's set to false.
  69281. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  69282. */
  69283. set: function (val) {
  69284. this._computeParticleColor = val;
  69285. },
  69286. enumerable: true,
  69287. configurable: true
  69288. });
  69289. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  69290. /**
  69291. * Gets if `setParticles()` computes the particle textures or not.
  69292. * Default value : true. The SPS is faster when it's set to false.
  69293. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  69294. */
  69295. get: function () {
  69296. return this._computeParticleTexture;
  69297. },
  69298. set: function (val) {
  69299. this._computeParticleTexture = val;
  69300. },
  69301. enumerable: true,
  69302. configurable: true
  69303. });
  69304. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  69305. /**
  69306. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  69307. * Default value : false. The SPS is faster when it's set to false.
  69308. * Note : the particle custom vertex positions aren't stored values.
  69309. */
  69310. get: function () {
  69311. return this._computeParticleVertex;
  69312. },
  69313. /**
  69314. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  69315. * Default value : false. The SPS is faster when it's set to false.
  69316. * Note : the particle custom vertex positions aren't stored values.
  69317. */
  69318. set: function (val) {
  69319. this._computeParticleVertex = val;
  69320. },
  69321. enumerable: true,
  69322. configurable: true
  69323. });
  69324. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  69325. /**
  69326. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  69327. */
  69328. get: function () {
  69329. return this._computeBoundingBox;
  69330. },
  69331. /**
  69332. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  69333. */
  69334. set: function (val) {
  69335. this._computeBoundingBox = val;
  69336. },
  69337. enumerable: true,
  69338. configurable: true
  69339. });
  69340. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  69341. /**
  69342. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  69343. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  69344. * Default : `true`
  69345. */
  69346. get: function () {
  69347. return this._depthSortParticles;
  69348. },
  69349. /**
  69350. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  69351. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  69352. * Default : `true`
  69353. */
  69354. set: function (val) {
  69355. this._depthSortParticles = val;
  69356. },
  69357. enumerable: true,
  69358. configurable: true
  69359. });
  69360. // =======================================================================
  69361. // Particle behavior logic
  69362. // these following methods may be overwritten by the user to fit his needs
  69363. /**
  69364. * This function does nothing. It may be overwritten to set all the particle first values.
  69365. * The SPS doesn't call this function, you may have to call it by your own.
  69366. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  69367. */
  69368. SolidParticleSystem.prototype.initParticles = function () {
  69369. };
  69370. /**
  69371. * This function does nothing. It may be overwritten to recycle a particle.
  69372. * The SPS doesn't call this function, you may have to call it by your own.
  69373. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  69374. * @param particle The particle to recycle
  69375. * @returns the recycled particle
  69376. */
  69377. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  69378. return particle;
  69379. };
  69380. /**
  69381. * Updates a particle : this function should be overwritten by the user.
  69382. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  69383. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  69384. * @example : just set a particle position or velocity and recycle conditions
  69385. * @param particle The particle to update
  69386. * @returns the updated particle
  69387. */
  69388. SolidParticleSystem.prototype.updateParticle = function (particle) {
  69389. return particle;
  69390. };
  69391. /**
  69392. * Updates a vertex of a particle : it can be overwritten by the user.
  69393. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  69394. * @param particle the current particle
  69395. * @param vertex the current index of the current particle
  69396. * @param pt the index of the current vertex in the particle shape
  69397. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  69398. * @example : just set a vertex particle position
  69399. * @returns the updated vertex
  69400. */
  69401. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  69402. return vertex;
  69403. };
  69404. /**
  69405. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  69406. * This does nothing and may be overwritten by the user.
  69407. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  69408. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  69409. * @param update the boolean update value actually passed to setParticles()
  69410. */
  69411. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  69412. };
  69413. /**
  69414. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  69415. * This will be passed three parameters.
  69416. * This does nothing and may be overwritten by the user.
  69417. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  69418. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  69419. * @param update the boolean update value actually passed to setParticles()
  69420. */
  69421. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  69422. };
  69423. return SolidParticleSystem;
  69424. }());
  69425. BABYLON.SolidParticleSystem = SolidParticleSystem;
  69426. })(BABYLON || (BABYLON = {}));
  69427. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  69428. var BABYLON;
  69429. (function (BABYLON) {
  69430. /**
  69431. * Class containing static functions to help procedurally build meshes
  69432. */
  69433. var MeshBuilder = /** @class */ (function () {
  69434. function MeshBuilder() {
  69435. }
  69436. MeshBuilder.updateSideOrientation = function (orientation) {
  69437. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  69438. return BABYLON.Mesh.DOUBLESIDE;
  69439. }
  69440. if (orientation === undefined || orientation === null) {
  69441. return BABYLON.Mesh.FRONTSIDE;
  69442. }
  69443. return orientation;
  69444. };
  69445. /**
  69446. * Creates a box mesh
  69447. * * The parameter `size` sets the size (float) of each box side (default 1)
  69448. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value of `size`)
  69449. * * 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)
  69450. * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  69451. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  69452. * * 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
  69453. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  69454. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  69455. * @param name defines the name of the mesh
  69456. * @param options defines the options used to create the mesh
  69457. * @param scene defines the hosting scene
  69458. * @returns the box mesh
  69459. */
  69460. MeshBuilder.CreateBox = function (name, options, scene) {
  69461. if (scene === void 0) { scene = null; }
  69462. var box = new BABYLON.Mesh(name, scene);
  69463. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  69464. box._originalBuilderSideOrientation = options.sideOrientation;
  69465. var vertexData = BABYLON.VertexData.CreateBox(options);
  69466. vertexData.applyToMesh(box, options.updatable);
  69467. return box;
  69468. };
  69469. /**
  69470. * Creates a sphere mesh
  69471. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  69472. * * 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`)
  69473. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  69474. * * 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
  69475. * * 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)
  69476. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  69477. * * 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
  69478. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  69479. * @param name defines the name of the mesh
  69480. * @param options defines the options used to create the mesh
  69481. * @param scene defines the hosting scene
  69482. * @returns the sphere mesh
  69483. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  69484. */
  69485. MeshBuilder.CreateSphere = function (name, options, scene) {
  69486. var sphere = new BABYLON.Mesh(name, scene);
  69487. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  69488. sphere._originalBuilderSideOrientation = options.sideOrientation;
  69489. var vertexData = BABYLON.VertexData.CreateSphere(options);
  69490. vertexData.applyToMesh(sphere, options.updatable);
  69491. return sphere;
  69492. };
  69493. /**
  69494. * Creates a plane polygonal mesh. By default, this is a disc
  69495. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  69496. * * 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
  69497. * * 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
  69498. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  69499. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  69500. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  69501. * @param name defines the name of the mesh
  69502. * @param options defines the options used to create the mesh
  69503. * @param scene defines the hosting scene
  69504. * @returns the plane polygonal mesh
  69505. * @see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  69506. */
  69507. MeshBuilder.CreateDisc = function (name, options, scene) {
  69508. if (scene === void 0) { scene = null; }
  69509. var disc = new BABYLON.Mesh(name, scene);
  69510. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  69511. disc._originalBuilderSideOrientation = options.sideOrientation;
  69512. var vertexData = BABYLON.VertexData.CreateDisc(options);
  69513. vertexData.applyToMesh(disc, options.updatable);
  69514. return disc;
  69515. };
  69516. /**
  69517. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  69518. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  69519. * * 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`)
  69520. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  69521. * * 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
  69522. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  69523. * * 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
  69524. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  69525. * @param name defines the name of the mesh
  69526. * @param options defines the options used to create the mesh
  69527. * @param scene defines the hosting scene
  69528. * @returns the icosahedron mesh
  69529. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  69530. */
  69531. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  69532. var sphere = new BABYLON.Mesh(name, scene);
  69533. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  69534. sphere._originalBuilderSideOrientation = options.sideOrientation;
  69535. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  69536. vertexData.applyToMesh(sphere, options.updatable);
  69537. return sphere;
  69538. };
  69539. /**
  69540. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  69541. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  69542. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  69543. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  69544. * * 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
  69545. * * 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
  69546. * * 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
  69547. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  69548. * * 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
  69549. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  69550. * * 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
  69551. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  69552. * * 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
  69553. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  69554. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  69555. * @param name defines the name of the mesh
  69556. * @param options defines the options used to create the mesh
  69557. * @param scene defines the hosting scene
  69558. * @returns the ribbon mesh
  69559. * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  69560. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  69561. */
  69562. MeshBuilder.CreateRibbon = function (name, options, scene) {
  69563. if (scene === void 0) { scene = null; }
  69564. var pathArray = options.pathArray;
  69565. var closeArray = options.closeArray;
  69566. var closePath = options.closePath;
  69567. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  69568. var instance = options.instance;
  69569. var updatable = options.updatable;
  69570. if (instance) { // existing ribbon instance update
  69571. // positionFunction : ribbon case
  69572. // only pathArray and sideOrientation parameters are taken into account for positions update
  69573. var minimum_1 = BABYLON.Tmp.Vector3[0].setAll(Number.MAX_VALUE);
  69574. var maximum_1 = BABYLON.Tmp.Vector3[1].setAll(-Number.MAX_VALUE);
  69575. var positionFunction = function (positions) {
  69576. var minlg = pathArray[0].length;
  69577. var mesh = instance;
  69578. var i = 0;
  69579. var ns = (mesh._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  69580. for (var si = 1; si <= ns; ++si) {
  69581. for (var p = 0; p < pathArray.length; ++p) {
  69582. var path = pathArray[p];
  69583. var l = path.length;
  69584. minlg = (minlg < l) ? minlg : l;
  69585. for (var j = 0; j < minlg; ++j) {
  69586. var pathPoint = path[j];
  69587. positions[i] = pathPoint.x;
  69588. positions[i + 1] = pathPoint.y;
  69589. positions[i + 2] = pathPoint.z;
  69590. minimum_1.minimizeInPlaceFromFloats(pathPoint.x, pathPoint.y, pathPoint.z);
  69591. maximum_1.maximizeInPlaceFromFloats(pathPoint.x, pathPoint.y, pathPoint.z);
  69592. i += 3;
  69593. }
  69594. if (mesh._creationDataStorage && mesh._creationDataStorage.closePath) {
  69595. var pathPoint = path[0];
  69596. positions[i] = pathPoint.x;
  69597. positions[i + 1] = pathPoint.y;
  69598. positions[i + 2] = pathPoint.z;
  69599. i += 3;
  69600. }
  69601. }
  69602. }
  69603. };
  69604. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  69605. positionFunction(positions);
  69606. if (instance._boundingInfo) {
  69607. instance._boundingInfo.reConstruct(minimum_1, maximum_1, instance._worldMatrix);
  69608. }
  69609. else {
  69610. instance._boundingInfo = new BABYLON.BoundingInfo(minimum_1, maximum_1, instance._worldMatrix);
  69611. }
  69612. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  69613. if (options.colors) {
  69614. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  69615. for (var c = 0, colorIndex = 0; c < options.colors.length; c++, colorIndex += 4) {
  69616. var color = options.colors[c];
  69617. colors[colorIndex] = color.r;
  69618. colors[colorIndex + 1] = color.g;
  69619. colors[colorIndex + 2] = color.b;
  69620. colors[colorIndex + 3] = color.a;
  69621. }
  69622. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  69623. }
  69624. if (options.uvs) {
  69625. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  69626. for (var i = 0; i < options.uvs.length; i++) {
  69627. uvs[i * 2] = options.uvs[i].x;
  69628. uvs[i * 2 + 1] = options.uvs[i].y;
  69629. }
  69630. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  69631. }
  69632. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  69633. var indices = instance.getIndices();
  69634. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  69635. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  69636. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  69637. if (instance._creationDataStorage && instance._creationDataStorage.closePath) {
  69638. var indexFirst = 0;
  69639. var indexLast = 0;
  69640. for (var p = 0; p < pathArray.length; p++) {
  69641. indexFirst = instance._creationDataStorage.idx[p] * 3;
  69642. if (p + 1 < pathArray.length) {
  69643. indexLast = (instance._creationDataStorage.idx[p + 1] - 1) * 3;
  69644. }
  69645. else {
  69646. indexLast = normals.length - 3;
  69647. }
  69648. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  69649. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  69650. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  69651. normals[indexLast] = normals[indexFirst];
  69652. normals[indexLast + 1] = normals[indexFirst + 1];
  69653. normals[indexLast + 2] = normals[indexFirst + 2];
  69654. }
  69655. }
  69656. if (!(instance.areNormalsFrozen)) {
  69657. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  69658. }
  69659. }
  69660. return instance;
  69661. }
  69662. else { // new ribbon creation
  69663. var ribbon = new BABYLON.Mesh(name, scene);
  69664. ribbon._originalBuilderSideOrientation = sideOrientation;
  69665. ribbon._creationDataStorage = new BABYLON._CreationDataStorage();
  69666. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  69667. if (closePath) {
  69668. ribbon._creationDataStorage.idx = vertexData._idx;
  69669. }
  69670. ribbon._creationDataStorage.closePath = closePath;
  69671. ribbon._creationDataStorage.closeArray = closeArray;
  69672. vertexData.applyToMesh(ribbon, updatable);
  69673. return ribbon;
  69674. }
  69675. };
  69676. /**
  69677. * Creates a cylinder or a cone mesh
  69678. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  69679. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  69680. * * 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.
  69681. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  69682. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  69683. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  69684. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  69685. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  69686. * * 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).
  69687. * * 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
  69688. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  69689. * * 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
  69690. * * 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.
  69691. * * If `enclose` is false, a ring surface is one element.
  69692. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  69693. * * 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
  69694. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  69695. * * 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
  69696. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  69697. * @param name defines the name of the mesh
  69698. * @param options defines the options used to create the mesh
  69699. * @param scene defines the hosting scene
  69700. * @returns the cylinder mesh
  69701. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  69702. */
  69703. MeshBuilder.CreateCylinder = function (name, options, scene) {
  69704. var cylinder = new BABYLON.Mesh(name, scene);
  69705. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  69706. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  69707. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  69708. vertexData.applyToMesh(cylinder, options.updatable);
  69709. return cylinder;
  69710. };
  69711. /**
  69712. * Creates a torus mesh
  69713. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  69714. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  69715. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  69716. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  69717. * * 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
  69718. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  69719. * @param name defines the name of the mesh
  69720. * @param options defines the options used to create the mesh
  69721. * @param scene defines the hosting scene
  69722. * @returns the torus mesh
  69723. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  69724. */
  69725. MeshBuilder.CreateTorus = function (name, options, scene) {
  69726. var torus = new BABYLON.Mesh(name, scene);
  69727. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  69728. torus._originalBuilderSideOrientation = options.sideOrientation;
  69729. var vertexData = BABYLON.VertexData.CreateTorus(options);
  69730. vertexData.applyToMesh(torus, options.updatable);
  69731. return torus;
  69732. };
  69733. /**
  69734. * Creates a torus knot mesh
  69735. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  69736. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  69737. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  69738. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  69739. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  69740. * * 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
  69741. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  69742. * @param name defines the name of the mesh
  69743. * @param options defines the options used to create the mesh
  69744. * @param scene defines the hosting scene
  69745. * @returns the torus knot mesh
  69746. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  69747. */
  69748. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  69749. var torusKnot = new BABYLON.Mesh(name, scene);
  69750. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  69751. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  69752. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  69753. vertexData.applyToMesh(torusKnot, options.updatable);
  69754. return torusKnot;
  69755. };
  69756. /**
  69757. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  69758. * * 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
  69759. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  69760. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  69761. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  69762. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  69763. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  69764. * * 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
  69765. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  69766. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  69767. * @see http://doc.babylonjs.com/how_to/parametric_shapes#line-system
  69768. * @param name defines the name of the new line system
  69769. * @param options defines the options used to create the line system
  69770. * @param scene defines the hosting scene
  69771. * @returns a new line system mesh
  69772. */
  69773. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  69774. var instance = options.instance;
  69775. var lines = options.lines;
  69776. var colors = options.colors;
  69777. if (instance) { // lines update
  69778. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  69779. var vertexColor;
  69780. var lineColors;
  69781. if (colors) {
  69782. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  69783. }
  69784. var i = 0;
  69785. var c = 0;
  69786. for (var l = 0; l < lines.length; l++) {
  69787. var points = lines[l];
  69788. for (var p = 0; p < points.length; p++) {
  69789. positions[i] = points[p].x;
  69790. positions[i + 1] = points[p].y;
  69791. positions[i + 2] = points[p].z;
  69792. if (colors && vertexColor) {
  69793. lineColors = colors[l];
  69794. vertexColor[c] = lineColors[p].r;
  69795. vertexColor[c + 1] = lineColors[p].g;
  69796. vertexColor[c + 2] = lineColors[p].b;
  69797. vertexColor[c + 3] = lineColors[p].a;
  69798. c += 4;
  69799. }
  69800. i += 3;
  69801. }
  69802. }
  69803. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  69804. if (colors && vertexColor) {
  69805. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  69806. }
  69807. return instance;
  69808. }
  69809. // line system creation
  69810. var useVertexColor = (colors) ? true : false;
  69811. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  69812. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  69813. vertexData.applyToMesh(lineSystem, options.updatable);
  69814. return lineSystem;
  69815. };
  69816. /**
  69817. * Creates a line mesh
  69818. * 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
  69819. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  69820. * * The parameter `points` is an array successive Vector3
  69821. * * 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
  69822. * * The optional parameter `colors` is an array of successive Color4, one per line point
  69823. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  69824. * * When updating an instance, remember that only point positions can change, not the number of points
  69825. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  69826. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lines
  69827. * @param name defines the name of the new line system
  69828. * @param options defines the options used to create the line system
  69829. * @param scene defines the hosting scene
  69830. * @returns a new line mesh
  69831. */
  69832. MeshBuilder.CreateLines = function (name, options, scene) {
  69833. if (scene === void 0) { scene = null; }
  69834. var colors = (options.colors) ? [options.colors] : null;
  69835. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  69836. return lines;
  69837. };
  69838. /**
  69839. * Creates a dashed line mesh
  69840. * * 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
  69841. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  69842. * * The parameter `points` is an array successive Vector3
  69843. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  69844. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  69845. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  69846. * * 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
  69847. * * When updating an instance, remember that only point positions can change, not the number of points
  69848. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  69849. * @param name defines the name of the mesh
  69850. * @param options defines the options used to create the mesh
  69851. * @param scene defines the hosting scene
  69852. * @returns the dashed line mesh
  69853. * @see http://doc.babylonjs.com/how_to/parametric_shapes#dashed-lines
  69854. */
  69855. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  69856. if (scene === void 0) { scene = null; }
  69857. var points = options.points;
  69858. var instance = options.instance;
  69859. var gapSize = options.gapSize || 1;
  69860. var dashSize = options.dashSize || 3;
  69861. if (instance) { // dashed lines update
  69862. var positionFunction = function (positions) {
  69863. var curvect = BABYLON.Vector3.Zero();
  69864. var nbSeg = positions.length / 6;
  69865. var lg = 0;
  69866. var nb = 0;
  69867. var shft = 0;
  69868. var dashshft = 0;
  69869. var curshft = 0;
  69870. var p = 0;
  69871. var i = 0;
  69872. var j = 0;
  69873. for (i = 0; i < points.length - 1; i++) {
  69874. points[i + 1].subtractToRef(points[i], curvect);
  69875. lg += curvect.length();
  69876. }
  69877. shft = lg / nbSeg;
  69878. var dashSize = instance._creationDataStorage.dashSize;
  69879. var gapSize = instance._creationDataStorage.gapSize;
  69880. dashshft = dashSize * shft / (dashSize + gapSize);
  69881. for (i = 0; i < points.length - 1; i++) {
  69882. points[i + 1].subtractToRef(points[i], curvect);
  69883. nb = Math.floor(curvect.length() / shft);
  69884. curvect.normalize();
  69885. j = 0;
  69886. while (j < nb && p < positions.length) {
  69887. curshft = shft * j;
  69888. positions[p] = points[i].x + curshft * curvect.x;
  69889. positions[p + 1] = points[i].y + curshft * curvect.y;
  69890. positions[p + 2] = points[i].z + curshft * curvect.z;
  69891. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  69892. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  69893. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  69894. p += 6;
  69895. j++;
  69896. }
  69897. }
  69898. while (p < positions.length) {
  69899. positions[p] = points[i].x;
  69900. positions[p + 1] = points[i].y;
  69901. positions[p + 2] = points[i].z;
  69902. p += 3;
  69903. }
  69904. };
  69905. instance.updateMeshPositions(positionFunction, false);
  69906. return instance;
  69907. }
  69908. // dashed lines creation
  69909. var dashedLines = new BABYLON.LinesMesh(name, scene);
  69910. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  69911. vertexData.applyToMesh(dashedLines, options.updatable);
  69912. dashedLines._creationDataStorage = new BABYLON._CreationDataStorage();
  69913. dashedLines._creationDataStorage.dashSize = dashSize;
  69914. dashedLines._creationDataStorage.gapSize = gapSize;
  69915. return dashedLines;
  69916. };
  69917. /**
  69918. * 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.
  69919. * * 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.
  69920. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  69921. * * 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.
  69922. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  69923. * * 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
  69924. * * 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
  69925. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  69926. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  69927. * * 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
  69928. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  69929. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  69930. * @param name defines the name of the mesh
  69931. * @param options defines the options used to create the mesh
  69932. * @param scene defines the hosting scene
  69933. * @returns the extruded shape mesh
  69934. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  69935. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  69936. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  69937. */
  69938. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  69939. if (scene === void 0) { scene = null; }
  69940. var path = options.path;
  69941. var shape = options.shape;
  69942. var scale = options.scale || 1;
  69943. var rotation = options.rotation || 0;
  69944. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  69945. var updatable = options.updatable;
  69946. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  69947. var instance = options.instance || null;
  69948. var invertUV = options.invertUV || false;
  69949. 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);
  69950. };
  69951. /**
  69952. * Creates an custom extruded shape mesh.
  69953. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  69954. * * 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.
  69955. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  69956. * * 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
  69957. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  69958. * * 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
  69959. * * It must returns a float value that will be the scale value applied to the shape on each path point
  69960. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  69961. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  69962. * * 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
  69963. * * 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
  69964. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  69965. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  69966. * * 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
  69967. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  69968. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  69969. * @param name defines the name of the mesh
  69970. * @param options defines the options used to create the mesh
  69971. * @param scene defines the hosting scene
  69972. * @returns the custom extruded shape mesh
  69973. * @see http://doc.babylonjs.com/how_to/parametric_shapes#custom-extruded-shapes
  69974. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  69975. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  69976. */
  69977. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  69978. var path = options.path;
  69979. var shape = options.shape;
  69980. var scaleFunction = options.scaleFunction || (function () { return 1; });
  69981. var rotationFunction = options.rotationFunction || (function () { return 0; });
  69982. var ribbonCloseArray = options.ribbonCloseArray || false;
  69983. var ribbonClosePath = options.ribbonClosePath || false;
  69984. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  69985. var updatable = options.updatable;
  69986. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  69987. var instance = options.instance;
  69988. var invertUV = options.invertUV || false;
  69989. 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);
  69990. };
  69991. /**
  69992. * Creates lathe mesh.
  69993. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  69994. * * 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
  69995. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  69996. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  69997. * * The parameter `clip` (positive integer, default 0) is the number of sides to not create without effecting the general shape of the sides
  69998. * * 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
  69999. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  70000. * * 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
  70001. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  70002. * * 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
  70003. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  70004. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  70005. * @param name defines the name of the mesh
  70006. * @param options defines the options used to create the mesh
  70007. * @param scene defines the hosting scene
  70008. * @returns the lathe mesh
  70009. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lathe
  70010. */
  70011. MeshBuilder.CreateLathe = function (name, options, scene) {
  70012. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  70013. var closed = (options.closed === undefined) ? true : options.closed;
  70014. var shape = options.shape;
  70015. var radius = options.radius || 1;
  70016. var tessellation = options.tessellation || 64;
  70017. var clip = options.clip || 0;
  70018. var updatable = options.updatable;
  70019. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  70020. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  70021. var pi2 = Math.PI * 2;
  70022. var paths = new Array();
  70023. var invertUV = options.invertUV || false;
  70024. var i = 0;
  70025. var p = 0;
  70026. var step = pi2 / tessellation * arc;
  70027. var rotated;
  70028. var path = new Array();
  70029. for (i = 0; i <= tessellation - clip; i++) {
  70030. var path = [];
  70031. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  70032. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  70033. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  70034. }
  70035. for (p = 0; p < shape.length; p++) {
  70036. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  70037. path.push(rotated);
  70038. }
  70039. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  70040. 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));
  70041. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  70042. }
  70043. paths.push(path);
  70044. }
  70045. // lathe ribbon
  70046. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  70047. return lathe;
  70048. };
  70049. /**
  70050. * Creates a plane mesh
  70051. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  70052. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value of `size`)
  70053. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  70054. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  70055. * * 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
  70056. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  70057. * @param name defines the name of the mesh
  70058. * @param options defines the options used to create the mesh
  70059. * @param scene defines the hosting scene
  70060. * @returns the plane mesh
  70061. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  70062. */
  70063. MeshBuilder.CreatePlane = function (name, options, scene) {
  70064. var plane = new BABYLON.Mesh(name, scene);
  70065. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  70066. plane._originalBuilderSideOrientation = options.sideOrientation;
  70067. var vertexData = BABYLON.VertexData.CreatePlane(options);
  70068. vertexData.applyToMesh(plane, options.updatable);
  70069. if (options.sourcePlane) {
  70070. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  70071. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  70072. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  70073. if (vectorProduct.lengthSquared() > BABYLON.Epsilon) {
  70074. plane.rotate(vectorProduct, product);
  70075. }
  70076. }
  70077. return plane;
  70078. };
  70079. /**
  70080. * Creates a ground mesh
  70081. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  70082. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  70083. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  70084. * @param name defines the name of the mesh
  70085. * @param options defines the options used to create the mesh
  70086. * @param scene defines the hosting scene
  70087. * @returns the ground mesh
  70088. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  70089. */
  70090. MeshBuilder.CreateGround = function (name, options, scene) {
  70091. var ground = new BABYLON.GroundMesh(name, scene);
  70092. ground._setReady(false);
  70093. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  70094. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  70095. ground._width = options.width || 1;
  70096. ground._height = options.height || 1;
  70097. ground._maxX = ground._width / 2;
  70098. ground._maxZ = ground._height / 2;
  70099. ground._minX = -ground._maxX;
  70100. ground._minZ = -ground._maxZ;
  70101. var vertexData = BABYLON.VertexData.CreateGround(options);
  70102. vertexData.applyToMesh(ground, options.updatable);
  70103. ground._setReady(true);
  70104. return ground;
  70105. };
  70106. /**
  70107. * Creates a tiled ground mesh
  70108. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  70109. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  70110. * * 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
  70111. * * 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
  70112. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  70113. * @param name defines the name of the mesh
  70114. * @param options defines the options used to create the mesh
  70115. * @param scene defines the hosting scene
  70116. * @returns the tiled ground mesh
  70117. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  70118. */
  70119. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  70120. var tiledGround = new BABYLON.Mesh(name, scene);
  70121. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  70122. vertexData.applyToMesh(tiledGround, options.updatable);
  70123. return tiledGround;
  70124. };
  70125. /**
  70126. * Creates a ground mesh from a height map
  70127. * * The parameter `url` sets the URL of the height map image resource.
  70128. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  70129. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  70130. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  70131. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  70132. * * 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.
  70133. * * 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).
  70134. * * The parameter `alphaFilter` will filter any data where the alpha channel is below this value, defaults 0 (all data visible)
  70135. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  70136. * @param name defines the name of the mesh
  70137. * @param url defines the url to the height map
  70138. * @param options defines the options used to create the mesh
  70139. * @param scene defines the hosting scene
  70140. * @returns the ground mesh
  70141. * @see http://doc.babylonjs.com/babylon101/height_map
  70142. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  70143. */
  70144. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  70145. var width = options.width || 10.0;
  70146. var height = options.height || 10.0;
  70147. var subdivisions = options.subdivisions || 1 | 0;
  70148. var minHeight = options.minHeight || 0.0;
  70149. var maxHeight = options.maxHeight || 1.0;
  70150. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  70151. var alphaFilter = options.alphaFilter || 0.0;
  70152. var updatable = options.updatable;
  70153. var onReady = options.onReady;
  70154. var ground = new BABYLON.GroundMesh(name, scene);
  70155. ground._subdivisionsX = subdivisions;
  70156. ground._subdivisionsY = subdivisions;
  70157. ground._width = width;
  70158. ground._height = height;
  70159. ground._maxX = ground._width / 2.0;
  70160. ground._maxZ = ground._height / 2.0;
  70161. ground._minX = -ground._maxX;
  70162. ground._minZ = -ground._maxZ;
  70163. ground._setReady(false);
  70164. var onload = function (img) {
  70165. // Getting height map data
  70166. var canvas = document.createElement("canvas");
  70167. var context = canvas.getContext("2d");
  70168. if (!context) {
  70169. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  70170. }
  70171. if (scene.isDisposed) {
  70172. return;
  70173. }
  70174. var bufferWidth = img.width;
  70175. var bufferHeight = img.height;
  70176. canvas.width = bufferWidth;
  70177. canvas.height = bufferHeight;
  70178. context.drawImage(img, 0, 0);
  70179. // Create VertexData from map data
  70180. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  70181. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  70182. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  70183. width: width, height: height,
  70184. subdivisions: subdivisions,
  70185. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  70186. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight,
  70187. alphaFilter: alphaFilter
  70188. });
  70189. vertexData.applyToMesh(ground, updatable);
  70190. //execute ready callback, if set
  70191. if (onReady) {
  70192. onReady(ground);
  70193. }
  70194. ground._setReady(true);
  70195. };
  70196. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.offlineProvider);
  70197. return ground;
  70198. };
  70199. /**
  70200. * Creates a polygon mesh
  70201. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  70202. * * 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
  70203. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  70204. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  70205. * * 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)
  70206. * * Remember you can only change the shape positions, not their number when updating a polygon
  70207. * @param name defines the name of the mesh
  70208. * @param options defines the options used to create the mesh
  70209. * @param scene defines the hosting scene
  70210. * @returns the polygon mesh
  70211. */
  70212. MeshBuilder.CreatePolygon = function (name, options, scene) {
  70213. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  70214. var shape = options.shape;
  70215. var holes = options.holes || [];
  70216. var depth = options.depth || 0;
  70217. var contours = [];
  70218. var hole = [];
  70219. for (var i = 0; i < shape.length; i++) {
  70220. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  70221. }
  70222. var epsilon = 0.00000001;
  70223. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  70224. contours.pop();
  70225. }
  70226. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  70227. for (var hNb = 0; hNb < holes.length; hNb++) {
  70228. hole = [];
  70229. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  70230. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  70231. }
  70232. polygonTriangulation.addHole(hole);
  70233. }
  70234. var polygon = polygonTriangulation.build(options.updatable, depth);
  70235. polygon._originalBuilderSideOrientation = options.sideOrientation;
  70236. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  70237. vertexData.applyToMesh(polygon, options.updatable);
  70238. return polygon;
  70239. };
  70240. /**
  70241. * Creates an extruded polygon mesh, with depth in the Y direction.
  70242. * * 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)
  70243. * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  70244. * @param name defines the name of the mesh
  70245. * @param options defines the options used to create the mesh
  70246. * @param scene defines the hosting scene
  70247. * @returns the polygon mesh
  70248. */
  70249. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  70250. return MeshBuilder.CreatePolygon(name, options, scene);
  70251. };
  70252. /**
  70253. * Creates a tube mesh.
  70254. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  70255. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  70256. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  70257. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  70258. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  70259. * * 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)
  70260. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  70261. * * 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
  70262. * * 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
  70263. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  70264. * * 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
  70265. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  70266. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  70267. * @param name defines the name of the mesh
  70268. * @param options defines the options used to create the mesh
  70269. * @param scene defines the hosting scene
  70270. * @returns the tube mesh
  70271. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  70272. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  70273. */
  70274. MeshBuilder.CreateTube = function (name, options, scene) {
  70275. var path = options.path;
  70276. var instance = options.instance;
  70277. var radius = 1.0;
  70278. if (options.radius !== undefined) {
  70279. radius = options.radius;
  70280. }
  70281. else if (instance) {
  70282. radius = instance._creationDataStorage.radius;
  70283. }
  70284. var tessellation = options.tessellation || 64 | 0;
  70285. var radiusFunction = options.radiusFunction || null;
  70286. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  70287. var invertUV = options.invertUV || false;
  70288. var updatable = options.updatable;
  70289. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  70290. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  70291. // tube geometry
  70292. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  70293. var tangents = path3D.getTangents();
  70294. var normals = path3D.getNormals();
  70295. var distances = path3D.getDistances();
  70296. var pi2 = Math.PI * 2;
  70297. var step = pi2 / tessellation * arc;
  70298. var returnRadius = function () { return radius; };
  70299. var radiusFunctionFinal = radiusFunction || returnRadius;
  70300. var circlePath;
  70301. var rad;
  70302. var normal;
  70303. var rotated;
  70304. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  70305. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  70306. for (var i = 0; i < path.length; i++) {
  70307. rad = radiusFunctionFinal(i, distances[i]); // current radius
  70308. circlePath = Array(); // current circle array
  70309. normal = normals[i]; // current normal
  70310. for (var t = 0; t < tessellation; t++) {
  70311. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  70312. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  70313. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  70314. rotated.scaleInPlace(rad).addInPlace(path[i]);
  70315. circlePath[t] = rotated;
  70316. }
  70317. circlePaths[index] = circlePath;
  70318. index++;
  70319. }
  70320. // cap
  70321. var capPath = function (nbPoints, pathIndex) {
  70322. var pointCap = Array();
  70323. for (var i = 0; i < nbPoints; i++) {
  70324. pointCap.push(path[pathIndex]);
  70325. }
  70326. return pointCap;
  70327. };
  70328. switch (cap) {
  70329. case BABYLON.Mesh.NO_CAP:
  70330. break;
  70331. case BABYLON.Mesh.CAP_START:
  70332. circlePaths[0] = capPath(tessellation, 0);
  70333. circlePaths[1] = circlePaths[2].slice(0);
  70334. break;
  70335. case BABYLON.Mesh.CAP_END:
  70336. circlePaths[index] = circlePaths[index - 1].slice(0);
  70337. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  70338. break;
  70339. case BABYLON.Mesh.CAP_ALL:
  70340. circlePaths[0] = capPath(tessellation, 0);
  70341. circlePaths[1] = circlePaths[2].slice(0);
  70342. circlePaths[index] = circlePaths[index - 1].slice(0);
  70343. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  70344. break;
  70345. default:
  70346. break;
  70347. }
  70348. return circlePaths;
  70349. };
  70350. var path3D;
  70351. var pathArray;
  70352. if (instance) { // tube update
  70353. var storage = instance._creationDataStorage;
  70354. var arc = options.arc || storage.arc;
  70355. path3D = storage.path3D.update(path);
  70356. pathArray = tubePathArray(path, path3D, storage.pathArray, radius, storage.tessellation, radiusFunction, storage.cap, arc);
  70357. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  70358. // Update mode, no need to recreate the storage.
  70359. storage.path3D = path3D;
  70360. storage.pathArray = pathArray;
  70361. storage.arc = arc;
  70362. storage.radius = radius;
  70363. return instance;
  70364. }
  70365. // tube creation
  70366. path3D = new BABYLON.Path3D(path);
  70367. var newPathArray = new Array();
  70368. cap = (cap < 0 || cap > 3) ? 0 : cap;
  70369. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  70370. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  70371. tube._creationDataStorage.pathArray = pathArray;
  70372. tube._creationDataStorage.path3D = path3D;
  70373. tube._creationDataStorage.tessellation = tessellation;
  70374. tube._creationDataStorage.cap = cap;
  70375. tube._creationDataStorage.arc = options.arc;
  70376. tube._creationDataStorage.radius = radius;
  70377. return tube;
  70378. };
  70379. /**
  70380. * Creates a polyhedron mesh
  70381. * * 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
  70382. * * The parameter `size` (positive float, default 1) sets the polygon size
  70383. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  70384. * * 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`
  70385. * * 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
  70386. * * 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)`)
  70387. * * 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
  70388. * * 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
  70389. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  70390. * * 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
  70391. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  70392. * @param name defines the name of the mesh
  70393. * @param options defines the options used to create the mesh
  70394. * @param scene defines the hosting scene
  70395. * @returns the polyhedron mesh
  70396. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes
  70397. */
  70398. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  70399. var polyhedron = new BABYLON.Mesh(name, scene);
  70400. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  70401. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  70402. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  70403. vertexData.applyToMesh(polyhedron, options.updatable);
  70404. return polyhedron;
  70405. };
  70406. /**
  70407. * Creates a decal mesh.
  70408. * 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
  70409. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  70410. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  70411. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  70412. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  70413. * @param name defines the name of the mesh
  70414. * @param sourceMesh defines the mesh where the decal must be applied
  70415. * @param options defines the options used to create the mesh
  70416. * @param scene defines the hosting scene
  70417. * @returns the decal mesh
  70418. * @see http://doc.babylonjs.com/how_to/decals
  70419. */
  70420. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  70421. var indices = sourceMesh.getIndices();
  70422. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  70423. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  70424. var position = options.position || BABYLON.Vector3.Zero();
  70425. var normal = options.normal || BABYLON.Vector3.Up();
  70426. var size = options.size || BABYLON.Vector3.One();
  70427. var angle = options.angle || 0;
  70428. // Getting correct rotation
  70429. if (!normal) {
  70430. var target = new BABYLON.Vector3(0, 0, 1);
  70431. var camera = sourceMesh.getScene().activeCamera;
  70432. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  70433. normal = camera.globalPosition.subtract(cameraWorldTarget);
  70434. }
  70435. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  70436. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  70437. var pitch = Math.atan2(normal.y, len);
  70438. // Matrix
  70439. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  70440. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  70441. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  70442. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  70443. var vertexData = new BABYLON.VertexData();
  70444. vertexData.indices = [];
  70445. vertexData.positions = [];
  70446. vertexData.normals = [];
  70447. vertexData.uvs = [];
  70448. var currentVertexDataIndex = 0;
  70449. var extractDecalVector3 = function (indexId) {
  70450. var result = new BABYLON.PositionNormalVertex();
  70451. if (!indices || !positions || !normals) {
  70452. return result;
  70453. }
  70454. var vertexId = indices[indexId];
  70455. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  70456. // Send vector to decal local world
  70457. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  70458. // Get normal
  70459. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  70460. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  70461. return result;
  70462. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  70463. var clip = function (vertices, axis) {
  70464. if (vertices.length === 0) {
  70465. return vertices;
  70466. }
  70467. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  70468. var clipVertices = function (v0, v1) {
  70469. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  70470. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  70471. };
  70472. var result = new Array();
  70473. for (var index = 0; index < vertices.length; index += 3) {
  70474. var v1Out;
  70475. var v2Out;
  70476. var v3Out;
  70477. var total = 0;
  70478. var nV1 = null;
  70479. var nV2 = null;
  70480. var nV3 = null;
  70481. var nV4 = null;
  70482. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  70483. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  70484. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  70485. v1Out = d1 > 0;
  70486. v2Out = d2 > 0;
  70487. v3Out = d3 > 0;
  70488. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  70489. switch (total) {
  70490. case 0:
  70491. result.push(vertices[index]);
  70492. result.push(vertices[index + 1]);
  70493. result.push(vertices[index + 2]);
  70494. break;
  70495. case 1:
  70496. if (v1Out) {
  70497. nV1 = vertices[index + 1];
  70498. nV2 = vertices[index + 2];
  70499. nV3 = clipVertices(vertices[index], nV1);
  70500. nV4 = clipVertices(vertices[index], nV2);
  70501. }
  70502. if (v2Out) {
  70503. nV1 = vertices[index];
  70504. nV2 = vertices[index + 2];
  70505. nV3 = clipVertices(vertices[index + 1], nV1);
  70506. nV4 = clipVertices(vertices[index + 1], nV2);
  70507. result.push(nV3);
  70508. result.push(nV2.clone());
  70509. result.push(nV1.clone());
  70510. result.push(nV2.clone());
  70511. result.push(nV3.clone());
  70512. result.push(nV4);
  70513. break;
  70514. }
  70515. if (v3Out) {
  70516. nV1 = vertices[index];
  70517. nV2 = vertices[index + 1];
  70518. nV3 = clipVertices(vertices[index + 2], nV1);
  70519. nV4 = clipVertices(vertices[index + 2], nV2);
  70520. }
  70521. if (nV1 && nV2 && nV3 && nV4) {
  70522. result.push(nV1.clone());
  70523. result.push(nV2.clone());
  70524. result.push(nV3);
  70525. result.push(nV4);
  70526. result.push(nV3.clone());
  70527. result.push(nV2.clone());
  70528. }
  70529. break;
  70530. case 2:
  70531. if (!v1Out) {
  70532. nV1 = vertices[index].clone();
  70533. nV2 = clipVertices(nV1, vertices[index + 1]);
  70534. nV3 = clipVertices(nV1, vertices[index + 2]);
  70535. result.push(nV1);
  70536. result.push(nV2);
  70537. result.push(nV3);
  70538. }
  70539. if (!v2Out) {
  70540. nV1 = vertices[index + 1].clone();
  70541. nV2 = clipVertices(nV1, vertices[index + 2]);
  70542. nV3 = clipVertices(nV1, vertices[index]);
  70543. result.push(nV1);
  70544. result.push(nV2);
  70545. result.push(nV3);
  70546. }
  70547. if (!v3Out) {
  70548. nV1 = vertices[index + 2].clone();
  70549. nV2 = clipVertices(nV1, vertices[index]);
  70550. nV3 = clipVertices(nV1, vertices[index + 1]);
  70551. result.push(nV1);
  70552. result.push(nV2);
  70553. result.push(nV3);
  70554. }
  70555. break;
  70556. case 3:
  70557. break;
  70558. }
  70559. }
  70560. return result;
  70561. };
  70562. for (var index = 0; index < indices.length; index += 3) {
  70563. var faceVertices = new Array();
  70564. faceVertices.push(extractDecalVector3(index));
  70565. faceVertices.push(extractDecalVector3(index + 1));
  70566. faceVertices.push(extractDecalVector3(index + 2));
  70567. // Clip
  70568. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  70569. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  70570. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  70571. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  70572. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  70573. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  70574. if (faceVertices.length === 0) {
  70575. continue;
  70576. }
  70577. // Add UVs and get back to world
  70578. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  70579. var vertex = faceVertices[vIndex];
  70580. //TODO check for Int32Array | Uint32Array | Uint16Array
  70581. vertexData.indices.push(currentVertexDataIndex);
  70582. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  70583. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  70584. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  70585. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  70586. currentVertexDataIndex++;
  70587. }
  70588. }
  70589. // Return mesh
  70590. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  70591. vertexData.applyToMesh(decal);
  70592. decal.position = position.clone();
  70593. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  70594. return decal;
  70595. };
  70596. // Privates
  70597. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  70598. // extrusion geometry
  70599. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  70600. var tangents = path3D.getTangents();
  70601. var normals = path3D.getNormals();
  70602. var binormals = path3D.getBinormals();
  70603. var distances = path3D.getDistances();
  70604. var angle = 0;
  70605. var returnScale = function () { return scale !== null ? scale : 1; };
  70606. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  70607. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  70608. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  70609. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  70610. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  70611. for (var i = 0; i < curve.length; i++) {
  70612. var shapePath = new Array();
  70613. var angleStep = rotate(i, distances[i]);
  70614. var scaleRatio = scl(i, distances[i]);
  70615. for (var p = 0; p < shape.length; p++) {
  70616. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  70617. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  70618. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  70619. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  70620. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  70621. shapePath[p] = rotated;
  70622. }
  70623. shapePaths[index] = shapePath;
  70624. angle += angleStep;
  70625. index++;
  70626. }
  70627. // cap
  70628. var capPath = function (shapePath) {
  70629. var pointCap = Array();
  70630. var barycenter = BABYLON.Vector3.Zero();
  70631. var i;
  70632. for (i = 0; i < shapePath.length; i++) {
  70633. barycenter.addInPlace(shapePath[i]);
  70634. }
  70635. barycenter.scaleInPlace(1.0 / shapePath.length);
  70636. for (i = 0; i < shapePath.length; i++) {
  70637. pointCap.push(barycenter);
  70638. }
  70639. return pointCap;
  70640. };
  70641. switch (cap) {
  70642. case BABYLON.Mesh.NO_CAP:
  70643. break;
  70644. case BABYLON.Mesh.CAP_START:
  70645. shapePaths[0] = capPath(shapePaths[2]);
  70646. shapePaths[1] = shapePaths[2];
  70647. break;
  70648. case BABYLON.Mesh.CAP_END:
  70649. shapePaths[index] = shapePaths[index - 1];
  70650. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  70651. break;
  70652. case BABYLON.Mesh.CAP_ALL:
  70653. shapePaths[0] = capPath(shapePaths[2]);
  70654. shapePaths[1] = shapePaths[2];
  70655. shapePaths[index] = shapePaths[index - 1];
  70656. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  70657. break;
  70658. default:
  70659. break;
  70660. }
  70661. return shapePaths;
  70662. };
  70663. var path3D;
  70664. var pathArray;
  70665. if (instance) { // instance update
  70666. var storage = instance._creationDataStorage;
  70667. path3D = storage.path3D.update(curve);
  70668. pathArray = extrusionPathArray(shape, curve, storage.path3D, storage.pathArray, scale, rotation, scaleFunction, rotateFunction, storage.cap, custom);
  70669. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  70670. return instance;
  70671. }
  70672. // extruded shape creation
  70673. path3D = new BABYLON.Path3D(curve);
  70674. var newShapePaths = new Array();
  70675. cap = (cap < 0 || cap > 3) ? 0 : cap;
  70676. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  70677. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  70678. extrudedGeneric._creationDataStorage.pathArray = pathArray;
  70679. extrudedGeneric._creationDataStorage.path3D = path3D;
  70680. extrudedGeneric._creationDataStorage.cap = cap;
  70681. return extrudedGeneric;
  70682. };
  70683. return MeshBuilder;
  70684. }());
  70685. BABYLON.MeshBuilder = MeshBuilder;
  70686. })(BABYLON || (BABYLON = {}));
  70687. //# sourceMappingURL=babylon.meshBuilder.js.map
  70688. var BABYLON;
  70689. (function (BABYLON) {
  70690. /**
  70691. * Draco compression (https://google.github.io/draco/)
  70692. *
  70693. * This class wraps the Draco module.
  70694. *
  70695. * **Encoder**
  70696. *
  70697. * The encoder is not currently implemented.
  70698. *
  70699. * **Decoder**
  70700. *
  70701. * 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.
  70702. *
  70703. * To update the configuration, use the following code:
  70704. * ```javascript
  70705. * BABYLON.DracoCompression.Configuration = {
  70706. * decoder: {
  70707. * wasmUrl: "<url to the WebAssembly library>",
  70708. * wasmBinaryUrl: "<url to the WebAssembly binary>",
  70709. * fallbackUrl: "<url to the fallback JavaScript library>",
  70710. * }
  70711. * };
  70712. * ```
  70713. *
  70714. * 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.
  70715. * Decoding will automatically fallback to the JavaScript version if WebAssembly version is not configured or if WebAssembly is not supported by the browser.
  70716. * Use `BABYLON.DracoCompression.DecoderAvailable` to determine if the decoder is available for the current session.
  70717. *
  70718. * To decode Draco compressed data, create a DracoCompression object and call decodeMeshAsync:
  70719. * ```javascript
  70720. * var dracoCompression = new BABYLON.DracoCompression();
  70721. * var vertexData = await dracoCompression.decodeMeshAsync(data, {
  70722. * [BABYLON.VertexBuffer.PositionKind]: 0
  70723. * });
  70724. * ```
  70725. *
  70726. * @see https://www.babylonjs-playground.com/#N3EK4B#0
  70727. */
  70728. var DracoCompression = /** @class */ (function () {
  70729. /**
  70730. * Constructor
  70731. */
  70732. function DracoCompression() {
  70733. }
  70734. Object.defineProperty(DracoCompression, "DecoderAvailable", {
  70735. /**
  70736. * Returns true if the decoder is available.
  70737. */
  70738. get: function () {
  70739. if (typeof DracoDecoderModule !== "undefined") {
  70740. return true;
  70741. }
  70742. var decoder = DracoCompression.Configuration.decoder;
  70743. if (decoder) {
  70744. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  70745. return true;
  70746. }
  70747. if (decoder.fallbackUrl) {
  70748. return true;
  70749. }
  70750. }
  70751. return false;
  70752. },
  70753. enumerable: true,
  70754. configurable: true
  70755. });
  70756. /**
  70757. * Stop all async operations and release resources.
  70758. */
  70759. DracoCompression.prototype.dispose = function () {
  70760. };
  70761. /**
  70762. * Decode Draco compressed mesh data to vertex data.
  70763. * @param data The ArrayBuffer or ArrayBufferView for the Draco compression data
  70764. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  70765. * @returns A promise that resolves with the decoded vertex data
  70766. */
  70767. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  70768. var dataView = data instanceof ArrayBuffer ? new Uint8Array(data) : data;
  70769. return DracoCompression._GetDecoderModule().then(function (wrappedModule) {
  70770. var module = wrappedModule.module;
  70771. var vertexData = new BABYLON.VertexData();
  70772. var buffer = new module.DecoderBuffer();
  70773. buffer.Init(dataView, dataView.byteLength);
  70774. var decoder = new module.Decoder();
  70775. var geometry;
  70776. var status;
  70777. try {
  70778. var type = decoder.GetEncodedGeometryType(buffer);
  70779. switch (type) {
  70780. case module.TRIANGULAR_MESH:
  70781. geometry = new module.Mesh();
  70782. status = decoder.DecodeBufferToMesh(buffer, geometry);
  70783. break;
  70784. case module.POINT_CLOUD:
  70785. geometry = new module.PointCloud();
  70786. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  70787. break;
  70788. default:
  70789. throw new Error("Invalid geometry type " + type);
  70790. }
  70791. if (!status.ok() || !geometry.ptr) {
  70792. throw new Error(status.error_msg());
  70793. }
  70794. var numPoints = geometry.num_points();
  70795. if (type === module.TRIANGULAR_MESH) {
  70796. var numFaces = geometry.num_faces();
  70797. var faceIndices = new module.DracoInt32Array();
  70798. try {
  70799. var indices = new Uint32Array(numFaces * 3);
  70800. for (var i = 0; i < numFaces; i++) {
  70801. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  70802. var offset = i * 3;
  70803. indices[offset + 0] = faceIndices.GetValue(0);
  70804. indices[offset + 1] = faceIndices.GetValue(1);
  70805. indices[offset + 2] = faceIndices.GetValue(2);
  70806. }
  70807. vertexData.indices = indices;
  70808. }
  70809. finally {
  70810. module.destroy(faceIndices);
  70811. }
  70812. }
  70813. for (var kind in attributes) {
  70814. var uniqueId = attributes[kind];
  70815. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  70816. var dracoData = new module.DracoFloat32Array();
  70817. try {
  70818. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  70819. var babylonData = new Float32Array(numPoints * attribute.num_components());
  70820. for (var i = 0; i < babylonData.length; i++) {
  70821. babylonData[i] = dracoData.GetValue(i);
  70822. }
  70823. vertexData.set(babylonData, kind);
  70824. }
  70825. finally {
  70826. module.destroy(dracoData);
  70827. }
  70828. }
  70829. }
  70830. finally {
  70831. if (geometry) {
  70832. module.destroy(geometry);
  70833. }
  70834. module.destroy(decoder);
  70835. module.destroy(buffer);
  70836. }
  70837. return vertexData;
  70838. });
  70839. };
  70840. DracoCompression._GetDecoderModule = function () {
  70841. if (!DracoCompression._DecoderModulePromise) {
  70842. var promise = null;
  70843. var config_1 = {};
  70844. if (typeof DracoDecoderModule !== "undefined") {
  70845. promise = Promise.resolve();
  70846. }
  70847. else {
  70848. var decoder = DracoCompression.Configuration.decoder;
  70849. if (decoder) {
  70850. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  70851. promise = Promise.all([
  70852. DracoCompression._LoadScriptAsync(decoder.wasmUrl),
  70853. DracoCompression._LoadFileAsync(decoder.wasmBinaryUrl).then(function (data) {
  70854. config_1.wasmBinary = data;
  70855. })
  70856. ]);
  70857. }
  70858. else if (decoder.fallbackUrl) {
  70859. promise = DracoCompression._LoadScriptAsync(decoder.fallbackUrl);
  70860. }
  70861. }
  70862. }
  70863. if (!promise) {
  70864. throw new Error("Draco decoder module is not available");
  70865. }
  70866. DracoCompression._DecoderModulePromise = promise.then(function () {
  70867. return new Promise(function (resolve) {
  70868. config_1.onModuleLoaded = function (decoderModule) {
  70869. // decoderModule is Promise-like. Wrap before resolving to avoid loop.
  70870. resolve({ module: decoderModule });
  70871. };
  70872. DracoDecoderModule(config_1);
  70873. });
  70874. });
  70875. }
  70876. return DracoCompression._DecoderModulePromise;
  70877. };
  70878. DracoCompression._LoadScriptAsync = function (url) {
  70879. return new Promise(function (resolve, reject) {
  70880. BABYLON.Tools.LoadScript(url, function () {
  70881. resolve();
  70882. }, function (message) {
  70883. reject(new Error(message));
  70884. });
  70885. });
  70886. };
  70887. DracoCompression._LoadFileAsync = function (url) {
  70888. return new Promise(function (resolve, reject) {
  70889. BABYLON.Tools.LoadFile(url, function (data) {
  70890. resolve(data);
  70891. }, undefined, undefined, true, function (request, exception) {
  70892. reject(exception);
  70893. });
  70894. });
  70895. };
  70896. /**
  70897. * The configuration. Defaults to the following urls:
  70898. * - wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js"
  70899. * - wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm"
  70900. * - fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  70901. */
  70902. DracoCompression.Configuration = {
  70903. decoder: {
  70904. wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",
  70905. wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm",
  70906. fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  70907. }
  70908. };
  70909. return DracoCompression;
  70910. }());
  70911. BABYLON.DracoCompression = DracoCompression;
  70912. })(BABYLON || (BABYLON = {}));
  70913. //# sourceMappingURL=babylon.dracoCompression.js.map
  70914. var BABYLON;
  70915. (function (BABYLON) {
  70916. // Sets the default audio engine to Babylon.js
  70917. BABYLON.Engine.AudioEngineFactory = function (hostElement) { return new AudioEngine(hostElement); };
  70918. /**
  70919. * This represents the default audio engine used in babylon.
  70920. * It is responsible to play, synchronize and analyse sounds throughout the application.
  70921. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  70922. */
  70923. var AudioEngine = /** @class */ (function () {
  70924. /**
  70925. * Instantiates a new audio engine.
  70926. *
  70927. * There should be only one per page as some browsers restrict the number
  70928. * of audio contexts you can create.
  70929. * @param hostElement defines the host element where to display the mute icon if necessary
  70930. */
  70931. function AudioEngine(hostElement) {
  70932. if (hostElement === void 0) { hostElement = null; }
  70933. var _this = this;
  70934. this._audioContext = null;
  70935. this._audioContextInitialized = false;
  70936. this._muteButton = null;
  70937. /**
  70938. * Gets whether the current host supports Web Audio and thus could create AudioContexts.
  70939. */
  70940. this.canUseWebAudio = false;
  70941. /**
  70942. * Defines if Babylon should emit a warning if WebAudio is not supported.
  70943. * @ignoreNaming
  70944. */
  70945. this.WarnedWebAudioUnsupported = false;
  70946. /**
  70947. * Gets whether or not mp3 are supported by your browser.
  70948. */
  70949. this.isMP3supported = false;
  70950. /**
  70951. * Gets whether or not ogg are supported by your browser.
  70952. */
  70953. this.isOGGsupported = false;
  70954. /**
  70955. * Gets whether audio has been unlocked on the device.
  70956. * Some Browsers have strong restrictions about Audio and won t autoplay unless
  70957. * a user interaction has happened.
  70958. */
  70959. this.unlocked = true;
  70960. /**
  70961. * Defines if the audio engine relies on a custom unlocked button.
  70962. * In this case, the embedded button will not be displayed.
  70963. */
  70964. this.useCustomUnlockedButton = false;
  70965. /**
  70966. * Event raised when audio has been unlocked on the browser.
  70967. */
  70968. this.onAudioUnlockedObservable = new BABYLON.Observable();
  70969. /**
  70970. * Event raised when audio has been locked on the browser.
  70971. */
  70972. this.onAudioLockedObservable = new BABYLON.Observable();
  70973. this._tryToRun = false;
  70974. this._onResize = function () {
  70975. _this._moveButtonToTopLeft();
  70976. };
  70977. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  70978. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  70979. this.canUseWebAudio = true;
  70980. }
  70981. var audioElem = document.createElement('audio');
  70982. this._hostElement = hostElement;
  70983. try {
  70984. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  70985. this.isMP3supported = true;
  70986. }
  70987. }
  70988. catch (e) {
  70989. // protect error during capability check.
  70990. }
  70991. try {
  70992. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  70993. this.isOGGsupported = true;
  70994. }
  70995. }
  70996. catch (e) {
  70997. // protect error during capability check.
  70998. }
  70999. }
  71000. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  71001. /**
  71002. * Gets the current AudioContext if available.
  71003. */
  71004. get: function () {
  71005. if (!this._audioContextInitialized) {
  71006. this._initializeAudioContext();
  71007. }
  71008. else {
  71009. if (!this.unlocked && !this._muteButton) {
  71010. this._displayMuteButton();
  71011. }
  71012. }
  71013. return this._audioContext;
  71014. },
  71015. enumerable: true,
  71016. configurable: true
  71017. });
  71018. /**
  71019. * Flags the audio engine in Locked state.
  71020. * This happens due to new browser policies preventing audio to autoplay.
  71021. */
  71022. AudioEngine.prototype.lock = function () {
  71023. this._triggerSuspendedState();
  71024. };
  71025. /**
  71026. * Unlocks the audio engine once a user action has been done on the dom.
  71027. * This is helpful to resume play once browser policies have been satisfied.
  71028. */
  71029. AudioEngine.prototype.unlock = function () {
  71030. this._triggerRunningState();
  71031. };
  71032. AudioEngine.prototype._resumeAudioContext = function () {
  71033. var result;
  71034. if (this._audioContext.resume) {
  71035. result = this._audioContext.resume();
  71036. }
  71037. return result || Promise.resolve();
  71038. };
  71039. AudioEngine.prototype._initializeAudioContext = function () {
  71040. try {
  71041. if (this.canUseWebAudio) {
  71042. this._audioContext = new AudioContext();
  71043. // create a global volume gain node
  71044. this.masterGain = this._audioContext.createGain();
  71045. this.masterGain.gain.value = 1;
  71046. this.masterGain.connect(this._audioContext.destination);
  71047. this._audioContextInitialized = true;
  71048. if (this._audioContext.state === "running") {
  71049. // Do not wait for the promise to unlock.
  71050. this._triggerRunningState();
  71051. }
  71052. }
  71053. }
  71054. catch (e) {
  71055. this.canUseWebAudio = false;
  71056. BABYLON.Tools.Error("Web Audio: " + e.message);
  71057. }
  71058. };
  71059. AudioEngine.prototype._triggerRunningState = function () {
  71060. var _this = this;
  71061. if (this._tryToRun) {
  71062. return;
  71063. }
  71064. this._tryToRun = true;
  71065. this._resumeAudioContext()
  71066. .then(function () {
  71067. _this._tryToRun = false;
  71068. if (_this._muteButton) {
  71069. _this._hideMuteButton();
  71070. }
  71071. }).catch(function () {
  71072. _this._tryToRun = false;
  71073. _this.unlocked = false;
  71074. });
  71075. // Notify users that the audio stack is unlocked/unmuted
  71076. this.unlocked = true;
  71077. this.onAudioUnlockedObservable.notifyObservers(this);
  71078. };
  71079. AudioEngine.prototype._triggerSuspendedState = function () {
  71080. this.unlocked = false;
  71081. this.onAudioLockedObservable.notifyObservers(this);
  71082. this._displayMuteButton();
  71083. };
  71084. AudioEngine.prototype._displayMuteButton = function () {
  71085. var _this = this;
  71086. if (this.useCustomUnlockedButton) {
  71087. return;
  71088. }
  71089. this._muteButton = document.createElement("BUTTON");
  71090. this._muteButton.className = "babylonUnmuteIcon";
  71091. this._muteButton.id = "babylonUnmuteIconBtn";
  71092. this._muteButton.title = "Unmute";
  71093. 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) }";
  71094. var style = document.createElement('style');
  71095. style.appendChild(document.createTextNode(css));
  71096. document.getElementsByTagName('head')[0].appendChild(style);
  71097. document.body.appendChild(this._muteButton);
  71098. this._moveButtonToTopLeft();
  71099. this._muteButton.addEventListener('touchend', function () {
  71100. _this._triggerRunningState();
  71101. }, true);
  71102. this._muteButton.addEventListener('click', function () {
  71103. _this._triggerRunningState();
  71104. }, true);
  71105. window.addEventListener("resize", this._onResize);
  71106. };
  71107. AudioEngine.prototype._moveButtonToTopLeft = function () {
  71108. if (this._hostElement && this._muteButton) {
  71109. this._muteButton.style.top = this._hostElement.offsetTop + 20 + "px";
  71110. this._muteButton.style.left = this._hostElement.offsetLeft + 20 + "px";
  71111. }
  71112. };
  71113. AudioEngine.prototype._hideMuteButton = function () {
  71114. if (this._muteButton) {
  71115. document.body.removeChild(this._muteButton);
  71116. this._muteButton = null;
  71117. }
  71118. };
  71119. /**
  71120. * Destroy and release the resources associated with the audio ccontext.
  71121. */
  71122. AudioEngine.prototype.dispose = function () {
  71123. if (this.canUseWebAudio && this._audioContextInitialized) {
  71124. if (this._connectedAnalyser && this._audioContext) {
  71125. this._connectedAnalyser.stopDebugCanvas();
  71126. this._connectedAnalyser.dispose();
  71127. this.masterGain.disconnect();
  71128. this.masterGain.connect(this._audioContext.destination);
  71129. this._connectedAnalyser = null;
  71130. }
  71131. this.masterGain.gain.value = 1;
  71132. }
  71133. this.WarnedWebAudioUnsupported = false;
  71134. this._hideMuteButton();
  71135. window.removeEventListener("resize", this._onResize);
  71136. this.onAudioUnlockedObservable.clear();
  71137. this.onAudioLockedObservable.clear();
  71138. };
  71139. /**
  71140. * Gets the global volume sets on the master gain.
  71141. * @returns the global volume if set or -1 otherwise
  71142. */
  71143. AudioEngine.prototype.getGlobalVolume = function () {
  71144. if (this.canUseWebAudio && this._audioContextInitialized) {
  71145. return this.masterGain.gain.value;
  71146. }
  71147. else {
  71148. return -1;
  71149. }
  71150. };
  71151. /**
  71152. * Sets the global volume of your experience (sets on the master gain).
  71153. * @param newVolume Defines the new global volume of the application
  71154. */
  71155. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  71156. if (this.canUseWebAudio && this._audioContextInitialized) {
  71157. this.masterGain.gain.value = newVolume;
  71158. }
  71159. };
  71160. /**
  71161. * Connect the audio engine to an audio analyser allowing some amazing
  71162. * synchornization between the sounds/music and your visualization (VuMeter for instance).
  71163. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#using-the-analyser
  71164. * @param analyser The analyser to connect to the engine
  71165. */
  71166. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  71167. if (this._connectedAnalyser) {
  71168. this._connectedAnalyser.stopDebugCanvas();
  71169. }
  71170. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  71171. this._connectedAnalyser = analyser;
  71172. this.masterGain.disconnect();
  71173. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  71174. }
  71175. };
  71176. return AudioEngine;
  71177. }());
  71178. BABYLON.AudioEngine = AudioEngine;
  71179. })(BABYLON || (BABYLON = {}));
  71180. //# sourceMappingURL=babylon.audioEngine.js.map
  71181. var BABYLON;
  71182. (function (BABYLON) {
  71183. /**
  71184. * Defines a sound that can be played in the application.
  71185. * The sound can either be an ambient track or a simple sound played in reaction to a user action.
  71186. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  71187. */
  71188. var Sound = /** @class */ (function () {
  71189. /**
  71190. * Create a sound and attach it to a scene
  71191. * @param name Name of your sound
  71192. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer, it also works with MediaStreams
  71193. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  71194. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  71195. */
  71196. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  71197. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  71198. var _this = this;
  71199. /**
  71200. * Does the sound autoplay once loaded.
  71201. */
  71202. this.autoplay = false;
  71203. /**
  71204. * Does the sound loop after it finishes playing once.
  71205. */
  71206. this.loop = false;
  71207. /**
  71208. * Does the sound use a custom attenuation curve to simulate the falloff
  71209. * happening when the source gets further away from the camera.
  71210. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-your-own-custom-attenuation-function
  71211. */
  71212. this.useCustomAttenuation = false;
  71213. /**
  71214. * Is this sound currently played.
  71215. */
  71216. this.isPlaying = false;
  71217. /**
  71218. * Is this sound currently paused.
  71219. */
  71220. this.isPaused = false;
  71221. /**
  71222. * Does this sound enables spatial sound.
  71223. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  71224. */
  71225. this.spatialSound = false;
  71226. /**
  71227. * Define the reference distance the sound should be heard perfectly.
  71228. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  71229. */
  71230. this.refDistance = 1;
  71231. /**
  71232. * Define the roll off factor of spatial sounds.
  71233. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  71234. */
  71235. this.rolloffFactor = 1;
  71236. /**
  71237. * Define the max distance the sound should be heard (intensity just became 0 at this point).
  71238. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  71239. */
  71240. this.maxDistance = 100;
  71241. /**
  71242. * Define the distance attenuation model the sound will follow.
  71243. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  71244. */
  71245. this.distanceModel = "linear";
  71246. /**
  71247. * Observable event when the current playing sound finishes.
  71248. */
  71249. this.onEndedObservable = new BABYLON.Observable();
  71250. this._panningModel = "equalpower";
  71251. this._playbackRate = 1;
  71252. this._streaming = false;
  71253. this._startTime = 0;
  71254. this._startOffset = 0;
  71255. this._position = BABYLON.Vector3.Zero();
  71256. /** @hidden */
  71257. this._positionInEmitterSpace = false;
  71258. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  71259. this._volume = 1;
  71260. this._isReadyToPlay = false;
  71261. this._isDirectional = false;
  71262. // Used if you'd like to create a directional sound.
  71263. // If not set, the sound will be omnidirectional
  71264. this._coneInnerAngle = 360;
  71265. this._coneOuterAngle = 360;
  71266. this._coneOuterGain = 0;
  71267. this._isOutputConnected = false;
  71268. this._urlType = "Unknown";
  71269. this.name = name;
  71270. this._scene = scene;
  71271. var compo = scene._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  71272. if (!compo) {
  71273. compo = new BABYLON.AudioSceneComponent(scene);
  71274. scene._addComponent(compo);
  71275. }
  71276. this._readyToPlayCallback = readyToPlayCallback;
  71277. // Default custom attenuation function is a linear attenuation
  71278. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  71279. if (currentDistance < maxDistance) {
  71280. return currentVolume * (1 - currentDistance / maxDistance);
  71281. }
  71282. else {
  71283. return 0;
  71284. }
  71285. };
  71286. if (options) {
  71287. this.autoplay = options.autoplay || false;
  71288. this.loop = options.loop || false;
  71289. // if volume === 0, we need another way to check this option
  71290. if (options.volume !== undefined) {
  71291. this._volume = options.volume;
  71292. }
  71293. this.spatialSound = options.spatialSound || false;
  71294. this.maxDistance = options.maxDistance || 100;
  71295. this.useCustomAttenuation = options.useCustomAttenuation || false;
  71296. this.rolloffFactor = options.rolloffFactor || 1;
  71297. this.refDistance = options.refDistance || 1;
  71298. this.distanceModel = options.distanceModel || "linear";
  71299. this._playbackRate = options.playbackRate || 1;
  71300. this._streaming = options.streaming || false;
  71301. }
  71302. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  71303. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  71304. this._soundGain.gain.value = this._volume;
  71305. this._inputAudioNode = this._soundGain;
  71306. this._outputAudioNode = this._soundGain;
  71307. if (this.spatialSound) {
  71308. this._createSpatialParameters();
  71309. }
  71310. this._scene.mainSoundTrack.AddSound(this);
  71311. var validParameter = true;
  71312. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  71313. if (urlOrArrayBuffer) {
  71314. try {
  71315. if (typeof (urlOrArrayBuffer) === "string") {
  71316. this._urlType = "String";
  71317. }
  71318. else if (urlOrArrayBuffer instanceof ArrayBuffer) {
  71319. this._urlType = "ArrayBuffer";
  71320. }
  71321. else if (urlOrArrayBuffer instanceof MediaStream) {
  71322. this._urlType = "MediaStream";
  71323. }
  71324. else if (Array.isArray(urlOrArrayBuffer)) {
  71325. this._urlType = "Array";
  71326. }
  71327. var urls = [];
  71328. var codecSupportedFound = false;
  71329. switch (this._urlType) {
  71330. case "MediaStream":
  71331. this._streaming = true;
  71332. this._isReadyToPlay = true;
  71333. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(urlOrArrayBuffer);
  71334. if (this.autoplay) {
  71335. this.play();
  71336. }
  71337. if (this._readyToPlayCallback) {
  71338. this._readyToPlayCallback();
  71339. }
  71340. break;
  71341. case "ArrayBuffer":
  71342. if (urlOrArrayBuffer.byteLength > 0) {
  71343. codecSupportedFound = true;
  71344. this._soundLoaded(urlOrArrayBuffer);
  71345. }
  71346. break;
  71347. case "String":
  71348. urls.push(urlOrArrayBuffer);
  71349. case "Array":
  71350. if (urls.length === 0) {
  71351. urls = urlOrArrayBuffer;
  71352. }
  71353. // If we found a supported format, we load it immediately and stop the loop
  71354. for (var i = 0; i < urls.length; i++) {
  71355. var url = urls[i];
  71356. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  71357. codecSupportedFound = true;
  71358. }
  71359. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  71360. codecSupportedFound = true;
  71361. }
  71362. if (url.indexOf(".wav", url.length - 4) !== -1) {
  71363. codecSupportedFound = true;
  71364. }
  71365. if (url.indexOf("blob:") !== -1) {
  71366. codecSupportedFound = true;
  71367. }
  71368. if (codecSupportedFound) {
  71369. // Loading sound using XHR2
  71370. if (!this._streaming) {
  71371. this._scene._loadFile(url, function (data) {
  71372. _this._soundLoaded(data);
  71373. }, undefined, true, true, function (exception) {
  71374. if (exception) {
  71375. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  71376. }
  71377. BABYLON.Tools.Error("Sound creation aborted.");
  71378. _this._scene.mainSoundTrack.RemoveSound(_this);
  71379. });
  71380. }
  71381. // Streaming sound using HTML5 Audio tag
  71382. else {
  71383. this._htmlAudioElement = new Audio(url);
  71384. this._htmlAudioElement.controls = false;
  71385. this._htmlAudioElement.loop = this.loop;
  71386. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  71387. this._htmlAudioElement.preload = "auto";
  71388. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  71389. _this._isReadyToPlay = true;
  71390. if (_this.autoplay) {
  71391. _this.play();
  71392. }
  71393. if (_this._readyToPlayCallback) {
  71394. _this._readyToPlayCallback();
  71395. }
  71396. });
  71397. document.body.appendChild(this._htmlAudioElement);
  71398. this._htmlAudioElement.load();
  71399. }
  71400. break;
  71401. }
  71402. }
  71403. break;
  71404. default:
  71405. validParameter = false;
  71406. break;
  71407. }
  71408. if (!validParameter) {
  71409. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  71410. }
  71411. else {
  71412. if (!codecSupportedFound) {
  71413. this._isReadyToPlay = true;
  71414. // Simulating a ready to play event to avoid breaking code path
  71415. if (this._readyToPlayCallback) {
  71416. window.setTimeout(function () {
  71417. if (_this._readyToPlayCallback) {
  71418. _this._readyToPlayCallback();
  71419. }
  71420. }, 1000);
  71421. }
  71422. }
  71423. }
  71424. }
  71425. catch (ex) {
  71426. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  71427. this._scene.mainSoundTrack.RemoveSound(this);
  71428. }
  71429. }
  71430. }
  71431. else {
  71432. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  71433. this._scene.mainSoundTrack.AddSound(this);
  71434. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  71435. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  71436. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  71437. }
  71438. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  71439. if (this._readyToPlayCallback) {
  71440. window.setTimeout(function () {
  71441. if (_this._readyToPlayCallback) {
  71442. _this._readyToPlayCallback();
  71443. }
  71444. }, 1000);
  71445. }
  71446. }
  71447. }
  71448. /**
  71449. * Release the sound and its associated resources
  71450. */
  71451. Sound.prototype.dispose = function () {
  71452. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  71453. if (this.isPlaying) {
  71454. this.stop();
  71455. }
  71456. this._isReadyToPlay = false;
  71457. if (this.soundTrackId === -1) {
  71458. this._scene.mainSoundTrack.RemoveSound(this);
  71459. }
  71460. else if (this._scene.soundTracks) {
  71461. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  71462. }
  71463. if (this._soundGain) {
  71464. this._soundGain.disconnect();
  71465. this._soundGain = null;
  71466. }
  71467. if (this._soundPanner) {
  71468. this._soundPanner.disconnect();
  71469. this._soundPanner = null;
  71470. }
  71471. if (this._soundSource) {
  71472. this._soundSource.disconnect();
  71473. this._soundSource = null;
  71474. }
  71475. this._audioBuffer = null;
  71476. if (this._htmlAudioElement) {
  71477. this._htmlAudioElement.pause();
  71478. this._htmlAudioElement.src = "";
  71479. document.body.removeChild(this._htmlAudioElement);
  71480. }
  71481. if (this._streamingSource) {
  71482. this._streamingSource.disconnect();
  71483. }
  71484. if (this._connectedTransformNode && this._registerFunc) {
  71485. this._connectedTransformNode.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  71486. this._connectedTransformNode = null;
  71487. }
  71488. }
  71489. };
  71490. /**
  71491. * Gets if the sounds is ready to be played or not.
  71492. * @returns true if ready, otherwise false
  71493. */
  71494. Sound.prototype.isReady = function () {
  71495. return this._isReadyToPlay;
  71496. };
  71497. Sound.prototype._soundLoaded = function (audioData) {
  71498. var _this = this;
  71499. if (!BABYLON.Engine.audioEngine.audioContext) {
  71500. return;
  71501. }
  71502. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  71503. _this._audioBuffer = buffer;
  71504. _this._isReadyToPlay = true;
  71505. if (_this.autoplay) {
  71506. _this.play();
  71507. }
  71508. if (_this._readyToPlayCallback) {
  71509. _this._readyToPlayCallback();
  71510. }
  71511. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  71512. };
  71513. /**
  71514. * Sets the data of the sound from an audiobuffer
  71515. * @param audioBuffer The audioBuffer containing the data
  71516. */
  71517. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  71518. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  71519. this._audioBuffer = audioBuffer;
  71520. this._isReadyToPlay = true;
  71521. }
  71522. };
  71523. /**
  71524. * Updates the current sounds options such as maxdistance, loop...
  71525. * @param options A JSON object containing values named as the object properties
  71526. */
  71527. Sound.prototype.updateOptions = function (options) {
  71528. if (options) {
  71529. this.loop = options.loop || this.loop;
  71530. this.maxDistance = options.maxDistance || this.maxDistance;
  71531. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  71532. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  71533. this.refDistance = options.refDistance || this.refDistance;
  71534. this.distanceModel = options.distanceModel || this.distanceModel;
  71535. this._playbackRate = options.playbackRate || this._playbackRate;
  71536. this._updateSpatialParameters();
  71537. if (this.isPlaying) {
  71538. if (this._streaming && this._htmlAudioElement) {
  71539. this._htmlAudioElement.playbackRate = this._playbackRate;
  71540. }
  71541. else {
  71542. if (this._soundSource) {
  71543. this._soundSource.playbackRate.value = this._playbackRate;
  71544. }
  71545. }
  71546. }
  71547. }
  71548. };
  71549. Sound.prototype._createSpatialParameters = function () {
  71550. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  71551. if (this._scene.headphone) {
  71552. this._panningModel = "HRTF";
  71553. }
  71554. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  71555. this._updateSpatialParameters();
  71556. this._soundPanner.connect(this._outputAudioNode);
  71557. this._inputAudioNode = this._soundPanner;
  71558. }
  71559. };
  71560. Sound.prototype._updateSpatialParameters = function () {
  71561. if (this.spatialSound && this._soundPanner) {
  71562. if (this.useCustomAttenuation) {
  71563. // Tricks to disable in a way embedded Web Audio attenuation
  71564. this._soundPanner.distanceModel = "linear";
  71565. this._soundPanner.maxDistance = Number.MAX_VALUE;
  71566. this._soundPanner.refDistance = 1;
  71567. this._soundPanner.rolloffFactor = 1;
  71568. this._soundPanner.panningModel = this._panningModel;
  71569. }
  71570. else {
  71571. this._soundPanner.distanceModel = this.distanceModel;
  71572. this._soundPanner.maxDistance = this.maxDistance;
  71573. this._soundPanner.refDistance = this.refDistance;
  71574. this._soundPanner.rolloffFactor = this.rolloffFactor;
  71575. this._soundPanner.panningModel = this._panningModel;
  71576. }
  71577. }
  71578. };
  71579. /**
  71580. * Switch the panning model to HRTF:
  71581. * Renders a stereo output of higher quality than equalpower — it uses a convolution with measured impulse responses from human subjects.
  71582. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  71583. */
  71584. Sound.prototype.switchPanningModelToHRTF = function () {
  71585. this._panningModel = "HRTF";
  71586. this._switchPanningModel();
  71587. };
  71588. /**
  71589. * Switch the panning model to Equal Power:
  71590. * Represents the equal-power panning algorithm, generally regarded as simple and efficient. equalpower is the default value.
  71591. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  71592. */
  71593. Sound.prototype.switchPanningModelToEqualPower = function () {
  71594. this._panningModel = "equalpower";
  71595. this._switchPanningModel();
  71596. };
  71597. Sound.prototype._switchPanningModel = function () {
  71598. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  71599. this._soundPanner.panningModel = this._panningModel;
  71600. }
  71601. };
  71602. /**
  71603. * Connect this sound to a sound track audio node like gain...
  71604. * @param soundTrackAudioNode the sound track audio node to connect to
  71605. */
  71606. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  71607. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  71608. if (this._isOutputConnected) {
  71609. this._outputAudioNode.disconnect();
  71610. }
  71611. this._outputAudioNode.connect(soundTrackAudioNode);
  71612. this._isOutputConnected = true;
  71613. }
  71614. };
  71615. /**
  71616. * Transform this sound into a directional source
  71617. * @param coneInnerAngle Size of the inner cone in degree
  71618. * @param coneOuterAngle Size of the outer cone in degree
  71619. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  71620. */
  71621. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  71622. if (coneOuterAngle < coneInnerAngle) {
  71623. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  71624. return;
  71625. }
  71626. this._coneInnerAngle = coneInnerAngle;
  71627. this._coneOuterAngle = coneOuterAngle;
  71628. this._coneOuterGain = coneOuterGain;
  71629. this._isDirectional = true;
  71630. if (this.isPlaying && this.loop) {
  71631. this.stop();
  71632. this.play();
  71633. }
  71634. };
  71635. Object.defineProperty(Sound.prototype, "directionalConeInnerAngle", {
  71636. /**
  71637. * Gets or sets the inner angle for the directional cone.
  71638. */
  71639. get: function () {
  71640. return this._coneInnerAngle;
  71641. },
  71642. /**
  71643. * Gets or sets the inner angle for the directional cone.
  71644. */
  71645. set: function (value) {
  71646. if (value != this._coneInnerAngle) {
  71647. if (this._coneOuterAngle < value) {
  71648. BABYLON.Tools.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");
  71649. return;
  71650. }
  71651. this._coneInnerAngle = value;
  71652. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  71653. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  71654. }
  71655. }
  71656. },
  71657. enumerable: true,
  71658. configurable: true
  71659. });
  71660. Object.defineProperty(Sound.prototype, "directionalConeOuterAngle", {
  71661. /**
  71662. * Gets or sets the outer angle for the directional cone.
  71663. */
  71664. get: function () {
  71665. return this._coneOuterAngle;
  71666. },
  71667. /**
  71668. * Gets or sets the outer angle for the directional cone.
  71669. */
  71670. set: function (value) {
  71671. if (value != this._coneOuterAngle) {
  71672. if (value < this._coneInnerAngle) {
  71673. BABYLON.Tools.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");
  71674. return;
  71675. }
  71676. this._coneOuterAngle = value;
  71677. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  71678. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  71679. }
  71680. }
  71681. },
  71682. enumerable: true,
  71683. configurable: true
  71684. });
  71685. /**
  71686. * Sets the position of the emitter if spatial sound is enabled
  71687. * @param newPosition Defines the new posisiton
  71688. */
  71689. Sound.prototype.setPosition = function (newPosition) {
  71690. this._position = newPosition;
  71691. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner && !isNaN(this._position.x) && !isNaN(this._position.y) && !isNaN(this._position.z)) {
  71692. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  71693. }
  71694. };
  71695. /**
  71696. * Sets the local direction of the emitter if spatial sound is enabled
  71697. * @param newLocalDirection Defines the new local direction
  71698. */
  71699. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  71700. this._localDirection = newLocalDirection;
  71701. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedTransformNode && this.isPlaying) {
  71702. this._updateDirection();
  71703. }
  71704. };
  71705. Sound.prototype._updateDirection = function () {
  71706. if (!this._connectedTransformNode || !this._soundPanner) {
  71707. return;
  71708. }
  71709. var mat = this._connectedTransformNode.getWorldMatrix();
  71710. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  71711. direction.normalize();
  71712. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  71713. };
  71714. /** @hidden */
  71715. Sound.prototype.updateDistanceFromListener = function () {
  71716. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedTransformNode && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  71717. var distance = this._connectedTransformNode.getDistanceToCamera(this._scene.activeCamera);
  71718. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  71719. }
  71720. };
  71721. /**
  71722. * Sets a new custom attenuation function for the sound.
  71723. * @param callback Defines the function used for the attenuation
  71724. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-your-own-custom-attenuation-function
  71725. */
  71726. Sound.prototype.setAttenuationFunction = function (callback) {
  71727. this._customAttenuationFunction = callback;
  71728. };
  71729. /**
  71730. * Play the sound
  71731. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  71732. * @param offset (optional) Start the sound setting it at a specific time
  71733. */
  71734. Sound.prototype.play = function (time, offset) {
  71735. var _this = this;
  71736. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  71737. try {
  71738. if (this._startOffset < 0) {
  71739. time = -this._startOffset;
  71740. this._startOffset = 0;
  71741. }
  71742. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  71743. if (!this._soundSource || !this._streamingSource) {
  71744. if (this.spatialSound && this._soundPanner) {
  71745. if (!isNaN(this._position.x) && !isNaN(this._position.y) && !isNaN(this._position.z)) {
  71746. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  71747. }
  71748. if (this._isDirectional) {
  71749. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  71750. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  71751. this._soundPanner.coneOuterGain = this._coneOuterGain;
  71752. if (this._connectedTransformNode) {
  71753. this._updateDirection();
  71754. }
  71755. else {
  71756. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  71757. }
  71758. }
  71759. }
  71760. }
  71761. if (this._streaming) {
  71762. if (!this._streamingSource) {
  71763. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  71764. this._htmlAudioElement.onended = function () { _this._onended(); };
  71765. this._htmlAudioElement.playbackRate = this._playbackRate;
  71766. }
  71767. this._streamingSource.disconnect();
  71768. this._streamingSource.connect(this._inputAudioNode);
  71769. if (this._htmlAudioElement) {
  71770. // required to manage properly the new suspended default state of Chrome
  71771. // When the option 'streaming: true' is used, we need first to wait for
  71772. // the audio engine to be unlocked by a user gesture before trying to play
  71773. // an HTML Audio elememt
  71774. var tryToPlay = function () {
  71775. if (BABYLON.Engine.audioEngine.unlocked) {
  71776. var playPromise = _this._htmlAudioElement.play();
  71777. // In browsers that don’t yet support this functionality,
  71778. // playPromise won’t be defined.
  71779. if (playPromise !== undefined) {
  71780. playPromise.catch(function (error) {
  71781. // Automatic playback failed.
  71782. // Waiting for the audio engine to be unlocked by user click on unmute
  71783. BABYLON.Engine.audioEngine.lock();
  71784. BABYLON.Engine.audioEngine.onAudioUnlockedObservable.addOnce(function () { tryToPlay(); });
  71785. });
  71786. }
  71787. }
  71788. else {
  71789. BABYLON.Engine.audioEngine.onAudioUnlockedObservable.addOnce(function () { tryToPlay(); });
  71790. }
  71791. };
  71792. tryToPlay();
  71793. }
  71794. }
  71795. else {
  71796. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  71797. this._soundSource.buffer = this._audioBuffer;
  71798. this._soundSource.connect(this._inputAudioNode);
  71799. this._soundSource.loop = this.loop;
  71800. this._soundSource.playbackRate.value = this._playbackRate;
  71801. this._soundSource.onended = function () { _this._onended(); };
  71802. if (this._soundSource.buffer) {
  71803. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  71804. }
  71805. }
  71806. this._startTime = startTime;
  71807. this.isPlaying = true;
  71808. this.isPaused = false;
  71809. }
  71810. catch (ex) {
  71811. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  71812. }
  71813. }
  71814. };
  71815. Sound.prototype._onended = function () {
  71816. this.isPlaying = false;
  71817. if (this.onended) {
  71818. this.onended();
  71819. }
  71820. this.onEndedObservable.notifyObservers(this);
  71821. };
  71822. /**
  71823. * Stop the sound
  71824. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  71825. */
  71826. Sound.prototype.stop = function (time) {
  71827. if (this.isPlaying) {
  71828. if (this._streaming) {
  71829. if (this._htmlAudioElement) {
  71830. this._htmlAudioElement.pause();
  71831. // Test needed for Firefox or it will generate an Invalid State Error
  71832. if (this._htmlAudioElement.currentTime > 0) {
  71833. this._htmlAudioElement.currentTime = 0;
  71834. }
  71835. }
  71836. else {
  71837. this._streamingSource.disconnect();
  71838. }
  71839. }
  71840. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  71841. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  71842. this._soundSource.stop(stopTime);
  71843. this._soundSource.onended = function () { };
  71844. if (!this.isPaused) {
  71845. this._startOffset = 0;
  71846. }
  71847. }
  71848. this.isPlaying = false;
  71849. }
  71850. };
  71851. /**
  71852. * Put the sound in pause
  71853. */
  71854. Sound.prototype.pause = function () {
  71855. if (this.isPlaying) {
  71856. this.isPaused = true;
  71857. if (this._streaming) {
  71858. if (this._htmlAudioElement) {
  71859. this._htmlAudioElement.pause();
  71860. }
  71861. else {
  71862. this._streamingSource.disconnect();
  71863. }
  71864. }
  71865. else if (BABYLON.Engine.audioEngine.audioContext) {
  71866. this.stop(0);
  71867. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  71868. }
  71869. }
  71870. };
  71871. /**
  71872. * Sets a dedicated volume for this sounds
  71873. * @param newVolume Define the new volume of the sound
  71874. * @param time Define in how long the sound should be at this value
  71875. */
  71876. Sound.prototype.setVolume = function (newVolume, time) {
  71877. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  71878. if (time && BABYLON.Engine.audioEngine.audioContext) {
  71879. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  71880. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  71881. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  71882. }
  71883. else {
  71884. this._soundGain.gain.value = newVolume;
  71885. }
  71886. }
  71887. this._volume = newVolume;
  71888. };
  71889. /**
  71890. * Set the sound play back rate
  71891. * @param newPlaybackRate Define the playback rate the sound should be played at
  71892. */
  71893. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  71894. this._playbackRate = newPlaybackRate;
  71895. if (this.isPlaying) {
  71896. if (this._streaming && this._htmlAudioElement) {
  71897. this._htmlAudioElement.playbackRate = this._playbackRate;
  71898. }
  71899. else if (this._soundSource) {
  71900. this._soundSource.playbackRate.value = this._playbackRate;
  71901. }
  71902. }
  71903. };
  71904. /**
  71905. * Gets the volume of the sound.
  71906. * @returns the volume of the sound
  71907. */
  71908. Sound.prototype.getVolume = function () {
  71909. return this._volume;
  71910. };
  71911. /**
  71912. * Attach the sound to a dedicated mesh
  71913. * @param transformNode The transform node to connect the sound with
  71914. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#attaching-a-sound-to-a-mesh
  71915. */
  71916. Sound.prototype.attachToMesh = function (transformNode) {
  71917. var _this = this;
  71918. if (this._connectedTransformNode && this._registerFunc) {
  71919. this._connectedTransformNode.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  71920. this._registerFunc = null;
  71921. }
  71922. this._connectedTransformNode = transformNode;
  71923. if (!this.spatialSound) {
  71924. this.spatialSound = true;
  71925. this._createSpatialParameters();
  71926. if (this.isPlaying && this.loop) {
  71927. this.stop();
  71928. this.play();
  71929. }
  71930. }
  71931. this._onRegisterAfterWorldMatrixUpdate(this._connectedTransformNode);
  71932. this._registerFunc = function (transformNode) { return _this._onRegisterAfterWorldMatrixUpdate(transformNode); };
  71933. this._connectedTransformNode.registerAfterWorldMatrixUpdate(this._registerFunc);
  71934. };
  71935. /**
  71936. * Detach the sound from the previously attached mesh
  71937. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#attaching-a-sound-to-a-mesh
  71938. */
  71939. Sound.prototype.detachFromMesh = function () {
  71940. if (this._connectedTransformNode && this._registerFunc) {
  71941. this._connectedTransformNode.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  71942. this._registerFunc = null;
  71943. this._connectedTransformNode = null;
  71944. }
  71945. };
  71946. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  71947. if (!node.getBoundingInfo) {
  71948. return;
  71949. }
  71950. var mesh = node;
  71951. if (this._positionInEmitterSpace) {
  71952. mesh.worldMatrixFromCache.invertToRef(BABYLON.Tmp.Matrix[0]);
  71953. this.setPosition(BABYLON.Tmp.Matrix[0].getTranslation());
  71954. }
  71955. else {
  71956. var boundingInfo = mesh.getBoundingInfo();
  71957. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  71958. }
  71959. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  71960. this._updateDirection();
  71961. }
  71962. };
  71963. /**
  71964. * Clone the current sound in the scene.
  71965. * @returns the new sound clone
  71966. */
  71967. Sound.prototype.clone = function () {
  71968. var _this = this;
  71969. if (!this._streaming) {
  71970. var setBufferAndRun = function () {
  71971. if (_this._isReadyToPlay) {
  71972. clonedSound._audioBuffer = _this.getAudioBuffer();
  71973. clonedSound._isReadyToPlay = true;
  71974. if (clonedSound.autoplay) {
  71975. clonedSound.play();
  71976. }
  71977. }
  71978. else {
  71979. window.setTimeout(setBufferAndRun, 300);
  71980. }
  71981. };
  71982. var currentOptions = {
  71983. autoplay: this.autoplay, loop: this.loop,
  71984. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  71985. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  71986. refDistance: this.refDistance, distanceModel: this.distanceModel
  71987. };
  71988. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  71989. if (this.useCustomAttenuation) {
  71990. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  71991. }
  71992. clonedSound.setPosition(this._position);
  71993. clonedSound.setPlaybackRate(this._playbackRate);
  71994. setBufferAndRun();
  71995. return clonedSound;
  71996. }
  71997. // Can't clone a streaming sound
  71998. else {
  71999. return null;
  72000. }
  72001. };
  72002. /**
  72003. * Gets the current underlying audio buffer containing the data
  72004. * @returns the audio buffer
  72005. */
  72006. Sound.prototype.getAudioBuffer = function () {
  72007. return this._audioBuffer;
  72008. };
  72009. /**
  72010. * Serializes the Sound in a JSON representation
  72011. * @returns the JSON representation of the sound
  72012. */
  72013. Sound.prototype.serialize = function () {
  72014. var serializationObject = {
  72015. name: this.name,
  72016. url: this.name,
  72017. autoplay: this.autoplay,
  72018. loop: this.loop,
  72019. volume: this._volume,
  72020. spatialSound: this.spatialSound,
  72021. maxDistance: this.maxDistance,
  72022. rolloffFactor: this.rolloffFactor,
  72023. refDistance: this.refDistance,
  72024. distanceModel: this.distanceModel,
  72025. playbackRate: this._playbackRate,
  72026. panningModel: this._panningModel,
  72027. soundTrackId: this.soundTrackId
  72028. };
  72029. if (this.spatialSound) {
  72030. if (this._connectedTransformNode) {
  72031. serializationObject.connectedMeshId = this._connectedTransformNode.id;
  72032. }
  72033. serializationObject.position = this._position.asArray();
  72034. serializationObject.refDistance = this.refDistance;
  72035. serializationObject.distanceModel = this.distanceModel;
  72036. serializationObject.isDirectional = this._isDirectional;
  72037. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  72038. serializationObject.coneInnerAngle = this._coneInnerAngle;
  72039. serializationObject.coneOuterAngle = this._coneOuterAngle;
  72040. serializationObject.coneOuterGain = this._coneOuterGain;
  72041. }
  72042. return serializationObject;
  72043. };
  72044. /**
  72045. * Parse a JSON representation of a sound to innstantiate in a given scene
  72046. * @param parsedSound Define the JSON representation of the sound (usually coming from the serialize method)
  72047. * @param scene Define the scene the new parsed sound should be created in
  72048. * @param rootUrl Define the rooturl of the load in case we need to fetch relative dependencies
  72049. * @param sourceSound Define a cound place holder if do not need to instantiate a new one
  72050. * @returns the newly parsed sound
  72051. */
  72052. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  72053. var soundName = parsedSound.name;
  72054. var soundUrl;
  72055. if (parsedSound.url) {
  72056. soundUrl = rootUrl + parsedSound.url;
  72057. }
  72058. else {
  72059. soundUrl = rootUrl + soundName;
  72060. }
  72061. var options = {
  72062. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  72063. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  72064. rolloffFactor: parsedSound.rolloffFactor,
  72065. refDistance: parsedSound.refDistance,
  72066. distanceModel: parsedSound.distanceModel,
  72067. playbackRate: parsedSound.playbackRate
  72068. };
  72069. var newSound;
  72070. if (!sourceSound) {
  72071. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  72072. scene._addPendingData(newSound);
  72073. }
  72074. else {
  72075. var setBufferAndRun = function () {
  72076. if (sourceSound._isReadyToPlay) {
  72077. newSound._audioBuffer = sourceSound.getAudioBuffer();
  72078. newSound._isReadyToPlay = true;
  72079. if (newSound.autoplay) {
  72080. newSound.play();
  72081. }
  72082. }
  72083. else {
  72084. window.setTimeout(setBufferAndRun, 300);
  72085. }
  72086. };
  72087. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  72088. setBufferAndRun();
  72089. }
  72090. if (parsedSound.position) {
  72091. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  72092. newSound.setPosition(soundPosition);
  72093. }
  72094. if (parsedSound.isDirectional) {
  72095. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  72096. if (parsedSound.localDirectionToMesh) {
  72097. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  72098. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  72099. }
  72100. }
  72101. if (parsedSound.connectedMeshId) {
  72102. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  72103. if (connectedMesh) {
  72104. newSound.attachToMesh(connectedMesh);
  72105. }
  72106. }
  72107. return newSound;
  72108. };
  72109. return Sound;
  72110. }());
  72111. BABYLON.Sound = Sound;
  72112. })(BABYLON || (BABYLON = {}));
  72113. //# sourceMappingURL=babylon.sound.js.map
  72114. var BABYLON;
  72115. (function (BABYLON) {
  72116. /**
  72117. * It could be useful to isolate your music & sounds on several tracks to better manage volume on a grouped instance of sounds.
  72118. * It will be also used in a future release to apply effects on a specific track.
  72119. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#using-sound-tracks
  72120. */
  72121. var SoundTrack = /** @class */ (function () {
  72122. /**
  72123. * Creates a new sound track.
  72124. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#using-sound-tracks
  72125. * @param scene Define the scene the sound track belongs to
  72126. * @param options
  72127. */
  72128. function SoundTrack(scene, options) {
  72129. if (options === void 0) { options = {}; }
  72130. /**
  72131. * The unique identifier of the sound track in the scene.
  72132. */
  72133. this.id = -1;
  72134. this._isMainTrack = false;
  72135. this._isInitialized = false;
  72136. this._scene = scene;
  72137. this.soundCollection = new Array();
  72138. this._options = options;
  72139. if (!this._isMainTrack && this._scene.soundTracks) {
  72140. this._scene.soundTracks.push(this);
  72141. this.id = this._scene.soundTracks.length - 1;
  72142. }
  72143. }
  72144. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  72145. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  72146. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  72147. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  72148. if (this._options) {
  72149. if (this._options.volume) {
  72150. this._outputAudioNode.gain.value = this._options.volume;
  72151. }
  72152. if (this._options.mainTrack) {
  72153. this._isMainTrack = this._options.mainTrack;
  72154. }
  72155. }
  72156. this._isInitialized = true;
  72157. }
  72158. };
  72159. /**
  72160. * Release the sound track and its associated resources
  72161. */
  72162. SoundTrack.prototype.dispose = function () {
  72163. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  72164. if (this._connectedAnalyser) {
  72165. this._connectedAnalyser.stopDebugCanvas();
  72166. }
  72167. while (this.soundCollection.length) {
  72168. this.soundCollection[0].dispose();
  72169. }
  72170. if (this._outputAudioNode) {
  72171. this._outputAudioNode.disconnect();
  72172. }
  72173. this._outputAudioNode = null;
  72174. }
  72175. };
  72176. /**
  72177. * Adds a sound to this sound track
  72178. * @param sound define the cound to add
  72179. * @ignoreNaming
  72180. */
  72181. SoundTrack.prototype.AddSound = function (sound) {
  72182. if (!this._isInitialized) {
  72183. this._initializeSoundTrackAudioGraph();
  72184. }
  72185. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  72186. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  72187. }
  72188. if (sound.soundTrackId) {
  72189. if (sound.soundTrackId === -1) {
  72190. this._scene.mainSoundTrack.RemoveSound(sound);
  72191. }
  72192. else if (this._scene.soundTracks) {
  72193. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  72194. }
  72195. }
  72196. this.soundCollection.push(sound);
  72197. sound.soundTrackId = this.id;
  72198. };
  72199. /**
  72200. * Removes a sound to this sound track
  72201. * @param sound define the cound to remove
  72202. * @ignoreNaming
  72203. */
  72204. SoundTrack.prototype.RemoveSound = function (sound) {
  72205. var index = this.soundCollection.indexOf(sound);
  72206. if (index !== -1) {
  72207. this.soundCollection.splice(index, 1);
  72208. }
  72209. };
  72210. /**
  72211. * Set a global volume for the full sound track.
  72212. * @param newVolume Define the new volume of the sound track
  72213. */
  72214. SoundTrack.prototype.setVolume = function (newVolume) {
  72215. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  72216. this._outputAudioNode.gain.value = newVolume;
  72217. }
  72218. };
  72219. /**
  72220. * Switch the panning model to HRTF:
  72221. * Renders a stereo output of higher quality than equalpower — it uses a convolution with measured impulse responses from human subjects.
  72222. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  72223. */
  72224. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  72225. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  72226. for (var i = 0; i < this.soundCollection.length; i++) {
  72227. this.soundCollection[i].switchPanningModelToHRTF();
  72228. }
  72229. }
  72230. };
  72231. /**
  72232. * Switch the panning model to Equal Power:
  72233. * Represents the equal-power panning algorithm, generally regarded as simple and efficient. equalpower is the default value.
  72234. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  72235. */
  72236. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  72237. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  72238. for (var i = 0; i < this.soundCollection.length; i++) {
  72239. this.soundCollection[i].switchPanningModelToEqualPower();
  72240. }
  72241. }
  72242. };
  72243. /**
  72244. * Connect the sound track to an audio analyser allowing some amazing
  72245. * synchornization between the sounds/music and your visualization (VuMeter for instance).
  72246. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#using-the-analyser
  72247. * @param analyser The analyser to connect to the engine
  72248. */
  72249. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  72250. if (this._connectedAnalyser) {
  72251. this._connectedAnalyser.stopDebugCanvas();
  72252. }
  72253. this._connectedAnalyser = analyser;
  72254. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  72255. this._outputAudioNode.disconnect();
  72256. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  72257. }
  72258. };
  72259. return SoundTrack;
  72260. }());
  72261. BABYLON.SoundTrack = SoundTrack;
  72262. })(BABYLON || (BABYLON = {}));
  72263. //# sourceMappingURL=babylon.soundtrack.js.map
  72264. var BABYLON;
  72265. (function (BABYLON) {
  72266. /**
  72267. * Class used to work with sound analyzer using fast fourier transform (FFT)
  72268. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  72269. */
  72270. var Analyser = /** @class */ (function () {
  72271. /**
  72272. * Creates a new analyser
  72273. * @param scene defines hosting scene
  72274. */
  72275. function Analyser(scene) {
  72276. /**
  72277. * Gets or sets the smoothing
  72278. * @ignorenaming
  72279. */
  72280. this.SMOOTHING = 0.75;
  72281. /**
  72282. * Gets or sets the FFT table size
  72283. * @ignorenaming
  72284. */
  72285. this.FFT_SIZE = 512;
  72286. /**
  72287. * Gets or sets the bar graph amplitude
  72288. * @ignorenaming
  72289. */
  72290. this.BARGRAPHAMPLITUDE = 256;
  72291. /**
  72292. * Gets or sets the position of the debug canvas
  72293. * @ignorenaming
  72294. */
  72295. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  72296. /**
  72297. * Gets or sets the debug canvas size
  72298. * @ignorenaming
  72299. */
  72300. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  72301. this._scene = scene;
  72302. this._audioEngine = BABYLON.Engine.audioEngine;
  72303. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  72304. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  72305. this._webAudioAnalyser.minDecibels = -140;
  72306. this._webAudioAnalyser.maxDecibels = 0;
  72307. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  72308. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  72309. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  72310. }
  72311. }
  72312. /**
  72313. * Get the number of data values you will have to play with for the visualization
  72314. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/frequencyBinCount
  72315. * @returns a number
  72316. */
  72317. Analyser.prototype.getFrequencyBinCount = function () {
  72318. if (this._audioEngine.canUseWebAudio) {
  72319. return this._webAudioAnalyser.frequencyBinCount;
  72320. }
  72321. else {
  72322. return 0;
  72323. }
  72324. };
  72325. /**
  72326. * Gets the current frequency data as a byte array
  72327. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  72328. * @returns a Uint8Array
  72329. */
  72330. Analyser.prototype.getByteFrequencyData = function () {
  72331. if (this._audioEngine.canUseWebAudio) {
  72332. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  72333. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  72334. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  72335. }
  72336. return this._byteFreqs;
  72337. };
  72338. /**
  72339. * Gets the current waveform as a byte array
  72340. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteTimeDomainData
  72341. * @returns a Uint8Array
  72342. */
  72343. Analyser.prototype.getByteTimeDomainData = function () {
  72344. if (this._audioEngine.canUseWebAudio) {
  72345. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  72346. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  72347. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  72348. }
  72349. return this._byteTime;
  72350. };
  72351. /**
  72352. * Gets the current frequency data as a float array
  72353. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  72354. * @returns a Float32Array
  72355. */
  72356. Analyser.prototype.getFloatFrequencyData = function () {
  72357. if (this._audioEngine.canUseWebAudio) {
  72358. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  72359. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  72360. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  72361. }
  72362. return this._floatFreqs;
  72363. };
  72364. /**
  72365. * Renders the debug canvas
  72366. */
  72367. Analyser.prototype.drawDebugCanvas = function () {
  72368. var _this = this;
  72369. if (this._audioEngine.canUseWebAudio) {
  72370. if (!this._debugCanvas) {
  72371. this._debugCanvas = document.createElement("canvas");
  72372. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  72373. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  72374. this._debugCanvas.style.position = "absolute";
  72375. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  72376. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  72377. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  72378. document.body.appendChild(this._debugCanvas);
  72379. this._registerFunc = function () {
  72380. _this.drawDebugCanvas();
  72381. };
  72382. this._scene.registerBeforeRender(this._registerFunc);
  72383. }
  72384. if (this._registerFunc && this._debugCanvasContext) {
  72385. var workingArray = this.getByteFrequencyData();
  72386. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  72387. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  72388. // Draw the frequency domain chart.
  72389. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  72390. var value = workingArray[i];
  72391. var percent = value / this.BARGRAPHAMPLITUDE;
  72392. var height = this.DEBUGCANVASSIZE.height * percent;
  72393. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  72394. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  72395. var hue = i / this.getFrequencyBinCount() * 360;
  72396. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  72397. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  72398. }
  72399. }
  72400. }
  72401. };
  72402. /**
  72403. * Stops rendering the debug canvas and removes it
  72404. */
  72405. Analyser.prototype.stopDebugCanvas = function () {
  72406. if (this._debugCanvas) {
  72407. if (this._registerFunc) {
  72408. this._scene.unregisterBeforeRender(this._registerFunc);
  72409. this._registerFunc = null;
  72410. }
  72411. document.body.removeChild(this._debugCanvas);
  72412. this._debugCanvas = null;
  72413. this._debugCanvasContext = null;
  72414. }
  72415. };
  72416. /**
  72417. * Connects two audio nodes
  72418. * @param inputAudioNode defines first node to connect
  72419. * @param outputAudioNode defines second node to connect
  72420. */
  72421. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  72422. if (this._audioEngine.canUseWebAudio) {
  72423. inputAudioNode.connect(this._webAudioAnalyser);
  72424. this._webAudioAnalyser.connect(outputAudioNode);
  72425. }
  72426. };
  72427. /**
  72428. * Releases all associated resources
  72429. */
  72430. Analyser.prototype.dispose = function () {
  72431. if (this._audioEngine.canUseWebAudio) {
  72432. this._webAudioAnalyser.disconnect();
  72433. }
  72434. };
  72435. return Analyser;
  72436. }());
  72437. BABYLON.Analyser = Analyser;
  72438. })(BABYLON || (BABYLON = {}));
  72439. //# sourceMappingURL=babylon.analyser.js.map
  72440. var BABYLON;
  72441. (function (BABYLON) {
  72442. /**
  72443. * Wraps one or more Sound objects and selects one with random weight for playback.
  72444. */
  72445. var WeightedSound = /** @class */ (function () {
  72446. /**
  72447. * Creates a new WeightedSound from the list of sounds given.
  72448. * @param loop When true a Sound will be selected and played when the current playing Sound completes.
  72449. * @param sounds Array of Sounds that will be selected from.
  72450. * @param weights Array of number values for selection weights; length must equal sounds, values will be normalized to 1
  72451. */
  72452. function WeightedSound(loop, sounds, weights) {
  72453. var _this = this;
  72454. /** When true a Sound will be selected and played when the current playing Sound completes. */
  72455. this.loop = false;
  72456. this._coneInnerAngle = 360;
  72457. this._coneOuterAngle = 360;
  72458. this._volume = 1;
  72459. /** A Sound is currently playing. */
  72460. this.isPlaying = false;
  72461. /** A Sound is currently paused. */
  72462. this.isPaused = false;
  72463. this._sounds = [];
  72464. this._weights = [];
  72465. if (sounds.length !== weights.length) {
  72466. throw new Error('Sounds length does not equal weights length');
  72467. }
  72468. this.loop = loop;
  72469. this._weights = weights;
  72470. // Normalize the weights
  72471. var weightSum = 0;
  72472. for (var _i = 0, weights_1 = weights; _i < weights_1.length; _i++) {
  72473. var weight = weights_1[_i];
  72474. weightSum += weight;
  72475. }
  72476. var invWeightSum = weightSum > 0 ? 1 / weightSum : 0;
  72477. for (var i = 0; i < this._weights.length; i++) {
  72478. this._weights[i] *= invWeightSum;
  72479. }
  72480. this._sounds = sounds;
  72481. for (var _a = 0, _b = this._sounds; _a < _b.length; _a++) {
  72482. var sound = _b[_a];
  72483. sound.onEndedObservable.add(function () { _this._onended(); });
  72484. }
  72485. }
  72486. Object.defineProperty(WeightedSound.prototype, "directionalConeInnerAngle", {
  72487. /**
  72488. * The size of cone in degrees for a directional sound in which there will be no attenuation.
  72489. */
  72490. get: function () {
  72491. return this._coneInnerAngle;
  72492. },
  72493. /**
  72494. * The size of cone in degress for a directional sound in which there will be no attenuation.
  72495. */
  72496. set: function (value) {
  72497. if (value !== this._coneInnerAngle) {
  72498. if (this._coneOuterAngle < value) {
  72499. BABYLON.Tools.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");
  72500. return;
  72501. }
  72502. this._coneInnerAngle = value;
  72503. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  72504. var sound = _a[_i];
  72505. sound.directionalConeInnerAngle = value;
  72506. }
  72507. }
  72508. },
  72509. enumerable: true,
  72510. configurable: true
  72511. });
  72512. Object.defineProperty(WeightedSound.prototype, "directionalConeOuterAngle", {
  72513. /**
  72514. * Size of cone in degrees for a directional sound outside of which there will be no sound.
  72515. * Listener angles between innerAngle and outerAngle will falloff linearly.
  72516. */
  72517. get: function () {
  72518. return this._coneOuterAngle;
  72519. },
  72520. /**
  72521. * Size of cone in degrees for a directional sound outside of which there will be no sound.
  72522. * Listener angles between innerAngle and outerAngle will falloff linearly.
  72523. */
  72524. set: function (value) {
  72525. if (value !== this._coneOuterAngle) {
  72526. if (value < this._coneInnerAngle) {
  72527. BABYLON.Tools.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");
  72528. return;
  72529. }
  72530. this._coneOuterAngle = value;
  72531. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  72532. var sound = _a[_i];
  72533. sound.directionalConeOuterAngle = value;
  72534. }
  72535. }
  72536. },
  72537. enumerable: true,
  72538. configurable: true
  72539. });
  72540. Object.defineProperty(WeightedSound.prototype, "volume", {
  72541. /**
  72542. * Playback volume.
  72543. */
  72544. get: function () {
  72545. return this._volume;
  72546. },
  72547. /**
  72548. * Playback volume.
  72549. */
  72550. set: function (value) {
  72551. if (value !== this._volume) {
  72552. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  72553. var sound = _a[_i];
  72554. sound.setVolume(value);
  72555. }
  72556. }
  72557. },
  72558. enumerable: true,
  72559. configurable: true
  72560. });
  72561. WeightedSound.prototype._onended = function () {
  72562. if (this._currentIndex !== undefined) {
  72563. this._sounds[this._currentIndex].autoplay = false;
  72564. }
  72565. if (this.loop && this.isPlaying) {
  72566. this.play();
  72567. }
  72568. else {
  72569. this.isPlaying = false;
  72570. }
  72571. };
  72572. /**
  72573. * Suspend playback
  72574. */
  72575. WeightedSound.prototype.pause = function () {
  72576. this.isPaused = true;
  72577. if (this._currentIndex !== undefined) {
  72578. this._sounds[this._currentIndex].pause();
  72579. }
  72580. };
  72581. /**
  72582. * Stop playback
  72583. */
  72584. WeightedSound.prototype.stop = function () {
  72585. this.isPlaying = false;
  72586. if (this._currentIndex !== undefined) {
  72587. this._sounds[this._currentIndex].stop();
  72588. }
  72589. };
  72590. /**
  72591. * Start playback.
  72592. * @param startOffset Position the clip head at a specific time in seconds.
  72593. */
  72594. WeightedSound.prototype.play = function (startOffset) {
  72595. if (!this.isPaused) {
  72596. this.stop();
  72597. var randomValue = Math.random();
  72598. var total = 0;
  72599. for (var i = 0; i < this._weights.length; i++) {
  72600. total += this._weights[i];
  72601. if (randomValue <= total) {
  72602. this._currentIndex = i;
  72603. break;
  72604. }
  72605. }
  72606. }
  72607. var sound = this._sounds[this._currentIndex];
  72608. if (sound.isReady()) {
  72609. sound.play(0, this.isPaused ? undefined : startOffset);
  72610. }
  72611. else {
  72612. sound.autoplay = true;
  72613. }
  72614. this.isPlaying = true;
  72615. this.isPaused = false;
  72616. };
  72617. return WeightedSound;
  72618. }());
  72619. BABYLON.WeightedSound = WeightedSound;
  72620. })(BABYLON || (BABYLON = {}));
  72621. //# sourceMappingURL=babylon.weightedsound.js.map
  72622. var BABYLON;
  72623. (function (BABYLON) {
  72624. // Adds the parser to the scene parsers.
  72625. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_AUDIO, function (parsedData, scene, container, rootUrl) {
  72626. // TODO: add sound
  72627. var loadedSounds = [];
  72628. var loadedSound;
  72629. container.sounds = container.sounds || [];
  72630. if (parsedData.sounds !== undefined && parsedData.sounds !== null) {
  72631. for (var index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  72632. var parsedSound = parsedData.sounds[index];
  72633. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  72634. if (!parsedSound.url) {
  72635. parsedSound.url = parsedSound.name;
  72636. }
  72637. if (!loadedSounds[parsedSound.url]) {
  72638. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  72639. loadedSounds[parsedSound.url] = loadedSound;
  72640. container.sounds.push(loadedSound);
  72641. }
  72642. else {
  72643. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  72644. }
  72645. }
  72646. else {
  72647. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  72648. }
  72649. }
  72650. }
  72651. loadedSounds = [];
  72652. });
  72653. Object.defineProperty(BABYLON.Scene.prototype, "mainSoundTrack", {
  72654. get: function () {
  72655. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  72656. if (!compo) {
  72657. compo = new AudioSceneComponent(this);
  72658. this._addComponent(compo);
  72659. }
  72660. if (!this._mainSoundTrack) {
  72661. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  72662. }
  72663. return this._mainSoundTrack;
  72664. },
  72665. enumerable: true,
  72666. configurable: true
  72667. });
  72668. BABYLON.Scene.prototype.getSoundByName = function (name) {
  72669. var index;
  72670. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  72671. if (this.mainSoundTrack.soundCollection[index].name === name) {
  72672. return this.mainSoundTrack.soundCollection[index];
  72673. }
  72674. }
  72675. if (this.soundTracks) {
  72676. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  72677. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  72678. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  72679. return this.soundTracks[sdIndex].soundCollection[index];
  72680. }
  72681. }
  72682. }
  72683. }
  72684. return null;
  72685. };
  72686. Object.defineProperty(BABYLON.Scene.prototype, "audioEnabled", {
  72687. get: function () {
  72688. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  72689. if (!compo) {
  72690. compo = new AudioSceneComponent(this);
  72691. this._addComponent(compo);
  72692. }
  72693. return compo.audioEnabled;
  72694. },
  72695. set: function (value) {
  72696. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  72697. if (!compo) {
  72698. compo = new AudioSceneComponent(this);
  72699. this._addComponent(compo);
  72700. }
  72701. if (value) {
  72702. compo.enableAudio();
  72703. }
  72704. else {
  72705. compo.disableAudio();
  72706. }
  72707. },
  72708. enumerable: true,
  72709. configurable: true
  72710. });
  72711. Object.defineProperty(BABYLON.Scene.prototype, "headphone", {
  72712. get: function () {
  72713. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  72714. if (!compo) {
  72715. compo = new AudioSceneComponent(this);
  72716. this._addComponent(compo);
  72717. }
  72718. return compo.headphone;
  72719. },
  72720. set: function (value) {
  72721. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  72722. if (!compo) {
  72723. compo = new AudioSceneComponent(this);
  72724. this._addComponent(compo);
  72725. }
  72726. if (value) {
  72727. compo.switchAudioModeForHeadphones();
  72728. }
  72729. else {
  72730. compo.switchAudioModeForNormalSpeakers();
  72731. }
  72732. },
  72733. enumerable: true,
  72734. configurable: true
  72735. });
  72736. /**
  72737. * Defines the sound scene component responsible to manage any sounds
  72738. * in a given scene.
  72739. */
  72740. var AudioSceneComponent = /** @class */ (function () {
  72741. /**
  72742. * Creates a new instance of the component for the given scene
  72743. * @param scene Defines the scene to register the component in
  72744. */
  72745. function AudioSceneComponent(scene) {
  72746. /**
  72747. * The component name helpfull to identify the component in the list of scene components.
  72748. */
  72749. this.name = BABYLON.SceneComponentConstants.NAME_AUDIO;
  72750. this._audioEnabled = true;
  72751. this._headphone = false;
  72752. this.scene = scene;
  72753. scene.soundTracks = new Array();
  72754. scene.sounds = new Array();
  72755. }
  72756. Object.defineProperty(AudioSceneComponent.prototype, "audioEnabled", {
  72757. /**
  72758. * Gets whether audio is enabled or not.
  72759. * Please use related enable/disable method to switch state.
  72760. */
  72761. get: function () {
  72762. return this._audioEnabled;
  72763. },
  72764. enumerable: true,
  72765. configurable: true
  72766. });
  72767. Object.defineProperty(AudioSceneComponent.prototype, "headphone", {
  72768. /**
  72769. * Gets whether audio is outputing to headphone or not.
  72770. * Please use the according Switch methods to change output.
  72771. */
  72772. get: function () {
  72773. return this._headphone;
  72774. },
  72775. enumerable: true,
  72776. configurable: true
  72777. });
  72778. /**
  72779. * Registers the component in a given scene
  72780. */
  72781. AudioSceneComponent.prototype.register = function () {
  72782. this.scene._afterRenderStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDER_AUDIO, this, this._afterRender);
  72783. };
  72784. /**
  72785. * Rebuilds the elements related to this component in case of
  72786. * context lost for instance.
  72787. */
  72788. AudioSceneComponent.prototype.rebuild = function () {
  72789. // Nothing to do here. (Not rendering related)
  72790. };
  72791. /**
  72792. * Serializes the component data to the specified json object
  72793. * @param serializationObject The object to serialize to
  72794. */
  72795. AudioSceneComponent.prototype.serialize = function (serializationObject) {
  72796. serializationObject.sounds = [];
  72797. if (this.scene.soundTracks) {
  72798. for (var index = 0; index < this.scene.soundTracks.length; index++) {
  72799. var soundtrack = this.scene.soundTracks[index];
  72800. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  72801. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  72802. }
  72803. }
  72804. }
  72805. };
  72806. /**
  72807. * Adds all the element from the container to the scene
  72808. * @param container the container holding the elements
  72809. */
  72810. AudioSceneComponent.prototype.addFromContainer = function (container) {
  72811. var _this = this;
  72812. if (!container.sounds) {
  72813. return;
  72814. }
  72815. container.sounds.forEach(function (sound) {
  72816. sound.play();
  72817. sound.autoplay = true;
  72818. _this.scene.mainSoundTrack.AddSound(sound);
  72819. });
  72820. };
  72821. /**
  72822. * Removes all the elements in the container from the scene
  72823. * @param container contains the elements to remove
  72824. */
  72825. AudioSceneComponent.prototype.removeFromContainer = function (container) {
  72826. var _this = this;
  72827. if (!container.sounds) {
  72828. return;
  72829. }
  72830. container.sounds.forEach(function (sound) {
  72831. sound.stop();
  72832. sound.autoplay = false;
  72833. _this.scene.mainSoundTrack.RemoveSound(sound);
  72834. });
  72835. };
  72836. /**
  72837. * Disposes the component and the associated ressources.
  72838. */
  72839. AudioSceneComponent.prototype.dispose = function () {
  72840. var scene = this.scene;
  72841. if (scene._mainSoundTrack) {
  72842. scene.mainSoundTrack.dispose();
  72843. }
  72844. if (scene.soundTracks) {
  72845. for (var scIndex = 0; scIndex < scene.soundTracks.length; scIndex++) {
  72846. scene.soundTracks[scIndex].dispose();
  72847. }
  72848. }
  72849. };
  72850. /**
  72851. * Disables audio in the associated scene.
  72852. */
  72853. AudioSceneComponent.prototype.disableAudio = function () {
  72854. var scene = this.scene;
  72855. this._audioEnabled = false;
  72856. var i;
  72857. for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) {
  72858. scene.mainSoundTrack.soundCollection[i].pause();
  72859. }
  72860. if (scene.soundTracks) {
  72861. for (i = 0; i < scene.soundTracks.length; i++) {
  72862. for (var j = 0; j < scene.soundTracks[i].soundCollection.length; j++) {
  72863. scene.soundTracks[i].soundCollection[j].pause();
  72864. }
  72865. }
  72866. }
  72867. };
  72868. /**
  72869. * Enables audio in the associated scene.
  72870. */
  72871. AudioSceneComponent.prototype.enableAudio = function () {
  72872. var scene = this.scene;
  72873. this._audioEnabled = true;
  72874. var i;
  72875. for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) {
  72876. if (scene.mainSoundTrack.soundCollection[i].isPaused) {
  72877. scene.mainSoundTrack.soundCollection[i].play();
  72878. }
  72879. }
  72880. if (scene.soundTracks) {
  72881. for (i = 0; i < scene.soundTracks.length; i++) {
  72882. for (var j = 0; j < scene.soundTracks[i].soundCollection.length; j++) {
  72883. if (scene.soundTracks[i].soundCollection[j].isPaused) {
  72884. scene.soundTracks[i].soundCollection[j].play();
  72885. }
  72886. }
  72887. }
  72888. }
  72889. };
  72890. /**
  72891. * Switch audio to headphone output.
  72892. */
  72893. AudioSceneComponent.prototype.switchAudioModeForHeadphones = function () {
  72894. var scene = this.scene;
  72895. this._headphone = true;
  72896. scene.mainSoundTrack.switchPanningModelToHRTF();
  72897. if (scene.soundTracks) {
  72898. for (var i = 0; i < scene.soundTracks.length; i++) {
  72899. scene.soundTracks[i].switchPanningModelToHRTF();
  72900. }
  72901. }
  72902. };
  72903. /**
  72904. * Switch audio to normal speakers.
  72905. */
  72906. AudioSceneComponent.prototype.switchAudioModeForNormalSpeakers = function () {
  72907. var scene = this.scene;
  72908. this._headphone = false;
  72909. scene.mainSoundTrack.switchPanningModelToEqualPower();
  72910. if (scene.soundTracks) {
  72911. for (var i = 0; i < scene.soundTracks.length; i++) {
  72912. scene.soundTracks[i].switchPanningModelToEqualPower();
  72913. }
  72914. }
  72915. };
  72916. AudioSceneComponent.prototype._afterRender = function () {
  72917. var scene = this.scene;
  72918. if (!this._audioEnabled || !scene._mainSoundTrack || !scene.soundTracks || (scene._mainSoundTrack.soundCollection.length === 0 && scene.soundTracks.length === 1)) {
  72919. return;
  72920. }
  72921. var listeningCamera;
  72922. var audioEngine = BABYLON.Engine.audioEngine;
  72923. if (scene.activeCameras.length > 0) {
  72924. listeningCamera = scene.activeCameras[0];
  72925. }
  72926. else {
  72927. listeningCamera = scene.activeCamera;
  72928. }
  72929. if (listeningCamera && audioEngine.audioContext) {
  72930. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  72931. // for VR cameras
  72932. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  72933. listeningCamera = listeningCamera.rigCameras[0];
  72934. }
  72935. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  72936. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  72937. cameraDirection.normalize();
  72938. // To avoid some errors on GearVR
  72939. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  72940. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  72941. }
  72942. var i;
  72943. for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) {
  72944. var sound = scene.mainSoundTrack.soundCollection[i];
  72945. if (sound.useCustomAttenuation) {
  72946. sound.updateDistanceFromListener();
  72947. }
  72948. }
  72949. if (scene.soundTracks) {
  72950. for (i = 0; i < scene.soundTracks.length; i++) {
  72951. for (var j = 0; j < scene.soundTracks[i].soundCollection.length; j++) {
  72952. sound = scene.soundTracks[i].soundCollection[j];
  72953. if (sound.useCustomAttenuation) {
  72954. sound.updateDistanceFromListener();
  72955. }
  72956. }
  72957. }
  72958. }
  72959. }
  72960. };
  72961. return AudioSceneComponent;
  72962. }());
  72963. BABYLON.AudioSceneComponent = AudioSceneComponent;
  72964. })(BABYLON || (BABYLON = {}));
  72965. //# sourceMappingURL=babylon.audioSceneComponent.js.map
  72966. var BABYLON;
  72967. (function (BABYLON) {
  72968. /**
  72969. * This defines an action helpful to play a defined sound on a triggered action.
  72970. */
  72971. var PlaySoundAction = /** @class */ (function (_super) {
  72972. __extends(PlaySoundAction, _super);
  72973. /**
  72974. * Instantiate the action
  72975. * @param triggerOptions defines the trigger options
  72976. * @param sound defines the sound to play
  72977. * @param condition defines the trigger related conditions
  72978. */
  72979. function PlaySoundAction(triggerOptions, sound, condition) {
  72980. var _this = _super.call(this, triggerOptions, condition) || this;
  72981. _this._sound = sound;
  72982. return _this;
  72983. }
  72984. /** @hidden */
  72985. PlaySoundAction.prototype._prepare = function () {
  72986. };
  72987. /**
  72988. * Execute the action and play the sound.
  72989. */
  72990. PlaySoundAction.prototype.execute = function () {
  72991. if (this._sound !== undefined) {
  72992. this._sound.play();
  72993. }
  72994. };
  72995. /**
  72996. * Serializes the actions and its related information.
  72997. * @param parent defines the object to serialize in
  72998. * @returns the serialized object
  72999. */
  73000. PlaySoundAction.prototype.serialize = function (parent) {
  73001. return _super.prototype._serialize.call(this, {
  73002. name: "PlaySoundAction",
  73003. properties: [{ name: "sound", value: this._sound.name }]
  73004. }, parent);
  73005. };
  73006. return PlaySoundAction;
  73007. }(BABYLON.Action));
  73008. BABYLON.PlaySoundAction = PlaySoundAction;
  73009. /**
  73010. * This defines an action helpful to stop a defined sound on a triggered action.
  73011. */
  73012. var StopSoundAction = /** @class */ (function (_super) {
  73013. __extends(StopSoundAction, _super);
  73014. /**
  73015. * Instantiate the action
  73016. * @param triggerOptions defines the trigger options
  73017. * @param sound defines the sound to stop
  73018. * @param condition defines the trigger related conditions
  73019. */
  73020. function StopSoundAction(triggerOptions, sound, condition) {
  73021. var _this = _super.call(this, triggerOptions, condition) || this;
  73022. _this._sound = sound;
  73023. return _this;
  73024. }
  73025. /** @hidden */
  73026. StopSoundAction.prototype._prepare = function () {
  73027. };
  73028. /**
  73029. * Execute the action and stop the sound.
  73030. */
  73031. StopSoundAction.prototype.execute = function () {
  73032. if (this._sound !== undefined) {
  73033. this._sound.stop();
  73034. }
  73035. };
  73036. /**
  73037. * Serializes the actions and its related information.
  73038. * @param parent defines the object to serialize in
  73039. * @returns the serialized object
  73040. */
  73041. StopSoundAction.prototype.serialize = function (parent) {
  73042. return _super.prototype._serialize.call(this, {
  73043. name: "StopSoundAction",
  73044. properties: [{ name: "sound", value: this._sound.name }]
  73045. }, parent);
  73046. };
  73047. return StopSoundAction;
  73048. }(BABYLON.Action));
  73049. BABYLON.StopSoundAction = StopSoundAction;
  73050. })(BABYLON || (BABYLON = {}));
  73051. //# sourceMappingURL=babylon.directAudioActions.js.map
  73052. var BABYLON;
  73053. (function (BABYLON) {
  73054. /**
  73055. * Class for creating a cube texture
  73056. */
  73057. var CubeTexture = /** @class */ (function (_super) {
  73058. __extends(CubeTexture, _super);
  73059. /**
  73060. * Creates a cube texture to use with reflection for instance. It can be based upon dds or six images as well
  73061. * as prefiltered data.
  73062. * @param rootUrl defines the url of the texture or the root name of the six images
  73063. * @param scene defines the scene the texture is attached to
  73064. * @param extensions defines the suffixes add to the picture name in case six images are in use like _px.jpg...
  73065. * @param noMipmap defines if mipmaps should be created or not
  73066. * @param files defines the six files to load for the different faces
  73067. * @param onLoad defines a callback triggered at the end of the file load if no errors occured
  73068. * @param onError defines a callback triggered in case of error during load
  73069. * @param format defines the internal format to use for the texture once loaded
  73070. * @param prefiltered defines whether or not the texture is created from prefiltered data
  73071. * @param forcedExtension defines the extensions to use (force a special type of file to load) in case it is different from the file name
  73072. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  73073. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  73074. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  73075. * @return the cube texture
  73076. */
  73077. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension, createPolynomials, lodScale, lodOffset) {
  73078. if (extensions === void 0) { extensions = null; }
  73079. if (noMipmap === void 0) { noMipmap = false; }
  73080. if (files === void 0) { files = null; }
  73081. if (onLoad === void 0) { onLoad = null; }
  73082. if (onError === void 0) { onError = null; }
  73083. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  73084. if (prefiltered === void 0) { prefiltered = false; }
  73085. if (forcedExtension === void 0) { forcedExtension = null; }
  73086. if (createPolynomials === void 0) { createPolynomials = false; }
  73087. if (lodScale === void 0) { lodScale = 0.8; }
  73088. if (lodOffset === void 0) { lodOffset = 0; }
  73089. var _this = _super.call(this, scene) || this;
  73090. /**
  73091. * Gets or sets the center of the bounding box associated with the cube texture.
  73092. * It must define where the camera used to render the texture was set
  73093. * @see http://doc.babylonjs.com/how_to/reflect#using-local-cubemap-mode
  73094. */
  73095. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  73096. _this._rotationY = 0;
  73097. /** @hidden */
  73098. _this._prefiltered = false;
  73099. _this.name = rootUrl;
  73100. _this.url = rootUrl;
  73101. _this._noMipmap = noMipmap;
  73102. _this.hasAlpha = false;
  73103. _this._format = format;
  73104. _this.isCube = true;
  73105. _this._textureMatrix = BABYLON.Matrix.Identity();
  73106. _this._createPolynomials = createPolynomials;
  73107. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  73108. if (!rootUrl && !files) {
  73109. return _this;
  73110. }
  73111. var lastDot = rootUrl.lastIndexOf(".");
  73112. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  73113. var isDDS = (extension === ".dds");
  73114. var isEnv = (extension === ".env");
  73115. if (isEnv) {
  73116. _this.gammaSpace = false;
  73117. _this._prefiltered = false;
  73118. }
  73119. else {
  73120. _this._prefiltered = prefiltered;
  73121. if (prefiltered) {
  73122. _this.gammaSpace = false;
  73123. }
  73124. }
  73125. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  73126. if (!files) {
  73127. if (!isEnv && !isDDS && !extensions) {
  73128. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  73129. }
  73130. files = [];
  73131. if (extensions) {
  73132. for (var index = 0; index < extensions.length; index++) {
  73133. files.push(rootUrl + extensions[index]);
  73134. }
  73135. }
  73136. }
  73137. _this._files = files;
  73138. if (!_this._texture) {
  73139. if (!scene.useDelayedTextureLoading) {
  73140. if (prefiltered) {
  73141. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, _this._createPolynomials);
  73142. }
  73143. else {
  73144. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension, false, lodScale, lodOffset);
  73145. }
  73146. }
  73147. else {
  73148. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  73149. }
  73150. }
  73151. else if (onLoad) {
  73152. if (_this._texture.isReady) {
  73153. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  73154. }
  73155. else {
  73156. _this._texture.onLoadedObservable.add(onLoad);
  73157. }
  73158. }
  73159. return _this;
  73160. }
  73161. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  73162. /**
  73163. * Returns the bounding box size
  73164. * @see http://doc.babylonjs.com/how_to/reflect#using-local-cubemap-mode
  73165. */
  73166. get: function () {
  73167. return this._boundingBoxSize;
  73168. },
  73169. /**
  73170. * Gets or sets the size of the bounding box associated with the cube texture
  73171. * When defined, the cubemap will switch to local mode
  73172. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  73173. * @example https://www.babylonjs-playground.com/#RNASML
  73174. */
  73175. set: function (value) {
  73176. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  73177. return;
  73178. }
  73179. this._boundingBoxSize = value;
  73180. var scene = this.getScene();
  73181. if (scene) {
  73182. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  73183. }
  73184. },
  73185. enumerable: true,
  73186. configurable: true
  73187. });
  73188. Object.defineProperty(CubeTexture.prototype, "rotationY", {
  73189. /**
  73190. * Gets texture matrix rotation angle around Y axis radians.
  73191. */
  73192. get: function () {
  73193. return this._rotationY;
  73194. },
  73195. /**
  73196. * Sets texture matrix rotation angle around Y axis in radians.
  73197. */
  73198. set: function (value) {
  73199. this._rotationY = value;
  73200. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  73201. },
  73202. enumerable: true,
  73203. configurable: true
  73204. });
  73205. /**
  73206. * Creates a cube texture from an array of image urls
  73207. * @param files defines an array of image urls
  73208. * @param scene defines the hosting scene
  73209. * @param noMipmap specifies if mip maps are not used
  73210. * @returns a cube texture
  73211. */
  73212. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  73213. var rootUrlKey = "";
  73214. files.forEach(function (url) { return rootUrlKey += url; });
  73215. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  73216. };
  73217. /**
  73218. * Creates and return a texture created from prefilterd data by tools like IBL Baker or Lys.
  73219. * @param url defines the url of the prefiltered texture
  73220. * @param scene defines the scene the texture is attached to
  73221. * @param forcedExtension defines the extension of the file if different from the url
  73222. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  73223. * @return the prefiltered texture
  73224. */
  73225. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension, createPolynomials) {
  73226. if (forcedExtension === void 0) { forcedExtension = null; }
  73227. if (createPolynomials === void 0) { createPolynomials = true; }
  73228. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension, createPolynomials);
  73229. };
  73230. /**
  73231. * Delays loading of the cube texture
  73232. */
  73233. CubeTexture.prototype.delayLoad = function () {
  73234. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  73235. return;
  73236. }
  73237. var scene = this.getScene();
  73238. if (!scene) {
  73239. return;
  73240. }
  73241. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  73242. this._texture = this._getFromCache(this.url, this._noMipmap);
  73243. if (!this._texture) {
  73244. if (this._prefiltered) {
  73245. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format, undefined, this._createPolynomials);
  73246. }
  73247. else {
  73248. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  73249. }
  73250. }
  73251. };
  73252. /**
  73253. * Returns the reflection texture matrix
  73254. * @returns the reflection texture matrix
  73255. */
  73256. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  73257. return this._textureMatrix;
  73258. };
  73259. /**
  73260. * Sets the reflection texture matrix
  73261. * @param value Reflection texture matrix
  73262. */
  73263. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  73264. this._textureMatrix = value;
  73265. };
  73266. /**
  73267. * Parses text to create a cube texture
  73268. * @param parsedTexture define the serialized text to read from
  73269. * @param scene defines the hosting scene
  73270. * @param rootUrl defines the root url of the cube texture
  73271. * @returns a cube texture
  73272. */
  73273. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  73274. var texture = BABYLON.SerializationHelper.Parse(function () {
  73275. var prefiltered = false;
  73276. if (parsedTexture.prefiltered) {
  73277. prefiltered = parsedTexture.prefiltered;
  73278. }
  73279. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions, false, null, null, null, undefined, prefiltered);
  73280. }, parsedTexture, scene);
  73281. // Local Cubemaps
  73282. if (parsedTexture.boundingBoxPosition) {
  73283. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  73284. }
  73285. if (parsedTexture.boundingBoxSize) {
  73286. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  73287. }
  73288. // Animations
  73289. if (parsedTexture.animations) {
  73290. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  73291. var parsedAnimation = parsedTexture.animations[animationIndex];
  73292. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  73293. }
  73294. }
  73295. return texture;
  73296. };
  73297. /**
  73298. * Makes a clone, or deep copy, of the cube texture
  73299. * @returns a new cube texture
  73300. */
  73301. CubeTexture.prototype.clone = function () {
  73302. var _this = this;
  73303. return BABYLON.SerializationHelper.Clone(function () {
  73304. var scene = _this.getScene();
  73305. if (!scene) {
  73306. return _this;
  73307. }
  73308. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  73309. }, this);
  73310. };
  73311. __decorate([
  73312. BABYLON.serialize("rotationY")
  73313. ], CubeTexture.prototype, "rotationY", null);
  73314. return CubeTexture;
  73315. }(BABYLON.BaseTexture));
  73316. BABYLON.CubeTexture = CubeTexture;
  73317. })(BABYLON || (BABYLON = {}));
  73318. //# sourceMappingURL=babylon.cubeTexture.js.map
  73319. var BABYLON;
  73320. (function (BABYLON) {
  73321. /**
  73322. * Raw cube texture where the raw buffers are passed in
  73323. */
  73324. var RawCubeTexture = /** @class */ (function (_super) {
  73325. __extends(RawCubeTexture, _super);
  73326. /**
  73327. * Creates a cube texture where the raw buffers are passed in.
  73328. * @param scene defines the scene the texture is attached to
  73329. * @param data defines the array of data to use to create each face
  73330. * @param size defines the size of the textures
  73331. * @param format defines the format of the data
  73332. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  73333. * @param generateMipMaps defines if the engine should generate the mip levels
  73334. * @param invertY defines if data must be stored with Y axis inverted
  73335. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  73336. * @param compression defines the compression used (null by default)
  73337. */
  73338. function RawCubeTexture(scene, data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  73339. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  73340. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  73341. if (generateMipMaps === void 0) { generateMipMaps = false; }
  73342. if (invertY === void 0) { invertY = false; }
  73343. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  73344. if (compression === void 0) { compression = null; }
  73345. var _this = _super.call(this, "", scene) || this;
  73346. _this._texture = scene.getEngine().createRawCubeTexture(data, size, format, type, generateMipMaps, invertY, samplingMode, compression);
  73347. return _this;
  73348. }
  73349. /**
  73350. * Updates the raw cube texture.
  73351. * @param data defines the data to store
  73352. * @param format defines the data format
  73353. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  73354. * @param invertY defines if data must be stored with Y axis inverted
  73355. * @param compression defines the compression used (null by default)
  73356. * @param level defines which level of the texture to update
  73357. */
  73358. RawCubeTexture.prototype.update = function (data, format, type, invertY, compression, level) {
  73359. if (compression === void 0) { compression = null; }
  73360. if (level === void 0) { level = 0; }
  73361. this._texture.getEngine().updateRawCubeTexture(this._texture, data, format, type, invertY, compression);
  73362. };
  73363. /**
  73364. * Updates a raw cube texture with RGBD encoded data.
  73365. * @param data defines the array of data [mipmap][face] to use to create each face
  73366. * @param sphericalPolynomial defines the spherical polynomial for irradiance
  73367. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  73368. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  73369. * @returns a promsie that resolves when the operation is complete
  73370. */
  73371. RawCubeTexture.prototype.updateRGBDAsync = function (data, sphericalPolynomial, lodScale, lodOffset) {
  73372. if (sphericalPolynomial === void 0) { sphericalPolynomial = null; }
  73373. if (lodScale === void 0) { lodScale = 0.8; }
  73374. if (lodOffset === void 0) { lodOffset = 0; }
  73375. return RawCubeTexture._UpdateRGBDAsync(this._texture, data, sphericalPolynomial, lodScale, lodOffset);
  73376. };
  73377. /**
  73378. * Clones the raw cube texture.
  73379. * @return a new cube texture
  73380. */
  73381. RawCubeTexture.prototype.clone = function () {
  73382. var _this = this;
  73383. return BABYLON.SerializationHelper.Clone(function () {
  73384. var scene = _this.getScene();
  73385. var internalTexture = _this._texture;
  73386. var texture = new RawCubeTexture(scene, internalTexture._bufferViewArray, internalTexture.width, internalTexture.format, internalTexture.type, internalTexture.generateMipMaps, internalTexture.invertY, internalTexture.samplingMode, internalTexture._compression);
  73387. if (internalTexture.dataSource === BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD) {
  73388. texture.updateRGBDAsync(internalTexture._bufferViewArrayArray, internalTexture._sphericalPolynomial, internalTexture._lodGenerationScale, internalTexture._lodGenerationOffset);
  73389. }
  73390. return texture;
  73391. }, this);
  73392. };
  73393. /** @hidden */
  73394. RawCubeTexture._UpdateRGBDAsync = function (internalTexture, data, sphericalPolynomial, lodScale, lodOffset) {
  73395. internalTexture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD;
  73396. internalTexture._bufferViewArrayArray = data;
  73397. internalTexture._lodGenerationScale = lodScale;
  73398. internalTexture._lodGenerationOffset = lodOffset;
  73399. internalTexture._sphericalPolynomial = sphericalPolynomial;
  73400. return BABYLON.EnvironmentTextureTools.UploadLevelsAsync(internalTexture, data).then(function () {
  73401. internalTexture.isReady = true;
  73402. });
  73403. };
  73404. return RawCubeTexture;
  73405. }(BABYLON.CubeTexture));
  73406. BABYLON.RawCubeTexture = RawCubeTexture;
  73407. })(BABYLON || (BABYLON = {}));
  73408. //# sourceMappingURL=babylon.rawCubeTexture.js.map
  73409. var BABYLON;
  73410. (function (BABYLON) {
  73411. /**
  73412. * This Helps creating a texture that will be created from a camera in your scene.
  73413. * It is basically a dynamic texture that could be used to create special effects for instance.
  73414. * Actually, It is the base of lot of effects in the framework like post process, shadows, effect layers and rendering pipelines...
  73415. */
  73416. var RenderTargetTexture = /** @class */ (function (_super) {
  73417. __extends(RenderTargetTexture, _super);
  73418. /**
  73419. * Instantiate a render target texture. This is mainly used to render of screen the scene to for instance apply post processse
  73420. * or used a shadow, depth texture...
  73421. * @param name The friendly name of the texture
  73422. * @param size The size of the RTT (number if square, or {width: number, height:number} or {ratio:} to define a ratio from the main scene)
  73423. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  73424. * @param generateMipMaps True if mip maps need to be generated after render.
  73425. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  73426. * @param type The type of the buffer in the RTT (int, half float, float...)
  73427. * @param isCube True if a cube texture needs to be created
  73428. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  73429. * @param generateDepthBuffer True to generate a depth buffer
  73430. * @param generateStencilBuffer True to generate a stencil buffer
  73431. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  73432. * @param format The internal format of the buffer in the RTT (RED, RG, RGB, RGBA, ALPHA...)
  73433. * @param delayAllocation if the texture allocation should be delayed (default: false)
  73434. */
  73435. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti, format, delayAllocation) {
  73436. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  73437. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  73438. if (isCube === void 0) { isCube = false; }
  73439. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  73440. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  73441. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  73442. if (isMulti === void 0) { isMulti = false; }
  73443. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  73444. if (delayAllocation === void 0) { delayAllocation = false; }
  73445. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  73446. _this.isCube = isCube;
  73447. /**
  73448. * Define if particles should be rendered in your texture.
  73449. */
  73450. _this.renderParticles = true;
  73451. /**
  73452. * Define if sprites should be rendered in your texture.
  73453. */
  73454. _this.renderSprites = false;
  73455. /**
  73456. * Override the default coordinates mode to projection for RTT as it is the most common case for rendered textures.
  73457. */
  73458. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  73459. /**
  73460. * Define if the camera viewport should be respected while rendering the texture or if the render should be done to the entire texture.
  73461. */
  73462. _this.ignoreCameraViewport = false;
  73463. /**
  73464. * An event triggered when the texture is unbind.
  73465. */
  73466. _this.onBeforeBindObservable = new BABYLON.Observable();
  73467. /**
  73468. * An event triggered when the texture is unbind.
  73469. */
  73470. _this.onAfterUnbindObservable = new BABYLON.Observable();
  73471. /**
  73472. * An event triggered before rendering the texture
  73473. */
  73474. _this.onBeforeRenderObservable = new BABYLON.Observable();
  73475. /**
  73476. * An event triggered after rendering the texture
  73477. */
  73478. _this.onAfterRenderObservable = new BABYLON.Observable();
  73479. /**
  73480. * An event triggered after the texture clear
  73481. */
  73482. _this.onClearObservable = new BABYLON.Observable();
  73483. _this._currentRefreshId = -1;
  73484. _this._refreshRate = 1;
  73485. _this._samples = 1;
  73486. /**
  73487. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  73488. * It must define where the camera used to render the texture is set
  73489. */
  73490. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  73491. scene = _this.getScene();
  73492. if (!scene) {
  73493. return _this;
  73494. }
  73495. _this.renderList = new Array();
  73496. _this._engine = scene.getEngine();
  73497. _this.name = name;
  73498. _this.isRenderTarget = true;
  73499. _this._initialSizeParameter = size;
  73500. _this._processSizeParameter(size);
  73501. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  73502. });
  73503. _this._generateMipMaps = generateMipMaps ? true : false;
  73504. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  73505. // Rendering groups
  73506. _this._renderingManager = new BABYLON.RenderingManager(scene);
  73507. _this._renderingManager._useSceneAutoClearSetup = true;
  73508. if (isMulti) {
  73509. return _this;
  73510. }
  73511. _this._renderTargetOptions = {
  73512. generateMipMaps: generateMipMaps,
  73513. type: type,
  73514. format: format,
  73515. samplingMode: samplingMode,
  73516. generateDepthBuffer: generateDepthBuffer,
  73517. generateStencilBuffer: generateStencilBuffer
  73518. };
  73519. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  73520. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73521. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73522. }
  73523. if (!delayAllocation) {
  73524. if (isCube) {
  73525. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  73526. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  73527. _this._textureMatrix = BABYLON.Matrix.Identity();
  73528. }
  73529. else {
  73530. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  73531. }
  73532. }
  73533. return _this;
  73534. }
  73535. Object.defineProperty(RenderTargetTexture.prototype, "renderList", {
  73536. /**
  73537. * Use this list to define the list of mesh you want to render.
  73538. */
  73539. get: function () {
  73540. return this._renderList;
  73541. },
  73542. set: function (value) {
  73543. this._renderList = value;
  73544. if (this._renderList) {
  73545. this._hookArray(this._renderList);
  73546. }
  73547. },
  73548. enumerable: true,
  73549. configurable: true
  73550. });
  73551. RenderTargetTexture.prototype._hookArray = function (array) {
  73552. var _this = this;
  73553. var oldPush = array.push;
  73554. array.push = function () {
  73555. var items = [];
  73556. for (var _i = 0; _i < arguments.length; _i++) {
  73557. items[_i] = arguments[_i];
  73558. }
  73559. var wasEmpty = array.length === 0;
  73560. var result = oldPush.apply(array, items);
  73561. if (wasEmpty) {
  73562. _this.getScene().meshes.forEach(function (mesh) {
  73563. mesh._markSubMeshesAsLightDirty();
  73564. });
  73565. }
  73566. return result;
  73567. };
  73568. var oldSplice = array.splice;
  73569. array.splice = function (index, deleteCount) {
  73570. var deleted = oldSplice.apply(array, [index, deleteCount]);
  73571. if (array.length === 0) {
  73572. _this.getScene().meshes.forEach(function (mesh) {
  73573. mesh._markSubMeshesAsLightDirty();
  73574. });
  73575. }
  73576. return deleted;
  73577. };
  73578. };
  73579. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  73580. /**
  73581. * Set a after unbind callback in the texture.
  73582. * This has been kept for backward compatibility and use of onAfterUnbindObservable is recommended.
  73583. */
  73584. set: function (callback) {
  73585. if (this._onAfterUnbindObserver) {
  73586. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  73587. }
  73588. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  73589. },
  73590. enumerable: true,
  73591. configurable: true
  73592. });
  73593. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  73594. /**
  73595. * Set a before render callback in the texture.
  73596. * This has been kept for backward compatibility and use of onBeforeRenderObservable is recommended.
  73597. */
  73598. set: function (callback) {
  73599. if (this._onBeforeRenderObserver) {
  73600. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  73601. }
  73602. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  73603. },
  73604. enumerable: true,
  73605. configurable: true
  73606. });
  73607. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  73608. /**
  73609. * Set a after render callback in the texture.
  73610. * This has been kept for backward compatibility and use of onAfterRenderObservable is recommended.
  73611. */
  73612. set: function (callback) {
  73613. if (this._onAfterRenderObserver) {
  73614. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  73615. }
  73616. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  73617. },
  73618. enumerable: true,
  73619. configurable: true
  73620. });
  73621. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  73622. /**
  73623. * Set a clear callback in the texture.
  73624. * This has been kept for backward compatibility and use of onClearObservable is recommended.
  73625. */
  73626. set: function (callback) {
  73627. if (this._onClearObserver) {
  73628. this.onClearObservable.remove(this._onClearObserver);
  73629. }
  73630. this._onClearObserver = this.onClearObservable.add(callback);
  73631. },
  73632. enumerable: true,
  73633. configurable: true
  73634. });
  73635. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  73636. /**
  73637. * Gets render target creation options that were used.
  73638. */
  73639. get: function () {
  73640. return this._renderTargetOptions;
  73641. },
  73642. enumerable: true,
  73643. configurable: true
  73644. });
  73645. RenderTargetTexture.prototype._onRatioRescale = function () {
  73646. if (this._sizeRatio) {
  73647. this.resize(this._initialSizeParameter);
  73648. }
  73649. };
  73650. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  73651. get: function () {
  73652. return this._boundingBoxSize;
  73653. },
  73654. /**
  73655. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  73656. * When defined, the cubemap will switch to local mode
  73657. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  73658. * @example https://www.babylonjs-playground.com/#RNASML
  73659. */
  73660. set: function (value) {
  73661. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  73662. return;
  73663. }
  73664. this._boundingBoxSize = value;
  73665. var scene = this.getScene();
  73666. if (scene) {
  73667. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  73668. }
  73669. },
  73670. enumerable: true,
  73671. configurable: true
  73672. });
  73673. /**
  73674. * Creates a depth stencil texture.
  73675. * This is only available in WebGL 2 or with the depth texture extension available.
  73676. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  73677. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  73678. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  73679. */
  73680. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  73681. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  73682. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  73683. if (generateStencil === void 0) { generateStencil = false; }
  73684. if (!this.getScene()) {
  73685. return;
  73686. }
  73687. var engine = this.getScene().getEngine();
  73688. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  73689. bilinearFiltering: bilinearFiltering,
  73690. comparisonFunction: comparisonFunction,
  73691. generateStencil: generateStencil,
  73692. isCube: this.isCube
  73693. });
  73694. engine.setFrameBufferDepthStencilTexture(this);
  73695. };
  73696. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  73697. if (size.ratio) {
  73698. this._sizeRatio = size.ratio;
  73699. this._size = {
  73700. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  73701. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  73702. };
  73703. }
  73704. else {
  73705. this._size = size;
  73706. }
  73707. };
  73708. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  73709. /**
  73710. * Define the number of samples to use in case of MSAA.
  73711. * It defaults to one meaning no MSAA has been enabled.
  73712. */
  73713. get: function () {
  73714. return this._samples;
  73715. },
  73716. set: function (value) {
  73717. if (this._samples === value) {
  73718. return;
  73719. }
  73720. var scene = this.getScene();
  73721. if (!scene) {
  73722. return;
  73723. }
  73724. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  73725. },
  73726. enumerable: true,
  73727. configurable: true
  73728. });
  73729. /**
  73730. * Resets the refresh counter of the texture and start bak from scratch.
  73731. * Could be usefull to regenerate the texture if it is setup to render only once.
  73732. */
  73733. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  73734. this._currentRefreshId = -1;
  73735. };
  73736. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  73737. /**
  73738. * Define the refresh rate of the texture or the rendering frequency.
  73739. * Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  73740. */
  73741. get: function () {
  73742. return this._refreshRate;
  73743. },
  73744. set: function (value) {
  73745. this._refreshRate = value;
  73746. this.resetRefreshCounter();
  73747. },
  73748. enumerable: true,
  73749. configurable: true
  73750. });
  73751. /**
  73752. * Adds a post process to the render target rendering passes.
  73753. * @param postProcess define the post process to add
  73754. */
  73755. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  73756. if (!this._postProcessManager) {
  73757. var scene = this.getScene();
  73758. if (!scene) {
  73759. return;
  73760. }
  73761. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  73762. this._postProcesses = new Array();
  73763. }
  73764. this._postProcesses.push(postProcess);
  73765. this._postProcesses[0].autoClear = false;
  73766. };
  73767. /**
  73768. * Clear all the post processes attached to the render target
  73769. * @param dispose define if the cleared post processesshould also be disposed (false by default)
  73770. */
  73771. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  73772. if (dispose === void 0) { dispose = false; }
  73773. if (!this._postProcesses) {
  73774. return;
  73775. }
  73776. if (dispose) {
  73777. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  73778. var postProcess = _a[_i];
  73779. postProcess.dispose();
  73780. }
  73781. }
  73782. this._postProcesses = [];
  73783. };
  73784. /**
  73785. * Remove one of the post process from the list of attached post processes to the texture
  73786. * @param postProcess define the post process to remove from the list
  73787. */
  73788. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  73789. if (!this._postProcesses) {
  73790. return;
  73791. }
  73792. var index = this._postProcesses.indexOf(postProcess);
  73793. if (index === -1) {
  73794. return;
  73795. }
  73796. this._postProcesses.splice(index, 1);
  73797. if (this._postProcesses.length > 0) {
  73798. this._postProcesses[0].autoClear = false;
  73799. }
  73800. };
  73801. /** @hidden */
  73802. RenderTargetTexture.prototype._shouldRender = function () {
  73803. if (this._currentRefreshId === -1) { // At least render once
  73804. this._currentRefreshId = 1;
  73805. return true;
  73806. }
  73807. if (this.refreshRate === this._currentRefreshId) {
  73808. this._currentRefreshId = 1;
  73809. return true;
  73810. }
  73811. this._currentRefreshId++;
  73812. return false;
  73813. };
  73814. /**
  73815. * Gets the actual render size of the texture.
  73816. * @returns the width of the render size
  73817. */
  73818. RenderTargetTexture.prototype.getRenderSize = function () {
  73819. return this.getRenderWidth();
  73820. };
  73821. /**
  73822. * Gets the actual render width of the texture.
  73823. * @returns the width of the render size
  73824. */
  73825. RenderTargetTexture.prototype.getRenderWidth = function () {
  73826. if (this._size.width) {
  73827. return this._size.width;
  73828. }
  73829. return this._size;
  73830. };
  73831. /**
  73832. * Gets the actual render height of the texture.
  73833. * @returns the height of the render size
  73834. */
  73835. RenderTargetTexture.prototype.getRenderHeight = function () {
  73836. if (this._size.width) {
  73837. return this._size.height;
  73838. }
  73839. return this._size;
  73840. };
  73841. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  73842. /**
  73843. * Get if the texture can be rescaled or not.
  73844. */
  73845. get: function () {
  73846. return true;
  73847. },
  73848. enumerable: true,
  73849. configurable: true
  73850. });
  73851. /**
  73852. * Resize the texture using a ratio.
  73853. * @param ratio the ratio to apply to the texture size in order to compute the new target size
  73854. */
  73855. RenderTargetTexture.prototype.scale = function (ratio) {
  73856. var newSize = this.getRenderSize() * ratio;
  73857. this.resize(newSize);
  73858. };
  73859. /**
  73860. * Get the texture reflection matrix used to rotate/transform the reflection.
  73861. * @returns the reflection matrix
  73862. */
  73863. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  73864. if (this.isCube) {
  73865. return this._textureMatrix;
  73866. }
  73867. return _super.prototype.getReflectionTextureMatrix.call(this);
  73868. };
  73869. /**
  73870. * Resize the texture to a new desired size.
  73871. * Be carrefull as it will recreate all the data in the new texture.
  73872. * @param size Define the new size. It can be:
  73873. * - a number for squared texture,
  73874. * - an object containing { width: number, height: number }
  73875. * - or an object containing a ratio { ratio: number }
  73876. */
  73877. RenderTargetTexture.prototype.resize = function (size) {
  73878. this.releaseInternalTexture();
  73879. var scene = this.getScene();
  73880. if (!scene) {
  73881. return;
  73882. }
  73883. this._processSizeParameter(size);
  73884. if (this.isCube) {
  73885. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  73886. }
  73887. else {
  73888. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  73889. }
  73890. };
  73891. /**
  73892. * Renders all the objects from the render list into the texture.
  73893. * @param useCameraPostProcess Define if camera post processes should be used during the rendering
  73894. * @param dumpForDebug Define if the rendering result should be dumped (copied) for debugging purpose
  73895. */
  73896. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  73897. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  73898. if (dumpForDebug === void 0) { dumpForDebug = false; }
  73899. var scene = this.getScene();
  73900. if (!scene) {
  73901. return;
  73902. }
  73903. var engine = scene.getEngine();
  73904. if (this.useCameraPostProcesses !== undefined) {
  73905. useCameraPostProcess = this.useCameraPostProcesses;
  73906. }
  73907. if (this._waitingRenderList) {
  73908. this.renderList = [];
  73909. for (var index = 0; index < this._waitingRenderList.length; index++) {
  73910. var id = this._waitingRenderList[index];
  73911. var mesh_1 = scene.getMeshByID(id);
  73912. if (mesh_1) {
  73913. this.renderList.push(mesh_1);
  73914. }
  73915. }
  73916. delete this._waitingRenderList;
  73917. }
  73918. // Is predicate defined?
  73919. if (this.renderListPredicate) {
  73920. if (this.renderList) {
  73921. this.renderList.length = 0; // Clear previous renderList
  73922. }
  73923. else {
  73924. this.renderList = [];
  73925. }
  73926. var scene = this.getScene();
  73927. if (!scene) {
  73928. return;
  73929. }
  73930. var sceneMeshes = scene.meshes;
  73931. for (var index = 0; index < sceneMeshes.length; index++) {
  73932. var mesh = sceneMeshes[index];
  73933. if (this.renderListPredicate(mesh)) {
  73934. this.renderList.push(mesh);
  73935. }
  73936. }
  73937. }
  73938. this.onBeforeBindObservable.notifyObservers(this);
  73939. // Set custom projection.
  73940. // Needs to be before binding to prevent changing the aspect ratio.
  73941. var camera;
  73942. if (this.activeCamera) {
  73943. camera = this.activeCamera;
  73944. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  73945. if (this.activeCamera !== scene.activeCamera) {
  73946. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  73947. }
  73948. }
  73949. else {
  73950. camera = scene.activeCamera;
  73951. if (camera) {
  73952. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  73953. }
  73954. }
  73955. // Prepare renderingManager
  73956. this._renderingManager.reset();
  73957. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  73958. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  73959. var sceneRenderId = scene.getRenderId();
  73960. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  73961. var mesh = currentRenderList[meshIndex];
  73962. if (mesh) {
  73963. if (!mesh.isReady(this.refreshRate === 0)) {
  73964. this.resetRefreshCounter();
  73965. continue;
  73966. }
  73967. mesh._preActivateForIntermediateRendering(sceneRenderId);
  73968. var isMasked = void 0;
  73969. if (!this.renderList && camera) {
  73970. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  73971. }
  73972. else {
  73973. isMasked = false;
  73974. }
  73975. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  73976. mesh._activate(sceneRenderId);
  73977. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  73978. var subMesh = mesh.subMeshes[subIndex];
  73979. scene._activeIndices.addCount(subMesh.indexCount, false);
  73980. this._renderingManager.dispatch(subMesh, mesh);
  73981. }
  73982. }
  73983. }
  73984. }
  73985. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  73986. var particleSystem = scene.particleSystems[particleIndex];
  73987. var emitter = particleSystem.emitter;
  73988. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  73989. continue;
  73990. }
  73991. if (currentRenderList.indexOf(emitter) >= 0) {
  73992. this._renderingManager.dispatchParticles(particleSystem);
  73993. }
  73994. }
  73995. if (this.isCube) {
  73996. for (var face = 0; face < 6; face++) {
  73997. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  73998. scene.incrementRenderId();
  73999. scene.resetCachedMaterial();
  74000. }
  74001. }
  74002. else {
  74003. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  74004. }
  74005. this.onAfterUnbindObservable.notifyObservers(this);
  74006. if (scene.activeCamera) {
  74007. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  74008. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  74009. }
  74010. engine.setViewport(scene.activeCamera.viewport);
  74011. }
  74012. scene.resetCachedMaterial();
  74013. };
  74014. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  74015. var minimum = 128;
  74016. var x = renderDimension * scale;
  74017. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  74018. // Ensure we don't exceed the render dimension (while staying POT)
  74019. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  74020. };
  74021. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  74022. var _this = this;
  74023. if (!this._texture) {
  74024. return;
  74025. }
  74026. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  74027. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  74028. });
  74029. };
  74030. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  74031. var scene = this.getScene();
  74032. if (!scene) {
  74033. return;
  74034. }
  74035. var engine = scene.getEngine();
  74036. if (!this._texture) {
  74037. return;
  74038. }
  74039. // Bind
  74040. if (this._postProcessManager) {
  74041. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  74042. }
  74043. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  74044. if (this._texture) {
  74045. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  74046. }
  74047. }
  74048. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  74049. // Clear
  74050. if (this.onClearObservable.hasObservers()) {
  74051. this.onClearObservable.notifyObservers(engine);
  74052. }
  74053. else {
  74054. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  74055. }
  74056. if (!this._doNotChangeAspectRatio) {
  74057. scene.updateTransformMatrix(true);
  74058. }
  74059. // Before Camera Draw
  74060. for (var _i = 0, _a = scene._beforeRenderTargetDrawStage; _i < _a.length; _i++) {
  74061. var step = _a[_i];
  74062. step.action(this);
  74063. }
  74064. // Render
  74065. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  74066. // After Camera Draw
  74067. for (var _b = 0, _c = scene._afterRenderTargetDrawStage; _b < _c.length; _b++) {
  74068. var step = _c[_b];
  74069. step.action(this);
  74070. }
  74071. if (this._postProcessManager) {
  74072. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  74073. }
  74074. else if (useCameraPostProcess) {
  74075. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  74076. }
  74077. if (!this._doNotChangeAspectRatio) {
  74078. scene.updateTransformMatrix(true);
  74079. }
  74080. // Dump ?
  74081. if (dumpForDebug) {
  74082. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  74083. }
  74084. // Unbind
  74085. if (!this.isCube || faceIndex === 5) {
  74086. if (this.isCube) {
  74087. if (faceIndex === 5) {
  74088. engine.generateMipMapsForCubemap(this._texture);
  74089. }
  74090. }
  74091. this.unbindFrameBuffer(engine, faceIndex);
  74092. }
  74093. else {
  74094. this.onAfterRenderObservable.notifyObservers(faceIndex);
  74095. }
  74096. };
  74097. /**
  74098. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  74099. * This allowed control for front to back rendering or reversly depending of the special needs.
  74100. *
  74101. * @param renderingGroupId The rendering group id corresponding to its index
  74102. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  74103. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  74104. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  74105. */
  74106. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  74107. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  74108. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  74109. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  74110. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  74111. };
  74112. /**
  74113. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  74114. *
  74115. * @param renderingGroupId The rendering group id corresponding to its index
  74116. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  74117. */
  74118. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  74119. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  74120. this._renderingManager._useSceneAutoClearSetup = false;
  74121. };
  74122. /**
  74123. * Clones the texture.
  74124. * @returns the cloned texture
  74125. */
  74126. RenderTargetTexture.prototype.clone = function () {
  74127. var textureSize = this.getSize();
  74128. 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);
  74129. // Base texture
  74130. newTexture.hasAlpha = this.hasAlpha;
  74131. newTexture.level = this.level;
  74132. // RenderTarget Texture
  74133. newTexture.coordinatesMode = this.coordinatesMode;
  74134. if (this.renderList) {
  74135. newTexture.renderList = this.renderList.slice(0);
  74136. }
  74137. return newTexture;
  74138. };
  74139. /**
  74140. * Serialize the texture to a JSON representation we can easily use in the resepective Parse function.
  74141. * @returns The JSON representation of the texture
  74142. */
  74143. RenderTargetTexture.prototype.serialize = function () {
  74144. if (!this.name) {
  74145. return null;
  74146. }
  74147. var serializationObject = _super.prototype.serialize.call(this);
  74148. serializationObject.renderTargetSize = this.getRenderSize();
  74149. serializationObject.renderList = [];
  74150. if (this.renderList) {
  74151. for (var index = 0; index < this.renderList.length; index++) {
  74152. serializationObject.renderList.push(this.renderList[index].id);
  74153. }
  74154. }
  74155. return serializationObject;
  74156. };
  74157. /**
  74158. * This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  74159. */
  74160. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  74161. var objBuffer = this.getInternalTexture();
  74162. var scene = this.getScene();
  74163. if (objBuffer && scene) {
  74164. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  74165. }
  74166. };
  74167. /**
  74168. * Dispose the texture and release its associated resources.
  74169. */
  74170. RenderTargetTexture.prototype.dispose = function () {
  74171. if (this._postProcessManager) {
  74172. this._postProcessManager.dispose();
  74173. this._postProcessManager = null;
  74174. }
  74175. this.clearPostProcesses(true);
  74176. if (this._resizeObserver) {
  74177. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  74178. this._resizeObserver = null;
  74179. }
  74180. this.renderList = null;
  74181. // Remove from custom render targets
  74182. var scene = this.getScene();
  74183. if (!scene) {
  74184. return;
  74185. }
  74186. var index = scene.customRenderTargets.indexOf(this);
  74187. if (index >= 0) {
  74188. scene.customRenderTargets.splice(index, 1);
  74189. }
  74190. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  74191. var camera = _a[_i];
  74192. index = camera.customRenderTargets.indexOf(this);
  74193. if (index >= 0) {
  74194. camera.customRenderTargets.splice(index, 1);
  74195. }
  74196. }
  74197. _super.prototype.dispose.call(this);
  74198. };
  74199. /** @hidden */
  74200. RenderTargetTexture.prototype._rebuild = function () {
  74201. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  74202. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  74203. }
  74204. if (this._postProcessManager) {
  74205. this._postProcessManager._rebuild();
  74206. }
  74207. };
  74208. /**
  74209. * Clear the info related to rendering groups preventing retention point in material dispose.
  74210. */
  74211. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  74212. if (this._renderingManager) {
  74213. this._renderingManager.freeRenderingGroups();
  74214. }
  74215. };
  74216. /**
  74217. * The texture will only be rendered once which can be useful to improve performance if everything in your render is static for instance.
  74218. */
  74219. RenderTargetTexture.REFRESHRATE_RENDER_ONCE = 0;
  74220. /**
  74221. * The texture will only be rendered rendered every frame and is recomended for dynamic contents.
  74222. */
  74223. RenderTargetTexture.REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  74224. /**
  74225. * The texture will be rendered every 2 frames which could be enough if your dynamic objects are not
  74226. * the central point of your effect and can save a lot of performances.
  74227. */
  74228. RenderTargetTexture.REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  74229. return RenderTargetTexture;
  74230. }(BABYLON.Texture));
  74231. BABYLON.RenderTargetTexture = RenderTargetTexture;
  74232. })(BABYLON || (BABYLON = {}));
  74233. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  74234. var BABYLON;
  74235. (function (BABYLON) {
  74236. /**
  74237. * A multi render target, like a render target provides the ability to render to a texture.
  74238. * Unlike the render target, it can render to several draw buffers in one draw.
  74239. * This is specially interesting in deferred rendering or for any effects requiring more than
  74240. * just one color from a single pass.
  74241. */
  74242. var MultiRenderTarget = /** @class */ (function (_super) {
  74243. __extends(MultiRenderTarget, _super);
  74244. /**
  74245. * Instantiate a new multi render target texture.
  74246. * A multi render target, like a render target provides the ability to render to a texture.
  74247. * Unlike the render target, it can render to several draw buffers in one draw.
  74248. * This is specially interesting in deferred rendering or for any effects requiring more than
  74249. * just one color from a single pass.
  74250. * @param name Define the name of the texture
  74251. * @param size Define the size of the buffers to render to
  74252. * @param count Define the number of target we are rendering into
  74253. * @param scene Define the scene the texture belongs to
  74254. * @param options Define the options used to create the multi render target
  74255. */
  74256. function MultiRenderTarget(name, size, count, scene, options) {
  74257. var _this = this;
  74258. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  74259. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  74260. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  74261. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  74262. _this._engine = scene.getEngine();
  74263. if (!_this.isSupported) {
  74264. _this.dispose();
  74265. return;
  74266. }
  74267. var types = [];
  74268. var samplingModes = [];
  74269. for (var i = 0; i < count; i++) {
  74270. if (options && options.types && options.types[i] !== undefined) {
  74271. types.push(options.types[i]);
  74272. }
  74273. else {
  74274. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  74275. }
  74276. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  74277. samplingModes.push(options.samplingModes[i]);
  74278. }
  74279. else {
  74280. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  74281. }
  74282. }
  74283. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  74284. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  74285. _this._size = size;
  74286. _this._multiRenderTargetOptions = {
  74287. samplingModes: samplingModes,
  74288. generateMipMaps: generateMipMaps,
  74289. generateDepthBuffer: generateDepthBuffer,
  74290. generateStencilBuffer: generateStencilBuffer,
  74291. generateDepthTexture: generateDepthTexture,
  74292. types: types,
  74293. textureCount: count
  74294. };
  74295. _this._createInternalTextures();
  74296. _this._createTextures();
  74297. return _this;
  74298. }
  74299. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  74300. /**
  74301. * Get if draw buffers are currently supported by the used hardware and browser.
  74302. */
  74303. get: function () {
  74304. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  74305. },
  74306. enumerable: true,
  74307. configurable: true
  74308. });
  74309. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  74310. /**
  74311. * Get the list of textures generated by the multi render target.
  74312. */
  74313. get: function () {
  74314. return this._textures;
  74315. },
  74316. enumerable: true,
  74317. configurable: true
  74318. });
  74319. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  74320. /**
  74321. * Get the depth texture generated by the multi render target if options.generateDepthTexture has been set
  74322. */
  74323. get: function () {
  74324. return this._textures[this._textures.length - 1];
  74325. },
  74326. enumerable: true,
  74327. configurable: true
  74328. });
  74329. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  74330. /**
  74331. * Set the wrapping mode on U of all the textures we are rendering to.
  74332. * Can be any of the Texture. (CLAMP_ADDRESSMODE, MIRROR_ADDRESSMODE or WRAP_ADDRESSMODE)
  74333. */
  74334. set: function (wrap) {
  74335. if (this._textures) {
  74336. for (var i = 0; i < this._textures.length; i++) {
  74337. this._textures[i].wrapU = wrap;
  74338. }
  74339. }
  74340. },
  74341. enumerable: true,
  74342. configurable: true
  74343. });
  74344. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  74345. /**
  74346. * Set the wrapping mode on V of all the textures we are rendering to.
  74347. * Can be any of the Texture. (CLAMP_ADDRESSMODE, MIRROR_ADDRESSMODE or WRAP_ADDRESSMODE)
  74348. */
  74349. set: function (wrap) {
  74350. if (this._textures) {
  74351. for (var i = 0; i < this._textures.length; i++) {
  74352. this._textures[i].wrapV = wrap;
  74353. }
  74354. }
  74355. },
  74356. enumerable: true,
  74357. configurable: true
  74358. });
  74359. /** @hidden */
  74360. MultiRenderTarget.prototype._rebuild = function () {
  74361. this.releaseInternalTextures();
  74362. this._createInternalTextures();
  74363. for (var i = 0; i < this._internalTextures.length; i++) {
  74364. var texture = this._textures[i];
  74365. texture._texture = this._internalTextures[i];
  74366. }
  74367. // Keeps references to frame buffer and stencil/depth buffer
  74368. this._texture = this._internalTextures[0];
  74369. };
  74370. MultiRenderTarget.prototype._createInternalTextures = function () {
  74371. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  74372. };
  74373. MultiRenderTarget.prototype._createTextures = function () {
  74374. this._textures = [];
  74375. for (var i = 0; i < this._internalTextures.length; i++) {
  74376. var texture = new BABYLON.Texture(null, this.getScene());
  74377. texture._texture = this._internalTextures[i];
  74378. this._textures.push(texture);
  74379. }
  74380. // Keeps references to frame buffer and stencil/depth buffer
  74381. this._texture = this._internalTextures[0];
  74382. };
  74383. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  74384. /**
  74385. * Define the number of samples used if MSAA is enabled.
  74386. */
  74387. get: function () {
  74388. return this._samples;
  74389. },
  74390. set: function (value) {
  74391. if (this._samples === value) {
  74392. return;
  74393. }
  74394. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  74395. },
  74396. enumerable: true,
  74397. configurable: true
  74398. });
  74399. /**
  74400. * Resize all the textures in the multi render target.
  74401. * Be carrefull as it will recreate all the data in the new texture.
  74402. * @param size Define the new size
  74403. */
  74404. MultiRenderTarget.prototype.resize = function (size) {
  74405. this.releaseInternalTextures();
  74406. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  74407. this._createInternalTextures();
  74408. };
  74409. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  74410. var _this = this;
  74411. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  74412. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  74413. });
  74414. };
  74415. /**
  74416. * Dispose the render targets and their associated resources
  74417. */
  74418. MultiRenderTarget.prototype.dispose = function () {
  74419. this.releaseInternalTextures();
  74420. _super.prototype.dispose.call(this);
  74421. };
  74422. /**
  74423. * Release all the underlying texture used as draw buffers.
  74424. */
  74425. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  74426. if (!this._internalTextures) {
  74427. return;
  74428. }
  74429. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  74430. if (this._internalTextures[i] !== undefined) {
  74431. this._internalTextures[i].dispose();
  74432. this._internalTextures.splice(i, 1);
  74433. }
  74434. }
  74435. };
  74436. return MultiRenderTarget;
  74437. }(BABYLON.RenderTargetTexture));
  74438. BABYLON.MultiRenderTarget = MultiRenderTarget;
  74439. })(BABYLON || (BABYLON = {}));
  74440. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  74441. var BABYLON;
  74442. (function (BABYLON) {
  74443. /**
  74444. * Mirror texture can be used to simulate the view from a mirror in a scene.
  74445. * It will dynamically be rendered every frame to adapt to the camera point of view.
  74446. * You can then easily use it as a reflectionTexture on a flat surface.
  74447. * In case the surface is not a plane, please consider relying on reflection probes.
  74448. * @see https://doc.babylonjs.com/how_to/reflect#mirrors
  74449. */
  74450. var MirrorTexture = /** @class */ (function (_super) {
  74451. __extends(MirrorTexture, _super);
  74452. /**
  74453. * Instantiates a Mirror Texture.
  74454. * Mirror texture can be used to simulate the view from a mirror in a scene.
  74455. * It will dynamically be rendered every frame to adapt to the camera point of view.
  74456. * You can then easily use it as a reflectionTexture on a flat surface.
  74457. * In case the surface is not a plane, please consider relying on reflection probes.
  74458. * @see https://doc.babylonjs.com/how_to/reflect#mirrors
  74459. * @param name
  74460. * @param size
  74461. * @param scene
  74462. * @param generateMipMaps
  74463. * @param type
  74464. * @param samplingMode
  74465. * @param generateDepthBuffer
  74466. */
  74467. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  74468. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74469. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  74470. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  74471. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  74472. _this.scene = scene;
  74473. /**
  74474. * Define the reflection plane we want to use. The mirrorPlane is usually set to the constructed reflector.
  74475. * It is possible to directly set the mirrorPlane by directly using a BABYLON.Plane(a, b, c, d) where a, b and c give the plane normal vector (a, b, c) and d is a scalar displacement from the mirrorPlane to the origin. However in all but the very simplest of situations it is more straight forward to set it to the reflector as stated in the doc.
  74476. * @see https://doc.babylonjs.com/how_to/reflect#mirrors
  74477. */
  74478. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  74479. _this._transformMatrix = BABYLON.Matrix.Zero();
  74480. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  74481. _this._adaptiveBlurKernel = 0;
  74482. _this._blurKernelX = 0;
  74483. _this._blurKernelY = 0;
  74484. _this._blurRatio = 1.0;
  74485. _this.ignoreCameraViewport = true;
  74486. _this._updateGammaSpace();
  74487. _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  74488. _this._updateGammaSpace;
  74489. });
  74490. _this.onBeforeRenderObservable.add(function () {
  74491. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  74492. _this._savedViewMatrix = scene.getViewMatrix();
  74493. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  74494. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  74495. scene.clipPlane = _this.mirrorPlane;
  74496. scene.getEngine().cullBackFaces = false;
  74497. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  74498. });
  74499. _this.onAfterRenderObservable.add(function () {
  74500. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  74501. scene.getEngine().cullBackFaces = true;
  74502. scene._mirroredCameraPosition = null;
  74503. delete scene.clipPlane;
  74504. });
  74505. return _this;
  74506. }
  74507. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  74508. get: function () {
  74509. return this._blurRatio;
  74510. },
  74511. /**
  74512. * Define the blur ratio used to blur the reflection if needed.
  74513. */
  74514. set: function (value) {
  74515. if (this._blurRatio === value) {
  74516. return;
  74517. }
  74518. this._blurRatio = value;
  74519. this._preparePostProcesses();
  74520. },
  74521. enumerable: true,
  74522. configurable: true
  74523. });
  74524. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  74525. /**
  74526. * Define the adaptive blur kernel used to blur the reflection if needed.
  74527. * This will autocompute the closest best match for the `blurKernel`
  74528. */
  74529. set: function (value) {
  74530. this._adaptiveBlurKernel = value;
  74531. this._autoComputeBlurKernel();
  74532. },
  74533. enumerable: true,
  74534. configurable: true
  74535. });
  74536. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  74537. /**
  74538. * Define the blur kernel used to blur the reflection if needed.
  74539. * Please consider using `adaptiveBlurKernel` as it could find the closest best value for you.
  74540. */
  74541. set: function (value) {
  74542. this.blurKernelX = value;
  74543. this.blurKernelY = value;
  74544. },
  74545. enumerable: true,
  74546. configurable: true
  74547. });
  74548. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  74549. get: function () {
  74550. return this._blurKernelX;
  74551. },
  74552. /**
  74553. * Define the blur kernel on the X Axis used to blur the reflection if needed.
  74554. * Please consider using `adaptiveBlurKernel` as it could find the closest best value for you.
  74555. */
  74556. set: function (value) {
  74557. if (this._blurKernelX === value) {
  74558. return;
  74559. }
  74560. this._blurKernelX = value;
  74561. this._preparePostProcesses();
  74562. },
  74563. enumerable: true,
  74564. configurable: true
  74565. });
  74566. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  74567. get: function () {
  74568. return this._blurKernelY;
  74569. },
  74570. /**
  74571. * Define the blur kernel on the Y Axis used to blur the reflection if needed.
  74572. * Please consider using `adaptiveBlurKernel` as it could find the closest best value for you.
  74573. */
  74574. set: function (value) {
  74575. if (this._blurKernelY === value) {
  74576. return;
  74577. }
  74578. this._blurKernelY = value;
  74579. this._preparePostProcesses();
  74580. },
  74581. enumerable: true,
  74582. configurable: true
  74583. });
  74584. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  74585. var engine = this.getScene().getEngine();
  74586. var dw = this.getRenderWidth() / engine.getRenderWidth();
  74587. var dh = this.getRenderHeight() / engine.getRenderHeight();
  74588. this.blurKernelX = this._adaptiveBlurKernel * dw;
  74589. this.blurKernelY = this._adaptiveBlurKernel * dh;
  74590. };
  74591. MirrorTexture.prototype._onRatioRescale = function () {
  74592. if (this._sizeRatio) {
  74593. this.resize(this._initialSizeParameter);
  74594. if (!this._adaptiveBlurKernel) {
  74595. this._preparePostProcesses();
  74596. }
  74597. }
  74598. if (this._adaptiveBlurKernel) {
  74599. this._autoComputeBlurKernel();
  74600. }
  74601. };
  74602. MirrorTexture.prototype._updateGammaSpace = function () {
  74603. this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;
  74604. };
  74605. MirrorTexture.prototype._preparePostProcesses = function () {
  74606. this.clearPostProcesses(true);
  74607. if (this._blurKernelX && this._blurKernelY) {
  74608. var engine = this.getScene().getEngine();
  74609. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  74610. 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);
  74611. this._blurX.autoClear = false;
  74612. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  74613. this._blurX.inputTexture = this._texture;
  74614. }
  74615. else {
  74616. this._blurX.alwaysForcePOT = true;
  74617. }
  74618. 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);
  74619. this._blurY.autoClear = false;
  74620. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  74621. this.addPostProcess(this._blurX);
  74622. this.addPostProcess(this._blurY);
  74623. }
  74624. else {
  74625. if (this._blurY) {
  74626. this.removePostProcess(this._blurY);
  74627. this._blurY.dispose();
  74628. this._blurY = null;
  74629. }
  74630. if (this._blurX) {
  74631. this.removePostProcess(this._blurX);
  74632. this._blurX.dispose();
  74633. this._blurX = null;
  74634. }
  74635. }
  74636. };
  74637. /**
  74638. * Clone the mirror texture.
  74639. * @returns the cloned texture
  74640. */
  74641. MirrorTexture.prototype.clone = function () {
  74642. var scene = this.getScene();
  74643. if (!scene) {
  74644. return this;
  74645. }
  74646. var textureSize = this.getSize();
  74647. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  74648. // Base texture
  74649. newTexture.hasAlpha = this.hasAlpha;
  74650. newTexture.level = this.level;
  74651. // Mirror Texture
  74652. newTexture.mirrorPlane = this.mirrorPlane.clone();
  74653. if (this.renderList) {
  74654. newTexture.renderList = this.renderList.slice(0);
  74655. }
  74656. return newTexture;
  74657. };
  74658. /**
  74659. * Serialize the texture to a JSON representation you could use in Parse later on
  74660. * @returns the serialized JSON representation
  74661. */
  74662. MirrorTexture.prototype.serialize = function () {
  74663. if (!this.name) {
  74664. return null;
  74665. }
  74666. var serializationObject = _super.prototype.serialize.call(this);
  74667. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  74668. return serializationObject;
  74669. };
  74670. /**
  74671. * Dispose the texture and release its associated resources.
  74672. */
  74673. MirrorTexture.prototype.dispose = function () {
  74674. _super.prototype.dispose.call(this);
  74675. this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
  74676. };
  74677. return MirrorTexture;
  74678. }(BABYLON.RenderTargetTexture));
  74679. BABYLON.MirrorTexture = MirrorTexture;
  74680. })(BABYLON || (BABYLON = {}));
  74681. //# sourceMappingURL=babylon.mirrorTexture.js.map
  74682. var BABYLON;
  74683. (function (BABYLON) {
  74684. /**
  74685. * Creates a refraction texture used by refraction channel of the standard material.
  74686. * It is like a mirror but to see through a material.
  74687. * @see https://doc.babylonjs.com/how_to/reflect#refraction
  74688. */
  74689. var RefractionTexture = /** @class */ (function (_super) {
  74690. __extends(RefractionTexture, _super);
  74691. /**
  74692. * Creates a refraction texture used by refraction channel of the standard material.
  74693. * It is like a mirror but to see through a material.
  74694. * @see https://doc.babylonjs.com/how_to/reflect#refraction
  74695. * @param name Define the texture name
  74696. * @param size Define the size of the underlying texture
  74697. * @param scene Define the scene the refraction belongs to
  74698. * @param generateMipMaps Define if we need to generate mips level for the refraction
  74699. */
  74700. function RefractionTexture(name, size, scene, generateMipMaps) {
  74701. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  74702. /**
  74703. * Define the reflection plane we want to use. The refractionPlane is usually set to the constructed refractor.
  74704. * It is possible to directly set the refractionPlane by directly using a BABYLON.Plane(a, b, c, d) where a, b and c give the plane normal vector (a, b, c) and d is a scalar displacement from the refractionPlane to the origin. However in all but the very simplest of situations it is more straight forward to set it to the refractor as stated in the doc.
  74705. * @see https://doc.babylonjs.com/how_to/reflect#refraction
  74706. */
  74707. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  74708. /**
  74709. * Define how deep under the surface we should see.
  74710. */
  74711. _this.depth = 2.0;
  74712. _this.onBeforeRenderObservable.add(function () {
  74713. scene.clipPlane = _this.refractionPlane;
  74714. });
  74715. _this.onAfterRenderObservable.add(function () {
  74716. delete scene.clipPlane;
  74717. });
  74718. return _this;
  74719. }
  74720. /**
  74721. * Clone the refraction texture.
  74722. * @returns the cloned texture
  74723. */
  74724. RefractionTexture.prototype.clone = function () {
  74725. var scene = this.getScene();
  74726. if (!scene) {
  74727. return this;
  74728. }
  74729. var textureSize = this.getSize();
  74730. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  74731. // Base texture
  74732. newTexture.hasAlpha = this.hasAlpha;
  74733. newTexture.level = this.level;
  74734. // Refraction Texture
  74735. newTexture.refractionPlane = this.refractionPlane.clone();
  74736. if (this.renderList) {
  74737. newTexture.renderList = this.renderList.slice(0);
  74738. }
  74739. newTexture.depth = this.depth;
  74740. return newTexture;
  74741. };
  74742. /**
  74743. * Serialize the texture to a JSON representation you could use in Parse later on
  74744. * @returns the serialized JSON representation
  74745. */
  74746. RefractionTexture.prototype.serialize = function () {
  74747. if (!this.name) {
  74748. return null;
  74749. }
  74750. var serializationObject = _super.prototype.serialize.call(this);
  74751. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  74752. serializationObject.depth = this.depth;
  74753. return serializationObject;
  74754. };
  74755. return RefractionTexture;
  74756. }(BABYLON.RenderTargetTexture));
  74757. BABYLON.RefractionTexture = RefractionTexture;
  74758. })(BABYLON || (BABYLON = {}));
  74759. //# sourceMappingURL=babylon.refractionTexture.js.map
  74760. var BABYLON;
  74761. (function (BABYLON) {
  74762. /**
  74763. * A class extending Texture allowing drawing on a texture
  74764. * @see http://doc.babylonjs.com/how_to/dynamictexture
  74765. */
  74766. var DynamicTexture = /** @class */ (function (_super) {
  74767. __extends(DynamicTexture, _super);
  74768. /**
  74769. * Creates a DynamicTexture
  74770. * @param name defines the name of the texture
  74771. * @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
  74772. * @param scene defines the scene where you want the texture
  74773. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  74774. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  74775. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  74776. */
  74777. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  74778. if (scene === void 0) { scene = null; }
  74779. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  74780. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  74781. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  74782. _this.name = name;
  74783. _this._engine = _this.getScene().getEngine();
  74784. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  74785. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  74786. _this._generateMipMaps = generateMipMaps;
  74787. if (options.getContext) {
  74788. _this._canvas = options;
  74789. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  74790. }
  74791. else {
  74792. _this._canvas = document.createElement("canvas");
  74793. if (options.width || options.width === 0) {
  74794. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  74795. }
  74796. else {
  74797. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  74798. }
  74799. }
  74800. var textureSize = _this.getSize();
  74801. _this._canvas.width = textureSize.width;
  74802. _this._canvas.height = textureSize.height;
  74803. _this._context = _this._canvas.getContext("2d");
  74804. return _this;
  74805. }
  74806. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  74807. /**
  74808. * Gets the current state of canRescale
  74809. */
  74810. get: function () {
  74811. return true;
  74812. },
  74813. enumerable: true,
  74814. configurable: true
  74815. });
  74816. DynamicTexture.prototype._recreate = function (textureSize) {
  74817. this._canvas.width = textureSize.width;
  74818. this._canvas.height = textureSize.height;
  74819. this.releaseInternalTexture();
  74820. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  74821. };
  74822. /**
  74823. * Scales the texture
  74824. * @param ratio the scale factor to apply to both width and height
  74825. */
  74826. DynamicTexture.prototype.scale = function (ratio) {
  74827. var textureSize = this.getSize();
  74828. textureSize.width *= ratio;
  74829. textureSize.height *= ratio;
  74830. this._recreate(textureSize);
  74831. };
  74832. /**
  74833. * Resizes the texture
  74834. * @param width the new width
  74835. * @param height the new height
  74836. */
  74837. DynamicTexture.prototype.scaleTo = function (width, height) {
  74838. var textureSize = this.getSize();
  74839. textureSize.width = width;
  74840. textureSize.height = height;
  74841. this._recreate(textureSize);
  74842. };
  74843. /**
  74844. * Gets the context of the canvas used by the texture
  74845. * @returns the canvas context of the dynamic texture
  74846. */
  74847. DynamicTexture.prototype.getContext = function () {
  74848. return this._context;
  74849. };
  74850. /**
  74851. * Clears the texture
  74852. */
  74853. DynamicTexture.prototype.clear = function () {
  74854. var size = this.getSize();
  74855. this._context.fillRect(0, 0, size.width, size.height);
  74856. };
  74857. /**
  74858. * Updates the texture
  74859. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  74860. * @param premulAlpha defines if alpha is stored as premultiplied (default is false)
  74861. */
  74862. DynamicTexture.prototype.update = function (invertY, premulAlpha) {
  74863. if (premulAlpha === void 0) { premulAlpha = false; }
  74864. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, premulAlpha, this._format || undefined);
  74865. };
  74866. /**
  74867. * Draws text onto the texture
  74868. * @param text defines the text to be drawn
  74869. * @param x defines the placement of the text from the left
  74870. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  74871. * @param font defines the font to be used with font-style, font-size, font-name
  74872. * @param color defines the color used for the text
  74873. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  74874. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  74875. * @param update defines whether texture is immediately update (default is true)
  74876. */
  74877. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  74878. if (update === void 0) { update = true; }
  74879. var size = this.getSize();
  74880. if (clearColor) {
  74881. this._context.fillStyle = clearColor;
  74882. this._context.fillRect(0, 0, size.width, size.height);
  74883. }
  74884. this._context.font = font;
  74885. if (x === null || x === undefined) {
  74886. var textSize = this._context.measureText(text);
  74887. x = (size.width - textSize.width) / 2;
  74888. }
  74889. if (y === null || y === undefined) {
  74890. var fontSize = parseInt((font.replace(/\D/g, '')));
  74891. y = (size.height / 2) + (fontSize / 3.65);
  74892. }
  74893. this._context.fillStyle = color;
  74894. this._context.fillText(text, x, y);
  74895. if (update) {
  74896. this.update(invertY);
  74897. }
  74898. };
  74899. /**
  74900. * Clones the texture
  74901. * @returns the clone of the texture.
  74902. */
  74903. DynamicTexture.prototype.clone = function () {
  74904. var scene = this.getScene();
  74905. if (!scene) {
  74906. return this;
  74907. }
  74908. var textureSize = this.getSize();
  74909. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  74910. // Base texture
  74911. newTexture.hasAlpha = this.hasAlpha;
  74912. newTexture.level = this.level;
  74913. // Dynamic Texture
  74914. newTexture.wrapU = this.wrapU;
  74915. newTexture.wrapV = this.wrapV;
  74916. return newTexture;
  74917. };
  74918. /**
  74919. * Serializes the dynamic texture. The scene should be ready before the dynamic texture is serialized
  74920. * @returns a serialized dynamic texture object
  74921. */
  74922. DynamicTexture.prototype.serialize = function () {
  74923. var scene = this.getScene();
  74924. if (scene && !scene.isReady()) {
  74925. BABYLON.Tools.Warn("The scene must be ready before serializing the dynamic texture");
  74926. }
  74927. var serializationObject = _super.prototype.serialize.call(this);
  74928. serializationObject.base64String = this._canvas.toDataURL();
  74929. serializationObject.invertY = this._invertY;
  74930. serializationObject.samplingMode = this.samplingMode;
  74931. return serializationObject;
  74932. };
  74933. /** @hidden */
  74934. DynamicTexture.prototype._rebuild = function () {
  74935. this.update();
  74936. };
  74937. return DynamicTexture;
  74938. }(BABYLON.Texture));
  74939. BABYLON.DynamicTexture = DynamicTexture;
  74940. })(BABYLON || (BABYLON = {}));
  74941. //# sourceMappingURL=babylon.dynamicTexture.js.map
  74942. var BABYLON;
  74943. (function (BABYLON) {
  74944. /**
  74945. * If you want to display a video in your scene, this is the special texture for that.
  74946. * This special texture works similar to other textures, with the exception of a few parameters.
  74947. * @see https://doc.babylonjs.com/how_to/video_texture
  74948. */
  74949. var VideoTexture = /** @class */ (function (_super) {
  74950. __extends(VideoTexture, _super);
  74951. /**
  74952. * Creates a video texture.
  74953. * If you want to display a video in your scene, this is the special texture for that.
  74954. * This special texture works similar to other textures, with the exception of a few parameters.
  74955. * @see https://doc.babylonjs.com/how_to/video_texture
  74956. * @param name optional name, will detect from video source, if not defined
  74957. * @param src can be used to provide an url, array of urls or an already setup HTML video element.
  74958. * @param scene is obviously the current scene.
  74959. * @param generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  74960. * @param invertY is false by default but can be used to invert video on Y axis
  74961. * @param samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  74962. * @param settings allows finer control over video usage
  74963. */
  74964. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  74965. if (generateMipMaps === void 0) { generateMipMaps = false; }
  74966. if (invertY === void 0) { invertY = false; }
  74967. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  74968. if (settings === void 0) { settings = {
  74969. autoPlay: true,
  74970. loop: true,
  74971. autoUpdateTexture: true,
  74972. }; }
  74973. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  74974. _this._onUserActionRequestedObservable = null;
  74975. _this._stillImageCaptured = false;
  74976. _this._displayingPosterTexture = false;
  74977. _this._createInternalTexture = function () {
  74978. if (_this._texture != null) {
  74979. if (_this._displayingPosterTexture) {
  74980. _this._texture.dispose();
  74981. _this._displayingPosterTexture = false;
  74982. }
  74983. else {
  74984. return;
  74985. }
  74986. }
  74987. if (!_this._engine.needPOTTextures ||
  74988. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  74989. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  74990. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  74991. }
  74992. else {
  74993. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  74994. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  74995. _this._generateMipMaps = false;
  74996. }
  74997. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  74998. if (!_this.video.autoplay && !_this._settings.poster) {
  74999. var oldHandler_1 = _this.video.onplaying;
  75000. var error_1 = false;
  75001. _this.video.onplaying = function () {
  75002. _this.video.onplaying = oldHandler_1;
  75003. _this._texture.isReady = true;
  75004. _this._updateInternalTexture();
  75005. if (!error_1) {
  75006. _this.video.pause();
  75007. }
  75008. if (_this.onLoadObservable.hasObservers()) {
  75009. _this.onLoadObservable.notifyObservers(_this);
  75010. }
  75011. };
  75012. var playing = _this.video.play();
  75013. if (playing) {
  75014. playing.then(function () {
  75015. // Everything is good.
  75016. })
  75017. .catch(function () {
  75018. error_1 = true;
  75019. // On Chrome for instance, new policies might prevent playing without user interaction.
  75020. if (_this._onUserActionRequestedObservable && _this._onUserActionRequestedObservable.hasObservers()) {
  75021. _this._onUserActionRequestedObservable.notifyObservers(_this);
  75022. }
  75023. });
  75024. }
  75025. else {
  75026. _this.video.onplaying = oldHandler_1;
  75027. _this._texture.isReady = true;
  75028. _this._updateInternalTexture();
  75029. if (_this.onLoadObservable.hasObservers()) {
  75030. _this.onLoadObservable.notifyObservers(_this);
  75031. }
  75032. }
  75033. }
  75034. else {
  75035. _this._texture.isReady = true;
  75036. _this._updateInternalTexture();
  75037. if (_this.onLoadObservable.hasObservers()) {
  75038. _this.onLoadObservable.notifyObservers(_this);
  75039. }
  75040. }
  75041. };
  75042. _this.reset = function () {
  75043. if (_this._texture == null) {
  75044. return;
  75045. }
  75046. if (!_this._displayingPosterTexture) {
  75047. _this._texture.dispose();
  75048. _this._texture = null;
  75049. }
  75050. };
  75051. _this._updateInternalTexture = function (e) {
  75052. if (_this._texture == null || !_this._texture.isReady) {
  75053. return;
  75054. }
  75055. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  75056. return;
  75057. }
  75058. if (_this._displayingPosterTexture) {
  75059. return;
  75060. }
  75061. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  75062. };
  75063. _this._engine = _this.getScene().getEngine();
  75064. _this._generateMipMaps = generateMipMaps;
  75065. _this._samplingMode = samplingMode;
  75066. _this.autoUpdateTexture = settings.autoUpdateTexture;
  75067. _this.name = name || _this._getName(src);
  75068. _this.video = _this._getVideo(src);
  75069. _this._settings = settings;
  75070. if (settings.poster) {
  75071. _this.video.poster = settings.poster;
  75072. }
  75073. if (settings.autoPlay !== undefined) {
  75074. _this.video.autoplay = settings.autoPlay;
  75075. }
  75076. if (settings.loop !== undefined) {
  75077. _this.video.loop = settings.loop;
  75078. }
  75079. _this.video.setAttribute("playsinline", "");
  75080. _this.video.addEventListener("paused", _this._updateInternalTexture);
  75081. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  75082. _this.video.addEventListener("emptied", _this.reset);
  75083. _this._createInternalTextureOnEvent = (settings.poster && !settings.autoPlay) ? "play" : "canplay";
  75084. _this.video.addEventListener(_this._createInternalTextureOnEvent, _this._createInternalTexture);
  75085. var videoHasEnoughData = (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA);
  75086. if (settings.poster &&
  75087. (!settings.autoPlay || !videoHasEnoughData)) {
  75088. _this._texture = _this._engine.createTexture(settings.poster, false, true, scene);
  75089. _this._displayingPosterTexture = true;
  75090. }
  75091. else if (videoHasEnoughData) {
  75092. _this._createInternalTexture();
  75093. }
  75094. return _this;
  75095. }
  75096. Object.defineProperty(VideoTexture.prototype, "onUserActionRequestedObservable", {
  75097. /**
  75098. * Event triggerd when a dom action is required by the user to play the video.
  75099. * This happens due to recent changes in browser policies preventing video to auto start.
  75100. */
  75101. get: function () {
  75102. if (!this._onUserActionRequestedObservable) {
  75103. this._onUserActionRequestedObservable = new BABYLON.Observable();
  75104. }
  75105. return this._onUserActionRequestedObservable;
  75106. },
  75107. enumerable: true,
  75108. configurable: true
  75109. });
  75110. VideoTexture.prototype._getName = function (src) {
  75111. if (src instanceof HTMLVideoElement) {
  75112. return src.currentSrc;
  75113. }
  75114. if (typeof src === "object") {
  75115. return src.toString();
  75116. }
  75117. return src;
  75118. };
  75119. VideoTexture.prototype._getVideo = function (src) {
  75120. if (src instanceof HTMLVideoElement) {
  75121. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  75122. return src;
  75123. }
  75124. var video = document.createElement("video");
  75125. if (typeof src === "string") {
  75126. BABYLON.Tools.SetCorsBehavior(src, video);
  75127. video.src = src;
  75128. }
  75129. else {
  75130. BABYLON.Tools.SetCorsBehavior(src[0], video);
  75131. src.forEach(function (url) {
  75132. var source = document.createElement("source");
  75133. source.src = url;
  75134. video.appendChild(source);
  75135. });
  75136. }
  75137. return video;
  75138. };
  75139. /**
  75140. * @hidden Internal method to initiate `update`.
  75141. */
  75142. VideoTexture.prototype._rebuild = function () {
  75143. this.update();
  75144. };
  75145. /**
  75146. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  75147. */
  75148. VideoTexture.prototype.update = function () {
  75149. if (!this.autoUpdateTexture) {
  75150. // Expecting user to call `updateTexture` manually
  75151. return;
  75152. }
  75153. this.updateTexture(true);
  75154. };
  75155. /**
  75156. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  75157. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  75158. */
  75159. VideoTexture.prototype.updateTexture = function (isVisible) {
  75160. if (!isVisible) {
  75161. return;
  75162. }
  75163. if (this.video.paused && this._stillImageCaptured) {
  75164. return;
  75165. }
  75166. this._stillImageCaptured = true;
  75167. this._updateInternalTexture();
  75168. };
  75169. /**
  75170. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  75171. * @param url New url.
  75172. */
  75173. VideoTexture.prototype.updateURL = function (url) {
  75174. this.video.src = url;
  75175. };
  75176. /**
  75177. * Dispose the texture and release its associated resources.
  75178. */
  75179. VideoTexture.prototype.dispose = function () {
  75180. _super.prototype.dispose.call(this);
  75181. if (this._onUserActionRequestedObservable) {
  75182. this._onUserActionRequestedObservable.clear();
  75183. this._onUserActionRequestedObservable = null;
  75184. }
  75185. this.video.removeEventListener(this._createInternalTextureOnEvent, this._createInternalTexture);
  75186. this.video.removeEventListener("paused", this._updateInternalTexture);
  75187. this.video.removeEventListener("seeked", this._updateInternalTexture);
  75188. this.video.removeEventListener("emptied", this.reset);
  75189. this.video.pause();
  75190. };
  75191. /**
  75192. * Creates a video texture straight from your WebCam video feed.
  75193. * @param scene Define the scene the texture should be created in
  75194. * @param onReady Define a callback to triggered once the texture will be ready
  75195. * @param constraints Define the constraints to use to create the web cam feed from WebRTC
  75196. */
  75197. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  75198. var video = document.createElement("video");
  75199. video.setAttribute('autoplay', '');
  75200. video.setAttribute('muted', '');
  75201. video.setAttribute('playsinline', '');
  75202. var constraintsDeviceId;
  75203. if (constraints && constraints.deviceId) {
  75204. constraintsDeviceId = {
  75205. exact: constraints.deviceId,
  75206. };
  75207. }
  75208. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  75209. if (navigator.mediaDevices) {
  75210. navigator.mediaDevices.getUserMedia({ video: constraints })
  75211. .then(function (stream) {
  75212. if (video.mozSrcObject !== undefined) {
  75213. // hack for Firefox < 19
  75214. video.mozSrcObject = stream;
  75215. }
  75216. else {
  75217. video.srcObject = stream;
  75218. }
  75219. var onPlaying = function () {
  75220. if (onReady) {
  75221. onReady(new VideoTexture("video", video, scene, true, true));
  75222. }
  75223. video.removeEventListener("playing", onPlaying);
  75224. };
  75225. video.addEventListener("playing", onPlaying);
  75226. video.play();
  75227. })
  75228. .catch(function (err) {
  75229. BABYLON.Tools.Error(err.name);
  75230. });
  75231. }
  75232. else {
  75233. navigator.getUserMedia =
  75234. navigator.getUserMedia ||
  75235. navigator.webkitGetUserMedia ||
  75236. navigator.mozGetUserMedia ||
  75237. navigator.msGetUserMedia;
  75238. if (navigator.getUserMedia) {
  75239. navigator.getUserMedia({
  75240. video: {
  75241. deviceId: constraintsDeviceId,
  75242. width: {
  75243. min: (constraints && constraints.minWidth) || 256,
  75244. max: (constraints && constraints.maxWidth) || 640,
  75245. },
  75246. height: {
  75247. min: (constraints && constraints.minHeight) || 256,
  75248. max: (constraints && constraints.maxHeight) || 480,
  75249. },
  75250. },
  75251. }, function (stream) {
  75252. if (video.mozSrcObject !== undefined) {
  75253. // hack for Firefox < 19
  75254. video.mozSrcObject = stream;
  75255. }
  75256. else {
  75257. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  75258. }
  75259. video.play();
  75260. if (onReady) {
  75261. onReady(new VideoTexture("video", video, scene, true, true));
  75262. }
  75263. }, function (e) {
  75264. BABYLON.Tools.Error(e.name);
  75265. });
  75266. }
  75267. }
  75268. };
  75269. return VideoTexture;
  75270. }(BABYLON.Texture));
  75271. BABYLON.VideoTexture = VideoTexture;
  75272. })(BABYLON || (BABYLON = {}));
  75273. //# sourceMappingURL=babylon.videoTexture.js.map
  75274. var BABYLON;
  75275. (function (BABYLON) {
  75276. /**
  75277. * Raw texture can help creating a texture directly from an array of data.
  75278. * This can be super useful if you either get the data from an uncompressed source or
  75279. * if you wish to create your texture pixel by pixel.
  75280. */
  75281. var RawTexture = /** @class */ (function (_super) {
  75282. __extends(RawTexture, _super);
  75283. /**
  75284. * Instantiates a new RawTexture.
  75285. * Raw texture can help creating a texture directly from an array of data.
  75286. * This can be super useful if you either get the data from an uncompressed source or
  75287. * if you wish to create your texture pixel by pixel.
  75288. * @param data define the array of data to use to create the texture
  75289. * @param width define the width of the texture
  75290. * @param height define the height of the texture
  75291. * @param format define the format of the data (RGB, RGBA... Engine.TEXTUREFORMAT_xxx)
  75292. * @param scene define the scene the texture belongs to
  75293. * @param generateMipMaps define whether mip maps should be generated or not
  75294. * @param invertY define if the data should be flipped on Y when uploaded to the GPU
  75295. * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
  75296. * @param type define the format of the data (int, float... Engine.TEXTURETYPE_xxx)
  75297. */
  75298. function RawTexture(data, width, height,
  75299. /**
  75300. * Define the format of the data (RGB, RGBA... Engine.TEXTUREFORMAT_xxx)
  75301. */
  75302. format, scene, generateMipMaps, invertY, samplingMode, type) {
  75303. if (generateMipMaps === void 0) { generateMipMaps = true; }
  75304. if (invertY === void 0) { invertY = false; }
  75305. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  75306. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75307. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  75308. _this.format = format;
  75309. _this._engine = scene.getEngine();
  75310. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  75311. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  75312. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  75313. return _this;
  75314. }
  75315. /**
  75316. * Updates the texture underlying data.
  75317. * @param data Define the new data of the texture
  75318. */
  75319. RawTexture.prototype.update = function (data) {
  75320. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  75321. };
  75322. /**
  75323. * Creates a luminance texture from some data.
  75324. * @param data Define the texture data
  75325. * @param width Define the width of the texture
  75326. * @param height Define the height of the texture
  75327. * @param scene Define the scene the texture belongs to
  75328. * @param generateMipMaps Define whether or not to create mip maps for the texture
  75329. * @param invertY define if the data should be flipped on Y when uploaded to the GPU
  75330. * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
  75331. * @returns the luminance texture
  75332. */
  75333. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  75334. if (generateMipMaps === void 0) { generateMipMaps = true; }
  75335. if (invertY === void 0) { invertY = false; }
  75336. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  75337. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  75338. };
  75339. /**
  75340. * Creates a luminance alpha texture from some data.
  75341. * @param data Define the texture data
  75342. * @param width Define the width of the texture
  75343. * @param height Define the height of the texture
  75344. * @param scene Define the scene the texture belongs to
  75345. * @param generateMipMaps Define whether or not to create mip maps for the texture
  75346. * @param invertY define if the data should be flipped on Y when uploaded to the GPU
  75347. * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
  75348. * @returns the luminance alpha texture
  75349. */
  75350. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  75351. if (generateMipMaps === void 0) { generateMipMaps = true; }
  75352. if (invertY === void 0) { invertY = false; }
  75353. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  75354. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  75355. };
  75356. /**
  75357. * Creates an alpha texture from some data.
  75358. * @param data Define the texture data
  75359. * @param width Define the width of the texture
  75360. * @param height Define the height of the texture
  75361. * @param scene Define the scene the texture belongs to
  75362. * @param generateMipMaps Define whether or not to create mip maps for the texture
  75363. * @param invertY define if the data should be flipped on Y when uploaded to the GPU
  75364. * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
  75365. * @returns the alpha texture
  75366. */
  75367. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  75368. if (generateMipMaps === void 0) { generateMipMaps = true; }
  75369. if (invertY === void 0) { invertY = false; }
  75370. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  75371. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  75372. };
  75373. /**
  75374. * Creates a RGB texture from some data.
  75375. * @param data Define the texture data
  75376. * @param width Define the width of the texture
  75377. * @param height Define the height of the texture
  75378. * @param scene Define the scene the texture belongs to
  75379. * @param generateMipMaps Define whether or not to create mip maps for the texture
  75380. * @param invertY define if the data should be flipped on Y when uploaded to the GPU
  75381. * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
  75382. * @param type define the format of the data (int, float... Engine.TEXTURETYPE_xxx)
  75383. * @returns the RGB alpha texture
  75384. */
  75385. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  75386. if (generateMipMaps === void 0) { generateMipMaps = true; }
  75387. if (invertY === void 0) { invertY = false; }
  75388. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  75389. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75390. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  75391. };
  75392. /**
  75393. * Creates a RGBA texture from some data.
  75394. * @param data Define the texture data
  75395. * @param width Define the width of the texture
  75396. * @param height Define the height of the texture
  75397. * @param scene Define the scene the texture belongs to
  75398. * @param generateMipMaps Define whether or not to create mip maps for the texture
  75399. * @param invertY define if the data should be flipped on Y when uploaded to the GPU
  75400. * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
  75401. * @param type define the format of the data (int, float... Engine.TEXTURETYPE_xxx)
  75402. * @returns the RGBA texture
  75403. */
  75404. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  75405. if (generateMipMaps === void 0) { generateMipMaps = true; }
  75406. if (invertY === void 0) { invertY = false; }
  75407. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  75408. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75409. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  75410. };
  75411. /**
  75412. * Creates a R texture from some data.
  75413. * @param data Define the texture data
  75414. * @param width Define the width of the texture
  75415. * @param height Define the height of the texture
  75416. * @param scene Define the scene the texture belongs to
  75417. * @param generateMipMaps Define whether or not to create mip maps for the texture
  75418. * @param invertY define if the data should be flipped on Y when uploaded to the GPU
  75419. * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
  75420. * @param type define the format of the data (int, float... Engine.TEXTURETYPE_xxx)
  75421. * @returns the R texture
  75422. */
  75423. RawTexture.CreateRTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  75424. if (generateMipMaps === void 0) { generateMipMaps = true; }
  75425. if (invertY === void 0) { invertY = false; }
  75426. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  75427. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  75428. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_R, scene, generateMipMaps, invertY, samplingMode, type);
  75429. };
  75430. return RawTexture;
  75431. }(BABYLON.Texture));
  75432. BABYLON.RawTexture = RawTexture;
  75433. })(BABYLON || (BABYLON = {}));
  75434. //# sourceMappingURL=babylon.rawTexture.js.map
  75435. var BABYLON;
  75436. (function (BABYLON) {
  75437. /**
  75438. * Class used to store 3D textures containing user data
  75439. */
  75440. var RawTexture3D = /** @class */ (function (_super) {
  75441. __extends(RawTexture3D, _super);
  75442. /**
  75443. * Create a new RawTexture3D
  75444. * @param data defines the data of the texture
  75445. * @param width defines the width of the texture
  75446. * @param height defines the height of the texture
  75447. * @param depth defines the depth of the texture
  75448. * @param format defines the texture format to use
  75449. * @param scene defines the hosting scene
  75450. * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
  75451. * @param invertY defines if texture must be stored with Y axis inverted
  75452. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  75453. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  75454. */
  75455. function RawTexture3D(data, width, height, depth,
  75456. /** Gets or sets the texture format to use */
  75457. format, scene, generateMipMaps, invertY, samplingMode, textureType) {
  75458. if (generateMipMaps === void 0) { generateMipMaps = true; }
  75459. if (invertY === void 0) { invertY = false; }
  75460. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  75461. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75462. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  75463. _this.format = format;
  75464. _this._engine = scene.getEngine();
  75465. _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode, undefined, textureType);
  75466. _this.is3D = true;
  75467. return _this;
  75468. }
  75469. /**
  75470. * Update the texture with new data
  75471. * @param data defines the data to store in the texture
  75472. */
  75473. RawTexture3D.prototype.update = function (data) {
  75474. if (!this._texture) {
  75475. return;
  75476. }
  75477. this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  75478. };
  75479. return RawTexture3D;
  75480. }(BABYLON.Texture));
  75481. BABYLON.RawTexture3D = RawTexture3D;
  75482. })(BABYLON || (BABYLON = {}));
  75483. //# sourceMappingURL=babylon.rawTexture3D.js.map
  75484. var BABYLON;
  75485. (function (BABYLON) {
  75486. /**
  75487. * PostProcessManager is used to manage one or more post processes or post process pipelines
  75488. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  75489. */
  75490. var PostProcessManager = /** @class */ (function () {
  75491. /**
  75492. * Creates a new instance PostProcess
  75493. * @param scene The scene that the post process is associated with.
  75494. */
  75495. function PostProcessManager(scene) {
  75496. this._vertexBuffers = {};
  75497. this._scene = scene;
  75498. }
  75499. PostProcessManager.prototype._prepareBuffers = function () {
  75500. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  75501. return;
  75502. }
  75503. // VBO
  75504. var vertices = [];
  75505. vertices.push(1, 1);
  75506. vertices.push(-1, 1);
  75507. vertices.push(-1, -1);
  75508. vertices.push(1, -1);
  75509. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  75510. this._buildIndexBuffer();
  75511. };
  75512. PostProcessManager.prototype._buildIndexBuffer = function () {
  75513. // Indices
  75514. var indices = [];
  75515. indices.push(0);
  75516. indices.push(1);
  75517. indices.push(2);
  75518. indices.push(0);
  75519. indices.push(2);
  75520. indices.push(3);
  75521. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  75522. };
  75523. /**
  75524. * Rebuilds the vertex buffers of the manager.
  75525. * @hidden
  75526. */
  75527. PostProcessManager.prototype._rebuild = function () {
  75528. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  75529. if (!vb) {
  75530. return;
  75531. }
  75532. vb._rebuild();
  75533. this._buildIndexBuffer();
  75534. };
  75535. // Methods
  75536. /**
  75537. * Prepares a frame to be run through a post process.
  75538. * @param sourceTexture The input texture to the post procesess. (default: null)
  75539. * @param postProcesses An array of post processes to be run. (default: null)
  75540. * @returns True if the post processes were able to be run.
  75541. * @hidden
  75542. */
  75543. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  75544. if (sourceTexture === void 0) { sourceTexture = null; }
  75545. if (postProcesses === void 0) { postProcesses = null; }
  75546. var camera = this._scene.activeCamera;
  75547. if (!camera) {
  75548. return false;
  75549. }
  75550. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  75551. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  75552. return false;
  75553. }
  75554. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  75555. return true;
  75556. };
  75557. /**
  75558. * Manually render a set of post processes to a texture.
  75559. * @param postProcesses An array of post processes to be run.
  75560. * @param targetTexture The target texture to render to.
  75561. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  75562. * @param faceIndex defines the face to render to if a cubemap is defined as the target
  75563. * @param lodLevel defines which lod of the texture to render to
  75564. */
  75565. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport, faceIndex, lodLevel) {
  75566. if (targetTexture === void 0) { targetTexture = null; }
  75567. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  75568. if (faceIndex === void 0) { faceIndex = 0; }
  75569. if (lodLevel === void 0) { lodLevel = 0; }
  75570. var engine = this._scene.getEngine();
  75571. for (var index = 0; index < postProcesses.length; index++) {
  75572. if (index < postProcesses.length - 1) {
  75573. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  75574. }
  75575. else {
  75576. if (targetTexture) {
  75577. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport, undefined, lodLevel);
  75578. }
  75579. else {
  75580. engine.restoreDefaultFramebuffer();
  75581. }
  75582. }
  75583. var pp = postProcesses[index];
  75584. var effect = pp.apply();
  75585. if (effect) {
  75586. pp.onBeforeRenderObservable.notifyObservers(effect);
  75587. // VBOs
  75588. this._prepareBuffers();
  75589. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  75590. // Draw order
  75591. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  75592. pp.onAfterRenderObservable.notifyObservers(effect);
  75593. }
  75594. }
  75595. // Restore depth buffer
  75596. engine.setDepthBuffer(true);
  75597. engine.setDepthWrite(true);
  75598. };
  75599. /**
  75600. * Finalize the result of the output of the postprocesses.
  75601. * @param doNotPresent If true the result will not be displayed to the screen.
  75602. * @param targetTexture The target texture to render to.
  75603. * @param faceIndex The index of the face to bind the target texture to.
  75604. * @param postProcesses The array of post processes to render.
  75605. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  75606. * @hidden
  75607. */
  75608. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  75609. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  75610. var camera = this._scene.activeCamera;
  75611. if (!camera) {
  75612. return;
  75613. }
  75614. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  75615. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  75616. return;
  75617. }
  75618. var engine = this._scene.getEngine();
  75619. for (var index = 0, len = postProcesses.length; index < len; index++) {
  75620. var pp = postProcesses[index];
  75621. if (index < len - 1) {
  75622. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  75623. }
  75624. else {
  75625. if (targetTexture) {
  75626. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  75627. pp._outputTexture = targetTexture;
  75628. }
  75629. else {
  75630. engine.restoreDefaultFramebuffer();
  75631. pp._outputTexture = null;
  75632. }
  75633. }
  75634. if (doNotPresent) {
  75635. break;
  75636. }
  75637. var effect = pp.apply();
  75638. if (effect) {
  75639. pp.onBeforeRenderObservable.notifyObservers(effect);
  75640. // VBOs
  75641. this._prepareBuffers();
  75642. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  75643. // Draw order
  75644. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  75645. pp.onAfterRenderObservable.notifyObservers(effect);
  75646. }
  75647. }
  75648. // Restore states
  75649. engine.setDepthBuffer(true);
  75650. engine.setDepthWrite(true);
  75651. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  75652. };
  75653. /**
  75654. * Disposes of the post process manager.
  75655. */
  75656. PostProcessManager.prototype.dispose = function () {
  75657. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  75658. if (buffer) {
  75659. buffer.dispose();
  75660. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  75661. }
  75662. if (this._indexBuffer) {
  75663. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  75664. this._indexBuffer = null;
  75665. }
  75666. };
  75667. return PostProcessManager;
  75668. }());
  75669. BABYLON.PostProcessManager = PostProcessManager;
  75670. })(BABYLON || (BABYLON = {}));
  75671. //# sourceMappingURL=babylon.postProcessManager.js.map
  75672. var BABYLON;
  75673. (function (BABYLON) {
  75674. /**
  75675. * PostProcess can be used to apply a shader to a texture after it has been rendered
  75676. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  75677. */
  75678. var PostProcess = /** @class */ (function () {
  75679. /**
  75680. * Creates a new instance PostProcess
  75681. * @param name The name of the PostProcess.
  75682. * @param fragmentUrl The url of the fragment shader to be used.
  75683. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  75684. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  75685. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  75686. * @param camera The camera to apply the render pass to.
  75687. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75688. * @param engine The engine which the post process will be applied. (default: current engine)
  75689. * @param reusable If the post process can be reused on the same frame. (default: false)
  75690. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  75691. * @param textureType Type of textures used when performing the post process. (default: 0)
  75692. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  75693. * @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
  75694. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  75695. */
  75696. function PostProcess(
  75697. /** Name of the PostProcess. */
  75698. name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  75699. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  75700. if (defines === void 0) { defines = null; }
  75701. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75702. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  75703. if (blockCompilation === void 0) { blockCompilation = false; }
  75704. this.name = name;
  75705. /**
  75706. * Width of the texture to apply the post process on
  75707. */
  75708. this.width = -1;
  75709. /**
  75710. * Height of the texture to apply the post process on
  75711. */
  75712. this.height = -1;
  75713. /**
  75714. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  75715. * @hidden
  75716. */
  75717. this._outputTexture = null;
  75718. /**
  75719. * If the buffer needs to be cleared before applying the post process. (default: true)
  75720. * Should be set to false if shader will overwrite all previous pixels.
  75721. */
  75722. this.autoClear = true;
  75723. /**
  75724. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  75725. */
  75726. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  75727. /**
  75728. * Animations to be used for the post processing
  75729. */
  75730. this.animations = new Array();
  75731. /**
  75732. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  75733. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  75734. */
  75735. this.enablePixelPerfectMode = false;
  75736. /**
  75737. * Force the postprocess to be applied without taking in account viewport
  75738. */
  75739. this.forceFullscreenViewport = true;
  75740. /**
  75741. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  75742. *
  75743. * | Value | Type | Description |
  75744. * | ----- | ----------------------------------- | ----------- |
  75745. * | 1 | SCALEMODE_FLOOR | [engine.scalemode_floor](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_floor) |
  75746. * | 2 | SCALEMODE_NEAREST | [engine.scalemode_nearest](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_nearest) |
  75747. * | 3 | SCALEMODE_CEILING | [engine.scalemode_ceiling](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_ceiling) |
  75748. *
  75749. */
  75750. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  75751. /**
  75752. * Force textures to be a power of two (default: false)
  75753. */
  75754. this.alwaysForcePOT = false;
  75755. this._samples = 1;
  75756. /**
  75757. * Modify the scale of the post process to be the same as the viewport (default: false)
  75758. */
  75759. this.adaptScaleToCurrentViewport = false;
  75760. this._reusable = false;
  75761. /**
  75762. * Smart array of input and output textures for the post process.
  75763. * @hidden
  75764. */
  75765. this._textures = new BABYLON.SmartArray(2);
  75766. /**
  75767. * The index in _textures that corresponds to the output texture.
  75768. * @hidden
  75769. */
  75770. this._currentRenderTextureInd = 0;
  75771. this._scaleRatio = new BABYLON.Vector2(1, 1);
  75772. this._texelSize = BABYLON.Vector2.Zero();
  75773. // Events
  75774. /**
  75775. * An event triggered when the postprocess is activated.
  75776. */
  75777. this.onActivateObservable = new BABYLON.Observable();
  75778. /**
  75779. * An event triggered when the postprocess changes its size.
  75780. */
  75781. this.onSizeChangedObservable = new BABYLON.Observable();
  75782. /**
  75783. * An event triggered when the postprocess applies its effect.
  75784. */
  75785. this.onApplyObservable = new BABYLON.Observable();
  75786. /**
  75787. * An event triggered before rendering the postprocess
  75788. */
  75789. this.onBeforeRenderObservable = new BABYLON.Observable();
  75790. /**
  75791. * An event triggered after rendering the postprocess
  75792. */
  75793. this.onAfterRenderObservable = new BABYLON.Observable();
  75794. if (camera != null) {
  75795. this._camera = camera;
  75796. this._scene = camera.getScene();
  75797. camera.attachPostProcess(this);
  75798. this._engine = this._scene.getEngine();
  75799. this._scene.postProcesses.push(this);
  75800. }
  75801. else if (engine) {
  75802. this._engine = engine;
  75803. this._engine.postProcesses.push(this);
  75804. }
  75805. this._options = options;
  75806. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  75807. this._reusable = reusable || false;
  75808. this._textureType = textureType;
  75809. this._samplers = samplers || [];
  75810. this._samplers.push("textureSampler");
  75811. this._fragmentUrl = fragmentUrl;
  75812. this._vertexUrl = vertexUrl;
  75813. this._parameters = parameters || [];
  75814. this._parameters.push("scale");
  75815. this._indexParameters = indexParameters;
  75816. if (!blockCompilation) {
  75817. this.updateEffect(defines);
  75818. }
  75819. }
  75820. Object.defineProperty(PostProcess.prototype, "samples", {
  75821. /**
  75822. * Number of sample textures (default: 1)
  75823. */
  75824. get: function () {
  75825. return this._samples;
  75826. },
  75827. set: function (n) {
  75828. var _this = this;
  75829. this._samples = n;
  75830. this._textures.forEach(function (texture) {
  75831. if (texture.samples !== _this._samples) {
  75832. _this._engine.updateRenderTargetTextureSampleCount(texture, _this._samples);
  75833. }
  75834. });
  75835. },
  75836. enumerable: true,
  75837. configurable: true
  75838. });
  75839. Object.defineProperty(PostProcess.prototype, "onActivate", {
  75840. /**
  75841. * A function that is added to the onActivateObservable
  75842. */
  75843. set: function (callback) {
  75844. if (this._onActivateObserver) {
  75845. this.onActivateObservable.remove(this._onActivateObserver);
  75846. }
  75847. if (callback) {
  75848. this._onActivateObserver = this.onActivateObservable.add(callback);
  75849. }
  75850. },
  75851. enumerable: true,
  75852. configurable: true
  75853. });
  75854. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  75855. /**
  75856. * A function that is added to the onSizeChangedObservable
  75857. */
  75858. set: function (callback) {
  75859. if (this._onSizeChangedObserver) {
  75860. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  75861. }
  75862. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  75863. },
  75864. enumerable: true,
  75865. configurable: true
  75866. });
  75867. Object.defineProperty(PostProcess.prototype, "onApply", {
  75868. /**
  75869. * A function that is added to the onApplyObservable
  75870. */
  75871. set: function (callback) {
  75872. if (this._onApplyObserver) {
  75873. this.onApplyObservable.remove(this._onApplyObserver);
  75874. }
  75875. this._onApplyObserver = this.onApplyObservable.add(callback);
  75876. },
  75877. enumerable: true,
  75878. configurable: true
  75879. });
  75880. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  75881. /**
  75882. * A function that is added to the onBeforeRenderObservable
  75883. */
  75884. set: function (callback) {
  75885. if (this._onBeforeRenderObserver) {
  75886. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  75887. }
  75888. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  75889. },
  75890. enumerable: true,
  75891. configurable: true
  75892. });
  75893. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  75894. /**
  75895. * A function that is added to the onAfterRenderObservable
  75896. */
  75897. set: function (callback) {
  75898. if (this._onAfterRenderObserver) {
  75899. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  75900. }
  75901. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  75902. },
  75903. enumerable: true,
  75904. configurable: true
  75905. });
  75906. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  75907. /**
  75908. * 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
  75909. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  75910. */
  75911. get: function () {
  75912. return this._textures.data[this._currentRenderTextureInd];
  75913. },
  75914. set: function (value) {
  75915. this._forcedOutputTexture = value;
  75916. },
  75917. enumerable: true,
  75918. configurable: true
  75919. });
  75920. /**
  75921. * Gets the camera which post process is applied to.
  75922. * @returns The camera the post process is applied to.
  75923. */
  75924. PostProcess.prototype.getCamera = function () {
  75925. return this._camera;
  75926. };
  75927. Object.defineProperty(PostProcess.prototype, "texelSize", {
  75928. /**
  75929. * Gets the texel size of the postprocess.
  75930. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  75931. */
  75932. get: function () {
  75933. if (this._shareOutputWithPostProcess) {
  75934. return this._shareOutputWithPostProcess.texelSize;
  75935. }
  75936. if (this._forcedOutputTexture) {
  75937. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  75938. }
  75939. return this._texelSize;
  75940. },
  75941. enumerable: true,
  75942. configurable: true
  75943. });
  75944. /**
  75945. * Gets the engine which this post process belongs to.
  75946. * @returns The engine the post process was enabled with.
  75947. */
  75948. PostProcess.prototype.getEngine = function () {
  75949. return this._engine;
  75950. };
  75951. /**
  75952. * The effect that is created when initializing the post process.
  75953. * @returns The created effect corrisponding the the postprocess.
  75954. */
  75955. PostProcess.prototype.getEffect = function () {
  75956. return this._effect;
  75957. };
  75958. /**
  75959. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  75960. * @param postProcess The post process to share the output with.
  75961. * @returns This post process.
  75962. */
  75963. PostProcess.prototype.shareOutputWith = function (postProcess) {
  75964. this._disposeTextures();
  75965. this._shareOutputWithPostProcess = postProcess;
  75966. return this;
  75967. };
  75968. /**
  75969. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  75970. * This should be called if the post process that shares output with this post process is disabled/disposed.
  75971. */
  75972. PostProcess.prototype.useOwnOutput = function () {
  75973. if (this._textures.length == 0) {
  75974. this._textures = new BABYLON.SmartArray(2);
  75975. }
  75976. this._shareOutputWithPostProcess = null;
  75977. };
  75978. /**
  75979. * Updates the effect with the current post process compile time values and recompiles the shader.
  75980. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  75981. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  75982. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  75983. * @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
  75984. * @param onCompiled Called when the shader has been compiled.
  75985. * @param onError Called if there is an error when compiling a shader.
  75986. */
  75987. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  75988. if (defines === void 0) { defines = null; }
  75989. if (uniforms === void 0) { uniforms = null; }
  75990. if (samplers === void 0) { samplers = null; }
  75991. 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);
  75992. };
  75993. /**
  75994. * The post process is reusable if it can be used multiple times within one frame.
  75995. * @returns If the post process is reusable
  75996. */
  75997. PostProcess.prototype.isReusable = function () {
  75998. return this._reusable;
  75999. };
  76000. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  76001. PostProcess.prototype.markTextureDirty = function () {
  76002. this.width = -1;
  76003. };
  76004. /**
  76005. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  76006. * 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.
  76007. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  76008. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  76009. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  76010. * @returns The target texture that was bound to be written to.
  76011. */
  76012. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  76013. var _this = this;
  76014. if (sourceTexture === void 0) { sourceTexture = null; }
  76015. camera = camera || this._camera;
  76016. var scene = camera.getScene();
  76017. var engine = scene.getEngine();
  76018. var maxSize = engine.getCaps().maxTextureSize;
  76019. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  76020. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  76021. // 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
  76022. var webVRCamera = camera.parent;
  76023. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  76024. requiredWidth /= 2;
  76025. }
  76026. var desiredWidth = (this._options.width || requiredWidth);
  76027. var desiredHeight = this._options.height || requiredHeight;
  76028. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  76029. if (this.adaptScaleToCurrentViewport) {
  76030. var currentViewport = engine.currentViewport;
  76031. if (currentViewport) {
  76032. desiredWidth *= currentViewport.width;
  76033. desiredHeight *= currentViewport.height;
  76034. }
  76035. }
  76036. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  76037. if (!this._options.width) {
  76038. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  76039. }
  76040. if (!this._options.height) {
  76041. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  76042. }
  76043. }
  76044. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  76045. if (this._textures.length > 0) {
  76046. for (var i = 0; i < this._textures.length; i++) {
  76047. this._engine._releaseTexture(this._textures.data[i]);
  76048. }
  76049. this._textures.reset();
  76050. }
  76051. this.width = desiredWidth;
  76052. this.height = desiredHeight;
  76053. var textureSize = { width: this.width, height: this.height };
  76054. var textureOptions = {
  76055. generateMipMaps: false,
  76056. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  76057. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  76058. samplingMode: this.renderTargetSamplingMode,
  76059. type: this._textureType
  76060. };
  76061. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  76062. if (this._reusable) {
  76063. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  76064. }
  76065. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  76066. this.onSizeChangedObservable.notifyObservers(this);
  76067. }
  76068. this._textures.forEach(function (texture) {
  76069. if (texture.samples !== _this.samples) {
  76070. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  76071. }
  76072. });
  76073. }
  76074. var target;
  76075. if (this._shareOutputWithPostProcess) {
  76076. target = this._shareOutputWithPostProcess.inputTexture;
  76077. }
  76078. else if (this._forcedOutputTexture) {
  76079. target = this._forcedOutputTexture;
  76080. this.width = this._forcedOutputTexture.width;
  76081. this.height = this._forcedOutputTexture.height;
  76082. }
  76083. else {
  76084. target = this.inputTexture;
  76085. }
  76086. // Bind the input of this post process to be used as the output of the previous post process.
  76087. if (this.enablePixelPerfectMode) {
  76088. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  76089. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, this.forceFullscreenViewport);
  76090. }
  76091. else {
  76092. this._scaleRatio.copyFromFloats(1, 1);
  76093. this._engine.bindFramebuffer(target, 0, undefined, undefined, this.forceFullscreenViewport);
  76094. }
  76095. this.onActivateObservable.notifyObservers(camera);
  76096. // Clear
  76097. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  76098. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, scene._allowPostProcessClearColor, true, true);
  76099. }
  76100. if (this._reusable) {
  76101. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  76102. }
  76103. return target;
  76104. };
  76105. Object.defineProperty(PostProcess.prototype, "isSupported", {
  76106. /**
  76107. * If the post process is supported.
  76108. */
  76109. get: function () {
  76110. return this._effect.isSupported;
  76111. },
  76112. enumerable: true,
  76113. configurable: true
  76114. });
  76115. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  76116. /**
  76117. * The aspect ratio of the output texture.
  76118. */
  76119. get: function () {
  76120. if (this._shareOutputWithPostProcess) {
  76121. return this._shareOutputWithPostProcess.aspectRatio;
  76122. }
  76123. if (this._forcedOutputTexture) {
  76124. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  76125. }
  76126. return this.width / this.height;
  76127. },
  76128. enumerable: true,
  76129. configurable: true
  76130. });
  76131. /**
  76132. * Get a value indicating if the post-process is ready to be used
  76133. * @returns true if the post-process is ready (shader is compiled)
  76134. */
  76135. PostProcess.prototype.isReady = function () {
  76136. return this._effect && this._effect.isReady();
  76137. };
  76138. /**
  76139. * Binds all textures and uniforms to the shader, this will be run on every pass.
  76140. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  76141. */
  76142. PostProcess.prototype.apply = function () {
  76143. // Check
  76144. if (!this._effect || !this._effect.isReady()) {
  76145. return null;
  76146. }
  76147. // States
  76148. this._engine.enableEffect(this._effect);
  76149. this._engine.setState(false);
  76150. this._engine.setDepthBuffer(false);
  76151. this._engine.setDepthWrite(false);
  76152. // Alpha
  76153. this._engine.setAlphaMode(this.alphaMode);
  76154. if (this.alphaConstants) {
  76155. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  76156. }
  76157. // Bind the output texture of the preivous post process as the input to this post process.
  76158. var source;
  76159. if (this._shareOutputWithPostProcess) {
  76160. source = this._shareOutputWithPostProcess.inputTexture;
  76161. }
  76162. else if (this._forcedOutputTexture) {
  76163. source = this._forcedOutputTexture;
  76164. }
  76165. else {
  76166. source = this.inputTexture;
  76167. }
  76168. this._effect._bindTexture("textureSampler", source);
  76169. // Parameters
  76170. this._effect.setVector2("scale", this._scaleRatio);
  76171. this.onApplyObservable.notifyObservers(this._effect);
  76172. return this._effect;
  76173. };
  76174. PostProcess.prototype._disposeTextures = function () {
  76175. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  76176. return;
  76177. }
  76178. if (this._textures.length > 0) {
  76179. for (var i = 0; i < this._textures.length; i++) {
  76180. this._engine._releaseTexture(this._textures.data[i]);
  76181. }
  76182. }
  76183. this._textures.dispose();
  76184. };
  76185. /**
  76186. * Disposes the post process.
  76187. * @param camera The camera to dispose the post process on.
  76188. */
  76189. PostProcess.prototype.dispose = function (camera) {
  76190. camera = camera || this._camera;
  76191. this._disposeTextures();
  76192. if (this._scene) {
  76193. var index_1 = this._scene.postProcesses.indexOf(this);
  76194. if (index_1 !== -1) {
  76195. this._scene.postProcesses.splice(index_1, 1);
  76196. }
  76197. }
  76198. else {
  76199. var index_2 = this._engine.postProcesses.indexOf(this);
  76200. if (index_2 !== -1) {
  76201. this._engine.postProcesses.splice(index_2, 1);
  76202. }
  76203. }
  76204. if (!camera) {
  76205. return;
  76206. }
  76207. camera.detachPostProcess(this);
  76208. var index = camera._postProcesses.indexOf(this);
  76209. if (index === 0 && camera._postProcesses.length > 0) {
  76210. var firstPostProcess = this._camera._getFirstPostProcess();
  76211. if (firstPostProcess) {
  76212. firstPostProcess.markTextureDirty();
  76213. }
  76214. }
  76215. this.onActivateObservable.clear();
  76216. this.onAfterRenderObservable.clear();
  76217. this.onApplyObservable.clear();
  76218. this.onBeforeRenderObservable.clear();
  76219. this.onSizeChangedObservable.clear();
  76220. };
  76221. return PostProcess;
  76222. }());
  76223. BABYLON.PostProcess = PostProcess;
  76224. })(BABYLON || (BABYLON = {}));
  76225. //# sourceMappingURL=babylon.postProcess.js.map
  76226. var BABYLON;
  76227. (function (BABYLON) {
  76228. /**
  76229. * PassPostProcess which produces an output the same as it's input
  76230. */
  76231. var PassPostProcess = /** @class */ (function (_super) {
  76232. __extends(PassPostProcess, _super);
  76233. /**
  76234. * Creates the PassPostProcess
  76235. * @param name The name of the effect.
  76236. * @param options The required width/height ratio to downsize to before computing the render pass.
  76237. * @param camera The camera to apply the render pass to.
  76238. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  76239. * @param engine The engine which the post process will be applied. (default: current engine)
  76240. * @param reusable If the post process can be reused on the same frame. (default: false)
  76241. * @param textureType The type of texture to be used when performing the post processing.
  76242. * @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)
  76243. */
  76244. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  76245. if (camera === void 0) { camera = null; }
  76246. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76247. if (blockCompilation === void 0) { blockCompilation = false; }
  76248. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  76249. }
  76250. return PassPostProcess;
  76251. }(BABYLON.PostProcess));
  76252. BABYLON.PassPostProcess = PassPostProcess;
  76253. /**
  76254. * PassCubePostProcess which produces an output the same as it's input (which must be a cube texture)
  76255. */
  76256. var PassCubePostProcess = /** @class */ (function (_super) {
  76257. __extends(PassCubePostProcess, _super);
  76258. /**
  76259. * Creates the PassCubePostProcess
  76260. * @param name The name of the effect.
  76261. * @param options The required width/height ratio to downsize to before computing the render pass.
  76262. * @param camera The camera to apply the render pass to.
  76263. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  76264. * @param engine The engine which the post process will be applied. (default: current engine)
  76265. * @param reusable If the post process can be reused on the same frame. (default: false)
  76266. * @param textureType The type of texture to be used when performing the post processing.
  76267. * @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)
  76268. */
  76269. function PassCubePostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  76270. if (camera === void 0) { camera = null; }
  76271. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76272. if (blockCompilation === void 0) { blockCompilation = false; }
  76273. var _this = _super.call(this, name, "passCube", null, null, options, camera, samplingMode, engine, reusable, "#define POSITIVEX", textureType, undefined, null, blockCompilation) || this;
  76274. _this._face = 0;
  76275. return _this;
  76276. }
  76277. Object.defineProperty(PassCubePostProcess.prototype, "face", {
  76278. /**
  76279. * Gets or sets the cube face to display.
  76280. * * 0 is +X
  76281. * * 1 is -X
  76282. * * 2 is +Y
  76283. * * 3 is -Y
  76284. * * 4 is +Z
  76285. * * 5 is -Z
  76286. */
  76287. get: function () {
  76288. return this._face;
  76289. },
  76290. set: function (value) {
  76291. if (value < 0 || value > 5) {
  76292. return;
  76293. }
  76294. this._face = value;
  76295. switch (this._face) {
  76296. case 0:
  76297. this.updateEffect("#define POSITIVEX");
  76298. break;
  76299. case 1:
  76300. this.updateEffect("#define NEGATIVEX");
  76301. break;
  76302. case 2:
  76303. this.updateEffect("#define POSITIVEY");
  76304. break;
  76305. case 3:
  76306. this.updateEffect("#define NEGATIVEY");
  76307. break;
  76308. case 4:
  76309. this.updateEffect("#define POSITIVEZ");
  76310. break;
  76311. case 5:
  76312. this.updateEffect("#define NEGATIVEZ");
  76313. break;
  76314. }
  76315. },
  76316. enumerable: true,
  76317. configurable: true
  76318. });
  76319. return PassCubePostProcess;
  76320. }(BABYLON.PostProcess));
  76321. BABYLON.PassCubePostProcess = PassCubePostProcess;
  76322. })(BABYLON || (BABYLON = {}));
  76323. //# sourceMappingURL=babylon.passPostProcess.js.map
  76324. var __assign = (this && this.__assign) || function () {
  76325. __assign = Object.assign || function(t) {
  76326. for (var s, i = 1, n = arguments.length; i < n; i++) {
  76327. s = arguments[i];
  76328. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  76329. t[p] = s[p];
  76330. }
  76331. return t;
  76332. };
  76333. return __assign.apply(this, arguments);
  76334. };
  76335. var BABYLON;
  76336. (function (BABYLON) {
  76337. /**
  76338. * Default implementation IShadowGenerator.
  76339. * This is the main object responsible of generating shadows in the framework.
  76340. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  76341. */
  76342. var ShadowGenerator = /** @class */ (function () {
  76343. /**
  76344. * Creates a ShadowGenerator object.
  76345. * A ShadowGenerator is the required tool to use the shadows.
  76346. * Each light casting shadows needs to use its own ShadowGenerator.
  76347. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  76348. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  76349. * @param light The light object generating the shadows.
  76350. * @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.
  76351. */
  76352. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  76353. this._bias = 0.00005;
  76354. this._normalBias = 0;
  76355. this._blurBoxOffset = 1;
  76356. this._blurScale = 2;
  76357. this._blurKernel = 1;
  76358. this._useKernelBlur = false;
  76359. this._filter = ShadowGenerator.FILTER_NONE;
  76360. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  76361. this._contactHardeningLightSizeUVRatio = 0.1;
  76362. this._darkness = 0;
  76363. this._transparencyShadow = false;
  76364. /**
  76365. * Controls the extent to which the shadows fade out at the edge of the frustum
  76366. * Used only by directionals and spots
  76367. */
  76368. this.frustumEdgeFalloff = 0;
  76369. /**
  76370. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  76371. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  76372. * It might on the other hand introduce peter panning.
  76373. */
  76374. this.forceBackFacesOnly = false;
  76375. this._lightDirection = BABYLON.Vector3.Zero();
  76376. this._viewMatrix = BABYLON.Matrix.Zero();
  76377. this._projectionMatrix = BABYLON.Matrix.Zero();
  76378. this._transformMatrix = BABYLON.Matrix.Zero();
  76379. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  76380. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  76381. this._currentFaceIndex = 0;
  76382. this._currentFaceIndexCache = 0;
  76383. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  76384. this._mapSize = mapSize;
  76385. this._light = light;
  76386. this._scene = light.getScene();
  76387. light._shadowGenerator = this;
  76388. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_SHADOWGENERATOR);
  76389. if (!component) {
  76390. component = new BABYLON.ShadowGeneratorSceneComponent(this._scene);
  76391. this._scene._addComponent(component);
  76392. }
  76393. // Texture type fallback from float to int if not supported.
  76394. var caps = this._scene.getEngine().getCaps();
  76395. if (!useFullFloatFirst) {
  76396. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  76397. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  76398. }
  76399. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  76400. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  76401. }
  76402. else {
  76403. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  76404. }
  76405. }
  76406. else {
  76407. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  76408. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  76409. }
  76410. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  76411. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  76412. }
  76413. else {
  76414. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  76415. }
  76416. }
  76417. this._initializeGenerator();
  76418. this._applyFilterValues();
  76419. }
  76420. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  76421. /**
  76422. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  76423. */
  76424. get: function () {
  76425. return this._bias;
  76426. },
  76427. /**
  76428. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  76429. */
  76430. set: function (bias) {
  76431. this._bias = bias;
  76432. },
  76433. enumerable: true,
  76434. configurable: true
  76435. });
  76436. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  76437. /**
  76438. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  76439. */
  76440. get: function () {
  76441. return this._normalBias;
  76442. },
  76443. /**
  76444. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  76445. */
  76446. set: function (normalBias) {
  76447. this._normalBias = normalBias;
  76448. },
  76449. enumerable: true,
  76450. configurable: true
  76451. });
  76452. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  76453. /**
  76454. * Gets the blur box offset: offset applied during the blur pass.
  76455. * Only usefull if useKernelBlur = false
  76456. */
  76457. get: function () {
  76458. return this._blurBoxOffset;
  76459. },
  76460. /**
  76461. * Sets the blur box offset: offset applied during the blur pass.
  76462. * Only usefull if useKernelBlur = false
  76463. */
  76464. set: function (value) {
  76465. if (this._blurBoxOffset === value) {
  76466. return;
  76467. }
  76468. this._blurBoxOffset = value;
  76469. this._disposeBlurPostProcesses();
  76470. },
  76471. enumerable: true,
  76472. configurable: true
  76473. });
  76474. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  76475. /**
  76476. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  76477. * 2 means half of the size.
  76478. */
  76479. get: function () {
  76480. return this._blurScale;
  76481. },
  76482. /**
  76483. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  76484. * 2 means half of the size.
  76485. */
  76486. set: function (value) {
  76487. if (this._blurScale === value) {
  76488. return;
  76489. }
  76490. this._blurScale = value;
  76491. this._disposeBlurPostProcesses();
  76492. },
  76493. enumerable: true,
  76494. configurable: true
  76495. });
  76496. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  76497. /**
  76498. * Gets the blur kernel: kernel size of the blur pass.
  76499. * Only usefull if useKernelBlur = true
  76500. */
  76501. get: function () {
  76502. return this._blurKernel;
  76503. },
  76504. /**
  76505. * Sets the blur kernel: kernel size of the blur pass.
  76506. * Only usefull if useKernelBlur = true
  76507. */
  76508. set: function (value) {
  76509. if (this._blurKernel === value) {
  76510. return;
  76511. }
  76512. this._blurKernel = value;
  76513. this._disposeBlurPostProcesses();
  76514. },
  76515. enumerable: true,
  76516. configurable: true
  76517. });
  76518. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  76519. /**
  76520. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  76521. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  76522. */
  76523. get: function () {
  76524. return this._useKernelBlur;
  76525. },
  76526. /**
  76527. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  76528. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  76529. */
  76530. set: function (value) {
  76531. if (this._useKernelBlur === value) {
  76532. return;
  76533. }
  76534. this._useKernelBlur = value;
  76535. this._disposeBlurPostProcesses();
  76536. },
  76537. enumerable: true,
  76538. configurable: true
  76539. });
  76540. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  76541. /**
  76542. * Gets the depth scale used in ESM mode.
  76543. */
  76544. get: function () {
  76545. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  76546. },
  76547. /**
  76548. * Sets the depth scale used in ESM mode.
  76549. * This can override the scale stored on the light.
  76550. */
  76551. set: function (value) {
  76552. this._depthScale = value;
  76553. },
  76554. enumerable: true,
  76555. configurable: true
  76556. });
  76557. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  76558. /**
  76559. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  76560. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  76561. */
  76562. get: function () {
  76563. return this._filter;
  76564. },
  76565. /**
  76566. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  76567. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  76568. */
  76569. set: function (value) {
  76570. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  76571. if (this._light.needCube()) {
  76572. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  76573. this.useExponentialShadowMap = true;
  76574. return;
  76575. }
  76576. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  76577. this.useCloseExponentialShadowMap = true;
  76578. return;
  76579. }
  76580. // PCF on cubemap would also be expensive
  76581. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  76582. this.usePoissonSampling = true;
  76583. return;
  76584. }
  76585. }
  76586. // Weblg1 fallback for PCF.
  76587. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  76588. if (this._scene.getEngine().webGLVersion === 1) {
  76589. this.usePoissonSampling = true;
  76590. return;
  76591. }
  76592. }
  76593. if (this._filter === value) {
  76594. return;
  76595. }
  76596. this._filter = value;
  76597. this._disposeBlurPostProcesses();
  76598. this._applyFilterValues();
  76599. this._light._markMeshesAsLightDirty();
  76600. },
  76601. enumerable: true,
  76602. configurable: true
  76603. });
  76604. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  76605. /**
  76606. * Gets if the current filter is set to Poisson Sampling.
  76607. */
  76608. get: function () {
  76609. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  76610. },
  76611. /**
  76612. * Sets the current filter to Poisson Sampling.
  76613. */
  76614. set: function (value) {
  76615. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  76616. return;
  76617. }
  76618. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  76619. },
  76620. enumerable: true,
  76621. configurable: true
  76622. });
  76623. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  76624. /**
  76625. * Gets if the current filter is set to ESM.
  76626. */
  76627. get: function () {
  76628. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  76629. },
  76630. /**
  76631. * Sets the current filter is to ESM.
  76632. */
  76633. set: function (value) {
  76634. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  76635. return;
  76636. }
  76637. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  76638. },
  76639. enumerable: true,
  76640. configurable: true
  76641. });
  76642. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  76643. /**
  76644. * Gets if the current filter is set to filtered ESM.
  76645. */
  76646. get: function () {
  76647. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  76648. },
  76649. /**
  76650. * Gets if the current filter is set to filtered ESM.
  76651. */
  76652. set: function (value) {
  76653. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  76654. return;
  76655. }
  76656. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  76657. },
  76658. enumerable: true,
  76659. configurable: true
  76660. });
  76661. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  76662. /**
  76663. * Gets if the current filter is set to "close ESM" (using the inverse of the
  76664. * exponential to prevent steep falloff artifacts).
  76665. */
  76666. get: function () {
  76667. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  76668. },
  76669. /**
  76670. * Sets the current filter to "close ESM" (using the inverse of the
  76671. * exponential to prevent steep falloff artifacts).
  76672. */
  76673. set: function (value) {
  76674. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  76675. return;
  76676. }
  76677. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  76678. },
  76679. enumerable: true,
  76680. configurable: true
  76681. });
  76682. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  76683. /**
  76684. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  76685. * exponential to prevent steep falloff artifacts).
  76686. */
  76687. get: function () {
  76688. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  76689. },
  76690. /**
  76691. * Sets the current filter to filtered "close ESM" (using the inverse of the
  76692. * exponential to prevent steep falloff artifacts).
  76693. */
  76694. set: function (value) {
  76695. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  76696. return;
  76697. }
  76698. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  76699. },
  76700. enumerable: true,
  76701. configurable: true
  76702. });
  76703. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  76704. /**
  76705. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  76706. */
  76707. get: function () {
  76708. return this.filter === ShadowGenerator.FILTER_PCF;
  76709. },
  76710. /**
  76711. * Sets the current filter to "PCF" (percentage closer filtering).
  76712. */
  76713. set: function (value) {
  76714. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  76715. return;
  76716. }
  76717. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  76718. },
  76719. enumerable: true,
  76720. configurable: true
  76721. });
  76722. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  76723. /**
  76724. * Gets the PCF or PCSS Quality.
  76725. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  76726. */
  76727. get: function () {
  76728. return this._filteringQuality;
  76729. },
  76730. /**
  76731. * Sets the PCF or PCSS Quality.
  76732. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  76733. */
  76734. set: function (filteringQuality) {
  76735. this._filteringQuality = filteringQuality;
  76736. },
  76737. enumerable: true,
  76738. configurable: true
  76739. });
  76740. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  76741. /**
  76742. * Gets if the current filter is set to "PCSS" (contact hardening).
  76743. */
  76744. get: function () {
  76745. return this.filter === ShadowGenerator.FILTER_PCSS;
  76746. },
  76747. /**
  76748. * Sets the current filter to "PCSS" (contact hardening).
  76749. */
  76750. set: function (value) {
  76751. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  76752. return;
  76753. }
  76754. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  76755. },
  76756. enumerable: true,
  76757. configurable: true
  76758. });
  76759. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  76760. /**
  76761. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  76762. * Using a ratio helps keeping shape stability independently of the map size.
  76763. *
  76764. * It does not account for the light projection as it was having too much
  76765. * instability during the light setup or during light position changes.
  76766. *
  76767. * Only valid if useContactHardeningShadow is true.
  76768. */
  76769. get: function () {
  76770. return this._contactHardeningLightSizeUVRatio;
  76771. },
  76772. /**
  76773. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  76774. * Using a ratio helps keeping shape stability independently of the map size.
  76775. *
  76776. * It does not account for the light projection as it was having too much
  76777. * instability during the light setup or during light position changes.
  76778. *
  76779. * Only valid if useContactHardeningShadow is true.
  76780. */
  76781. set: function (contactHardeningLightSizeUVRatio) {
  76782. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  76783. },
  76784. enumerable: true,
  76785. configurable: true
  76786. });
  76787. /**
  76788. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  76789. * 0 means strongest and 1 would means no shadow.
  76790. * @returns the darkness.
  76791. */
  76792. ShadowGenerator.prototype.getDarkness = function () {
  76793. return this._darkness;
  76794. };
  76795. /**
  76796. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  76797. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  76798. * @returns the shadow generator allowing fluent coding.
  76799. */
  76800. ShadowGenerator.prototype.setDarkness = function (darkness) {
  76801. if (darkness >= 1.0) {
  76802. this._darkness = 1.0;
  76803. }
  76804. else if (darkness <= 0.0) {
  76805. this._darkness = 0.0;
  76806. }
  76807. else {
  76808. this._darkness = darkness;
  76809. }
  76810. return this;
  76811. };
  76812. /**
  76813. * Sets the ability to have transparent shadow (boolean).
  76814. * @param transparent True if transparent else False
  76815. * @returns the shadow generator allowing fluent coding
  76816. */
  76817. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  76818. this._transparencyShadow = transparent;
  76819. return this;
  76820. };
  76821. /**
  76822. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  76823. * @returns The render target texture if present otherwise, null
  76824. */
  76825. ShadowGenerator.prototype.getShadowMap = function () {
  76826. return this._shadowMap;
  76827. };
  76828. /**
  76829. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  76830. * @returns The render target texture if the shadow map is present otherwise, null
  76831. */
  76832. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  76833. if (this._shadowMap2) {
  76834. return this._shadowMap2;
  76835. }
  76836. return this._shadowMap;
  76837. };
  76838. /**
  76839. * Helper function to add a mesh and its descendants to the list of shadow casters.
  76840. * @param mesh Mesh to add
  76841. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  76842. * @returns the Shadow Generator itself
  76843. */
  76844. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  76845. if (includeDescendants === void 0) { includeDescendants = true; }
  76846. var _a;
  76847. if (!this._shadowMap) {
  76848. return this;
  76849. }
  76850. if (!this._shadowMap.renderList) {
  76851. this._shadowMap.renderList = [];
  76852. }
  76853. this._shadowMap.renderList.push(mesh);
  76854. if (includeDescendants) {
  76855. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  76856. }
  76857. return this;
  76858. };
  76859. /**
  76860. * Helper function to remove a mesh and its descendants from the list of shadow casters
  76861. * @param mesh Mesh to remove
  76862. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  76863. * @returns the Shadow Generator itself
  76864. */
  76865. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  76866. if (includeDescendants === void 0) { includeDescendants = true; }
  76867. if (!this._shadowMap || !this._shadowMap.renderList) {
  76868. return this;
  76869. }
  76870. var index = this._shadowMap.renderList.indexOf(mesh);
  76871. if (index !== -1) {
  76872. this._shadowMap.renderList.splice(index, 1);
  76873. }
  76874. if (includeDescendants) {
  76875. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  76876. var child = _a[_i];
  76877. this.removeShadowCaster(child);
  76878. }
  76879. }
  76880. return this;
  76881. };
  76882. /**
  76883. * Returns the associated light object.
  76884. * @returns the light generating the shadow
  76885. */
  76886. ShadowGenerator.prototype.getLight = function () {
  76887. return this._light;
  76888. };
  76889. ShadowGenerator.prototype._initializeGenerator = function () {
  76890. this._light._markMeshesAsLightDirty();
  76891. this._initializeShadowMap();
  76892. };
  76893. ShadowGenerator.prototype._initializeShadowMap = function () {
  76894. var _this = this;
  76895. // Render target
  76896. var engine = this._scene.getEngine();
  76897. if (engine.webGLVersion > 1) {
  76898. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  76899. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  76900. }
  76901. else {
  76902. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  76903. }
  76904. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76905. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76906. this._shadowMap.anisotropicFilteringLevel = 1;
  76907. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  76908. this._shadowMap.renderParticles = false;
  76909. this._shadowMap.ignoreCameraViewport = true;
  76910. // Record Face Index before render.
  76911. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  76912. _this._currentFaceIndex = faceIndex;
  76913. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  76914. engine.setColorWrite(false);
  76915. }
  76916. });
  76917. // Custom render function.
  76918. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  76919. // Blur if required afer render.
  76920. this._shadowMap.onAfterUnbindObservable.add(function () {
  76921. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  76922. engine.setColorWrite(true);
  76923. }
  76924. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  76925. return;
  76926. }
  76927. var shadowMap = _this.getShadowMapForRendering();
  76928. if (shadowMap) {
  76929. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  76930. }
  76931. });
  76932. // Clear according to the chosen filter.
  76933. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  76934. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  76935. this._shadowMap.onClearObservable.add(function (engine) {
  76936. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  76937. engine.clear(clearOne, false, true, false);
  76938. }
  76939. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  76940. engine.clear(clearZero, true, true, false);
  76941. }
  76942. else {
  76943. engine.clear(clearOne, true, true, false);
  76944. }
  76945. });
  76946. };
  76947. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  76948. var _this = this;
  76949. var engine = this._scene.getEngine();
  76950. var targetSize = this._mapSize / this.blurScale;
  76951. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  76952. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  76953. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76954. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76955. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  76956. }
  76957. if (this.useKernelBlur) {
  76958. 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);
  76959. this._kernelBlurXPostprocess.width = targetSize;
  76960. this._kernelBlurXPostprocess.height = targetSize;
  76961. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  76962. effect.setTexture("textureSampler", _this._shadowMap);
  76963. });
  76964. 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);
  76965. this._kernelBlurXPostprocess.autoClear = false;
  76966. this._kernelBlurYPostprocess.autoClear = false;
  76967. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  76968. this._kernelBlurXPostprocess.packedFloat = true;
  76969. this._kernelBlurYPostprocess.packedFloat = true;
  76970. }
  76971. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  76972. }
  76973. else {
  76974. 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);
  76975. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  76976. effect.setFloat2("screenSize", targetSize, targetSize);
  76977. effect.setTexture("textureSampler", _this._shadowMap);
  76978. });
  76979. this._boxBlurPostprocess.autoClear = false;
  76980. this._blurPostProcesses = [this._boxBlurPostprocess];
  76981. }
  76982. };
  76983. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  76984. var index;
  76985. var engine = this._scene.getEngine();
  76986. if (depthOnlySubMeshes.length) {
  76987. engine.setColorWrite(false);
  76988. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  76989. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  76990. }
  76991. engine.setColorWrite(true);
  76992. }
  76993. for (index = 0; index < opaqueSubMeshes.length; index++) {
  76994. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  76995. }
  76996. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  76997. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  76998. }
  76999. if (this._transparencyShadow) {
  77000. for (index = 0; index < transparentSubMeshes.length; index++) {
  77001. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  77002. }
  77003. }
  77004. };
  77005. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  77006. var _this = this;
  77007. var mesh = subMesh.getRenderingMesh();
  77008. var scene = this._scene;
  77009. var engine = scene.getEngine();
  77010. var material = subMesh.getMaterial();
  77011. if (!material || subMesh.verticesCount === 0) {
  77012. return;
  77013. }
  77014. // Culling
  77015. engine.setState(material.backFaceCulling);
  77016. // Managing instances
  77017. var batch = mesh._getInstancesRenderList(subMesh._id);
  77018. if (batch.mustReturn) {
  77019. return;
  77020. }
  77021. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  77022. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  77023. engine.enableEffect(this._effect);
  77024. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  77025. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  77026. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  77027. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  77028. this._effect.setVector3("lightData", this._cachedDirection);
  77029. }
  77030. else {
  77031. this._effect.setVector3("lightData", this._cachedPosition);
  77032. }
  77033. if (scene.activeCamera) {
  77034. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  77035. }
  77036. // Alpha test
  77037. if (material && material.needAlphaTesting()) {
  77038. var alphaTexture = material.getAlphaTestTexture();
  77039. if (alphaTexture) {
  77040. this._effect.setTexture("diffuseSampler", alphaTexture);
  77041. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  77042. }
  77043. }
  77044. // Bones
  77045. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  77046. var skeleton = mesh.skeleton;
  77047. if (skeleton.isUsingTextureForMatrices) {
  77048. var boneTexture = skeleton.getTransformMatrixTexture();
  77049. if (!boneTexture) {
  77050. return;
  77051. }
  77052. this._effect.setTexture("boneSampler", boneTexture);
  77053. this._effect.setFloat("boneTextureWidth", 4.0 * (skeleton.bones.length + 1));
  77054. }
  77055. else {
  77056. this._effect.setMatrices("mBones", skeleton.getTransformMatrices((mesh)));
  77057. }
  77058. }
  77059. // Morph targets
  77060. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  77061. if (this.forceBackFacesOnly) {
  77062. engine.setState(true, 0, false, true);
  77063. }
  77064. // Draw
  77065. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  77066. if (this.forceBackFacesOnly) {
  77067. engine.setState(true, 0, false, false);
  77068. }
  77069. }
  77070. else {
  77071. // Need to reset refresh rate of the shadowMap
  77072. if (this._shadowMap) {
  77073. this._shadowMap.resetRefreshCounter();
  77074. }
  77075. }
  77076. };
  77077. ShadowGenerator.prototype._applyFilterValues = function () {
  77078. if (!this._shadowMap) {
  77079. return;
  77080. }
  77081. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  77082. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  77083. }
  77084. else {
  77085. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  77086. }
  77087. };
  77088. /**
  77089. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  77090. * @param onCompiled Callback triggered at the and of the effects compilation
  77091. * @param options Sets of optional options forcing the compilation with different modes
  77092. */
  77093. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  77094. var _this = this;
  77095. var localOptions = __assign({ useInstances: false }, options);
  77096. var shadowMap = this.getShadowMap();
  77097. if (!shadowMap) {
  77098. if (onCompiled) {
  77099. onCompiled(this);
  77100. }
  77101. return;
  77102. }
  77103. var renderList = shadowMap.renderList;
  77104. if (!renderList) {
  77105. if (onCompiled) {
  77106. onCompiled(this);
  77107. }
  77108. return;
  77109. }
  77110. var subMeshes = new Array();
  77111. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  77112. var mesh = renderList_1[_i];
  77113. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  77114. }
  77115. if (subMeshes.length === 0) {
  77116. if (onCompiled) {
  77117. onCompiled(this);
  77118. }
  77119. return;
  77120. }
  77121. var currentIndex = 0;
  77122. var checkReady = function () {
  77123. if (!_this._scene || !_this._scene.getEngine()) {
  77124. return;
  77125. }
  77126. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  77127. currentIndex++;
  77128. if (currentIndex >= subMeshes.length) {
  77129. if (onCompiled) {
  77130. onCompiled(_this);
  77131. }
  77132. return;
  77133. }
  77134. }
  77135. setTimeout(checkReady, 16);
  77136. };
  77137. checkReady();
  77138. };
  77139. /**
  77140. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  77141. * @param options Sets of optional options forcing the compilation with different modes
  77142. * @returns A promise that resolves when the compilation completes
  77143. */
  77144. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  77145. var _this = this;
  77146. return new Promise(function (resolve) {
  77147. _this.forceCompilation(function () {
  77148. resolve();
  77149. }, options);
  77150. });
  77151. };
  77152. /**
  77153. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  77154. * @param subMesh The submesh we want to render in the shadow map
  77155. * @param useInstances Defines wether will draw in the map using instances
  77156. * @returns true if ready otherwise, false
  77157. */
  77158. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  77159. var defines = [];
  77160. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  77161. defines.push("#define FLOAT");
  77162. }
  77163. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  77164. defines.push("#define ESM");
  77165. }
  77166. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  77167. defines.push("#define DEPTHTEXTURE");
  77168. }
  77169. var attribs = [BABYLON.VertexBuffer.PositionKind];
  77170. var mesh = subMesh.getMesh();
  77171. var material = subMesh.getMaterial();
  77172. // Normal bias.
  77173. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  77174. attribs.push(BABYLON.VertexBuffer.NormalKind);
  77175. defines.push("#define NORMAL");
  77176. if (mesh.nonUniformScaling) {
  77177. defines.push("#define NONUNIFORMSCALING");
  77178. }
  77179. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  77180. defines.push("#define DIRECTIONINLIGHTDATA");
  77181. }
  77182. }
  77183. // Alpha test
  77184. if (material && material.needAlphaTesting()) {
  77185. var alphaTexture = material.getAlphaTestTexture();
  77186. if (alphaTexture) {
  77187. defines.push("#define ALPHATEST");
  77188. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  77189. attribs.push(BABYLON.VertexBuffer.UVKind);
  77190. defines.push("#define UV1");
  77191. }
  77192. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  77193. if (alphaTexture.coordinatesIndex === 1) {
  77194. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  77195. defines.push("#define UV2");
  77196. }
  77197. }
  77198. }
  77199. }
  77200. // Bones
  77201. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  77202. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  77203. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  77204. if (mesh.numBoneInfluencers > 4) {
  77205. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  77206. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  77207. }
  77208. var skeleton = mesh.skeleton;
  77209. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  77210. if (skeleton.isUsingTextureForMatrices) {
  77211. defines.push("#define BONETEXTURE");
  77212. }
  77213. else {
  77214. defines.push("#define BonesPerMesh " + (skeleton.bones.length + 1));
  77215. }
  77216. }
  77217. else {
  77218. defines.push("#define NUM_BONE_INFLUENCERS 0");
  77219. }
  77220. // Morph targets
  77221. var manager = mesh.morphTargetManager;
  77222. var morphInfluencers = 0;
  77223. if (manager) {
  77224. if (manager.numInfluencers > 0) {
  77225. defines.push("#define MORPHTARGETS");
  77226. morphInfluencers = manager.numInfluencers;
  77227. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  77228. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  77229. }
  77230. }
  77231. // Instances
  77232. if (useInstances) {
  77233. defines.push("#define INSTANCES");
  77234. attribs.push("world0");
  77235. attribs.push("world1");
  77236. attribs.push("world2");
  77237. attribs.push("world3");
  77238. }
  77239. // Get correct effect
  77240. var join = defines.join("\n");
  77241. if (this._cachedDefines !== join) {
  77242. this._cachedDefines = join;
  77243. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences", "boneTextureWidth"], ["diffuseSampler", "boneSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  77244. }
  77245. if (!this._effect.isReady()) {
  77246. return false;
  77247. }
  77248. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  77249. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  77250. this._initializeBlurRTTAndPostProcesses();
  77251. }
  77252. }
  77253. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  77254. return false;
  77255. }
  77256. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  77257. return false;
  77258. }
  77259. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  77260. return false;
  77261. }
  77262. return true;
  77263. };
  77264. /**
  77265. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  77266. * @param defines Defines of the material we want to update
  77267. * @param lightIndex Index of the light in the enabled light list of the material
  77268. */
  77269. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  77270. var scene = this._scene;
  77271. var light = this._light;
  77272. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  77273. return;
  77274. }
  77275. defines["SHADOW" + lightIndex] = true;
  77276. if (this.useContactHardeningShadow) {
  77277. defines["SHADOWPCSS" + lightIndex] = true;
  77278. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  77279. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  77280. }
  77281. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  77282. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  77283. }
  77284. // else default to high.
  77285. }
  77286. if (this.usePercentageCloserFiltering) {
  77287. defines["SHADOWPCF" + lightIndex] = true;
  77288. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  77289. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  77290. }
  77291. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  77292. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  77293. }
  77294. // else default to high.
  77295. }
  77296. else if (this.usePoissonSampling) {
  77297. defines["SHADOWPOISSON" + lightIndex] = true;
  77298. }
  77299. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  77300. defines["SHADOWESM" + lightIndex] = true;
  77301. }
  77302. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  77303. defines["SHADOWCLOSEESM" + lightIndex] = true;
  77304. }
  77305. if (light.needCube()) {
  77306. defines["SHADOWCUBE" + lightIndex] = true;
  77307. }
  77308. };
  77309. /**
  77310. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  77311. * defined in the generator but impacting the effect).
  77312. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  77313. * @param effect The effect we are binfing the information for
  77314. */
  77315. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  77316. var light = this._light;
  77317. var scene = this._scene;
  77318. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  77319. return;
  77320. }
  77321. var camera = scene.activeCamera;
  77322. if (!camera) {
  77323. return;
  77324. }
  77325. var shadowMap = this.getShadowMap();
  77326. if (!shadowMap) {
  77327. return;
  77328. }
  77329. if (!light.needCube()) {
  77330. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  77331. }
  77332. // Only PCF uses depth stencil texture.
  77333. if (this._filter === ShadowGenerator.FILTER_PCF) {
  77334. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  77335. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  77336. }
  77337. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  77338. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  77339. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  77340. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  77341. }
  77342. else {
  77343. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  77344. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  77345. }
  77346. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  77347. };
  77348. /**
  77349. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  77350. * (eq to shadow prjection matrix * light transform matrix)
  77351. * @returns The transform matrix used to create the shadow map
  77352. */
  77353. ShadowGenerator.prototype.getTransformMatrix = function () {
  77354. var scene = this._scene;
  77355. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  77356. return this._transformMatrix;
  77357. }
  77358. this._currentRenderID = scene.getRenderId();
  77359. this._currentFaceIndexCache = this._currentFaceIndex;
  77360. var lightPosition = this._light.position;
  77361. if (this._light.computeTransformedInformation()) {
  77362. lightPosition = this._light.transformedPosition;
  77363. }
  77364. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  77365. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  77366. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  77367. }
  77368. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  77369. this._cachedPosition.copyFrom(lightPosition);
  77370. this._cachedDirection.copyFrom(this._lightDirection);
  77371. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  77372. var shadowMap = this.getShadowMap();
  77373. if (shadowMap) {
  77374. var renderList = shadowMap.renderList;
  77375. if (renderList) {
  77376. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  77377. }
  77378. }
  77379. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  77380. }
  77381. return this._transformMatrix;
  77382. };
  77383. /**
  77384. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  77385. * Cube and 2D textures for instance.
  77386. */
  77387. ShadowGenerator.prototype.recreateShadowMap = function () {
  77388. var shadowMap = this._shadowMap;
  77389. if (!shadowMap) {
  77390. return;
  77391. }
  77392. // Track render list.
  77393. var renderList = shadowMap.renderList;
  77394. // Clean up existing data.
  77395. this._disposeRTTandPostProcesses();
  77396. // Reinitializes.
  77397. this._initializeGenerator();
  77398. // Reaffect the filter to ensure a correct fallback if necessary.
  77399. this.filter = this.filter;
  77400. // Reaffect the filter.
  77401. this._applyFilterValues();
  77402. // Reaffect Render List.
  77403. this._shadowMap.renderList = renderList;
  77404. };
  77405. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  77406. if (this._shadowMap2) {
  77407. this._shadowMap2.dispose();
  77408. this._shadowMap2 = null;
  77409. }
  77410. if (this._boxBlurPostprocess) {
  77411. this._boxBlurPostprocess.dispose();
  77412. this._boxBlurPostprocess = null;
  77413. }
  77414. if (this._kernelBlurXPostprocess) {
  77415. this._kernelBlurXPostprocess.dispose();
  77416. this._kernelBlurXPostprocess = null;
  77417. }
  77418. if (this._kernelBlurYPostprocess) {
  77419. this._kernelBlurYPostprocess.dispose();
  77420. this._kernelBlurYPostprocess = null;
  77421. }
  77422. this._blurPostProcesses = [];
  77423. };
  77424. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  77425. if (this._shadowMap) {
  77426. this._shadowMap.dispose();
  77427. this._shadowMap = null;
  77428. }
  77429. this._disposeBlurPostProcesses();
  77430. };
  77431. /**
  77432. * Disposes the ShadowGenerator.
  77433. * Returns nothing.
  77434. */
  77435. ShadowGenerator.prototype.dispose = function () {
  77436. this._disposeRTTandPostProcesses();
  77437. if (this._light) {
  77438. this._light._shadowGenerator = null;
  77439. this._light._markMeshesAsLightDirty();
  77440. }
  77441. };
  77442. /**
  77443. * Serializes the shadow generator setup to a json object.
  77444. * @returns The serialized JSON object
  77445. */
  77446. ShadowGenerator.prototype.serialize = function () {
  77447. var serializationObject = {};
  77448. var shadowMap = this.getShadowMap();
  77449. if (!shadowMap) {
  77450. return serializationObject;
  77451. }
  77452. serializationObject.lightId = this._light.id;
  77453. serializationObject.mapSize = shadowMap.getRenderSize();
  77454. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  77455. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  77456. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  77457. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  77458. serializationObject.usePoissonSampling = this.usePoissonSampling;
  77459. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  77460. serializationObject.depthScale = this.depthScale;
  77461. serializationObject.darkness = this.getDarkness();
  77462. serializationObject.blurBoxOffset = this.blurBoxOffset;
  77463. serializationObject.blurKernel = this.blurKernel;
  77464. serializationObject.blurScale = this.blurScale;
  77465. serializationObject.useKernelBlur = this.useKernelBlur;
  77466. serializationObject.transparencyShadow = this._transparencyShadow;
  77467. serializationObject.frustumEdgeFalloff = this.frustumEdgeFalloff;
  77468. serializationObject.bias = this.bias;
  77469. serializationObject.normalBias = this.normalBias;
  77470. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  77471. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  77472. serializationObject.filteringQuality = this.filteringQuality;
  77473. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  77474. serializationObject.renderList = [];
  77475. if (shadowMap.renderList) {
  77476. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  77477. var mesh = shadowMap.renderList[meshIndex];
  77478. serializationObject.renderList.push(mesh.id);
  77479. }
  77480. }
  77481. return serializationObject;
  77482. };
  77483. /**
  77484. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  77485. * @param parsedShadowGenerator The JSON object to parse
  77486. * @param scene The scene to create the shadow map for
  77487. * @returns The parsed shadow generator
  77488. */
  77489. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  77490. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  77491. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  77492. var shadowMap = shadowGenerator.getShadowMap();
  77493. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  77494. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  77495. meshes.forEach(function (mesh) {
  77496. if (!shadowMap) {
  77497. return;
  77498. }
  77499. if (!shadowMap.renderList) {
  77500. shadowMap.renderList = [];
  77501. }
  77502. shadowMap.renderList.push(mesh);
  77503. });
  77504. }
  77505. if (parsedShadowGenerator.usePoissonSampling) {
  77506. shadowGenerator.usePoissonSampling = true;
  77507. }
  77508. else if (parsedShadowGenerator.useExponentialShadowMap) {
  77509. shadowGenerator.useExponentialShadowMap = true;
  77510. }
  77511. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  77512. shadowGenerator.useBlurExponentialShadowMap = true;
  77513. }
  77514. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  77515. shadowGenerator.useCloseExponentialShadowMap = true;
  77516. }
  77517. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  77518. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  77519. }
  77520. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  77521. shadowGenerator.usePercentageCloserFiltering = true;
  77522. }
  77523. else if (parsedShadowGenerator.useContactHardeningShadow) {
  77524. shadowGenerator.useContactHardeningShadow = true;
  77525. }
  77526. if (parsedShadowGenerator.filteringQuality) {
  77527. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  77528. }
  77529. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  77530. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  77531. }
  77532. // Backward compat
  77533. else if (parsedShadowGenerator.useVarianceShadowMap) {
  77534. shadowGenerator.useExponentialShadowMap = true;
  77535. }
  77536. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  77537. shadowGenerator.useBlurExponentialShadowMap = true;
  77538. }
  77539. if (parsedShadowGenerator.depthScale) {
  77540. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  77541. }
  77542. if (parsedShadowGenerator.blurScale) {
  77543. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  77544. }
  77545. if (parsedShadowGenerator.blurBoxOffset) {
  77546. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  77547. }
  77548. if (parsedShadowGenerator.useKernelBlur) {
  77549. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  77550. }
  77551. if (parsedShadowGenerator.blurKernel) {
  77552. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  77553. }
  77554. if (parsedShadowGenerator.bias !== undefined) {
  77555. shadowGenerator.bias = parsedShadowGenerator.bias;
  77556. }
  77557. if (parsedShadowGenerator.normalBias !== undefined) {
  77558. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  77559. }
  77560. if (parsedShadowGenerator.frustumEdgeFalloff !== undefined) {
  77561. shadowGenerator.frustumEdgeFalloff = parsedShadowGenerator.frustumEdgeFalloff;
  77562. }
  77563. if (parsedShadowGenerator.darkness) {
  77564. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  77565. }
  77566. if (parsedShadowGenerator.transparencyShadow) {
  77567. shadowGenerator.setTransparencyShadow(true);
  77568. }
  77569. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  77570. return shadowGenerator;
  77571. };
  77572. /**
  77573. * Shadow generator mode None: no filtering applied.
  77574. */
  77575. ShadowGenerator.FILTER_NONE = 0;
  77576. /**
  77577. * Shadow generator mode ESM: Exponential Shadow Mapping.
  77578. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  77579. */
  77580. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  77581. /**
  77582. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  77583. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  77584. */
  77585. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  77586. /**
  77587. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  77588. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  77589. */
  77590. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  77591. /**
  77592. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  77593. * edge artifacts on steep falloff.
  77594. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  77595. */
  77596. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  77597. /**
  77598. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  77599. * edge artifacts on steep falloff.
  77600. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  77601. */
  77602. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  77603. /**
  77604. * Shadow generator mode PCF: Percentage Closer Filtering
  77605. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  77606. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  77607. */
  77608. ShadowGenerator.FILTER_PCF = 6;
  77609. /**
  77610. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  77611. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  77612. * Contact Hardening
  77613. */
  77614. ShadowGenerator.FILTER_PCSS = 7;
  77615. /**
  77616. * Reserved for PCF and PCSS
  77617. * Highest Quality.
  77618. *
  77619. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  77620. *
  77621. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  77622. */
  77623. ShadowGenerator.QUALITY_HIGH = 0;
  77624. /**
  77625. * Reserved for PCF and PCSS
  77626. * Good tradeoff for quality/perf cross devices
  77627. *
  77628. * Execute PCF on a 3*3 kernel.
  77629. *
  77630. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  77631. */
  77632. ShadowGenerator.QUALITY_MEDIUM = 1;
  77633. /**
  77634. * Reserved for PCF and PCSS
  77635. * The lowest quality but the fastest.
  77636. *
  77637. * Execute PCF on a 1*1 kernel.
  77638. *
  77639. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  77640. */
  77641. ShadowGenerator.QUALITY_LOW = 2;
  77642. return ShadowGenerator;
  77643. }());
  77644. BABYLON.ShadowGenerator = ShadowGenerator;
  77645. })(BABYLON || (BABYLON = {}));
  77646. //# sourceMappingURL=babylon.shadowGenerator.js.map
  77647. var BABYLON;
  77648. (function (BABYLON) {
  77649. // Adds the parser to the scene parsers.
  77650. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_SHADOWGENERATOR, function (parsedData, scene, container, rootUrl) {
  77651. // Shadows
  77652. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  77653. for (var index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  77654. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  77655. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  77656. // SG would be available on their associated lights
  77657. }
  77658. }
  77659. });
  77660. /**
  77661. * Defines the shadow generator component responsible to manage any shadow generators
  77662. * in a given scene.
  77663. */
  77664. var ShadowGeneratorSceneComponent = /** @class */ (function () {
  77665. /**
  77666. * Creates a new instance of the component for the given scene
  77667. * @param scene Defines the scene to register the component in
  77668. */
  77669. function ShadowGeneratorSceneComponent(scene) {
  77670. /**
  77671. * The component name helpfull to identify the component in the list of scene components.
  77672. */
  77673. this.name = BABYLON.SceneComponentConstants.NAME_SHADOWGENERATOR;
  77674. this.scene = scene;
  77675. }
  77676. /**
  77677. * Registers the component in a given scene
  77678. */
  77679. ShadowGeneratorSceneComponent.prototype.register = function () {
  77680. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR, this, this._gatherRenderTargets);
  77681. };
  77682. /**
  77683. * Rebuilds the elements related to this component in case of
  77684. * context lost for instance.
  77685. */
  77686. ShadowGeneratorSceneComponent.prototype.rebuild = function () {
  77687. // Nothing To Do Here.
  77688. };
  77689. /**
  77690. * Serializes the component data to the specified json object
  77691. * @param serializationObject The object to serialize to
  77692. */
  77693. ShadowGeneratorSceneComponent.prototype.serialize = function (serializationObject) {
  77694. // Shadows
  77695. serializationObject.shadowGenerators = [];
  77696. var lights = this.scene.lights;
  77697. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  77698. var light = lights_1[_i];
  77699. var shadowGenerator = light.getShadowGenerator();
  77700. if (shadowGenerator) {
  77701. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  77702. }
  77703. }
  77704. };
  77705. /**
  77706. * Adds all the element from the container to the scene
  77707. * @param container the container holding the elements
  77708. */
  77709. ShadowGeneratorSceneComponent.prototype.addFromContainer = function (container) {
  77710. // Nothing To Do Here. (directly attached to a light)
  77711. };
  77712. /**
  77713. * Removes all the elements in the container from the scene
  77714. * @param container contains the elements to remove
  77715. */
  77716. ShadowGeneratorSceneComponent.prototype.removeFromContainer = function (container) {
  77717. // Nothing To Do Here. (directly attached to a light)
  77718. };
  77719. /**
  77720. * Rebuilds the elements related to this component in case of
  77721. * context lost for instance.
  77722. */
  77723. ShadowGeneratorSceneComponent.prototype.dispose = function () {
  77724. // Nothing To Do Here.
  77725. };
  77726. ShadowGeneratorSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  77727. // Shadows
  77728. var scene = this.scene;
  77729. if (this.scene.shadowsEnabled) {
  77730. for (var lightIndex = 0; lightIndex < scene.lights.length; lightIndex++) {
  77731. var light = scene.lights[lightIndex];
  77732. var shadowGenerator = light.getShadowGenerator();
  77733. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  77734. var shadowMap = (shadowGenerator.getShadowMap());
  77735. if (scene.textures.indexOf(shadowMap) !== -1) {
  77736. renderTargets.push(shadowMap);
  77737. }
  77738. }
  77739. }
  77740. }
  77741. };
  77742. return ShadowGeneratorSceneComponent;
  77743. }());
  77744. BABYLON.ShadowGeneratorSceneComponent = ShadowGeneratorSceneComponent;
  77745. })(BABYLON || (BABYLON = {}));
  77746. //# sourceMappingURL=babylon.shadowGeneratorSceneComponent.js.map
  77747. var BABYLON;
  77748. (function (BABYLON) {
  77749. /**
  77750. * Class used for the default loading screen
  77751. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  77752. */
  77753. var DefaultLoadingScreen = /** @class */ (function () {
  77754. /**
  77755. * Creates a new default loading screen
  77756. * @param _renderingCanvas defines the canvas used to render the scene
  77757. * @param _loadingText defines the default text to display
  77758. * @param _loadingDivBackgroundColor defines the default background color
  77759. */
  77760. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  77761. if (_loadingText === void 0) { _loadingText = ""; }
  77762. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  77763. var _this = this;
  77764. this._renderingCanvas = _renderingCanvas;
  77765. this._loadingText = _loadingText;
  77766. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  77767. // Resize
  77768. this._resizeLoadingUI = function () {
  77769. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  77770. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  77771. if (!_this._loadingDiv) {
  77772. return;
  77773. }
  77774. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  77775. _this._loadingDiv.style.left = canvasRect.left + "px";
  77776. _this._loadingDiv.style.top = canvasRect.top + "px";
  77777. _this._loadingDiv.style.width = canvasRect.width + "px";
  77778. _this._loadingDiv.style.height = canvasRect.height + "px";
  77779. };
  77780. }
  77781. /**
  77782. * Function called to display the loading screen
  77783. */
  77784. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  77785. if (this._loadingDiv) {
  77786. // Do not add a loading screen if there is already one
  77787. return;
  77788. }
  77789. this._loadingDiv = document.createElement("div");
  77790. this._loadingDiv.id = "babylonjsLoadingDiv";
  77791. this._loadingDiv.style.opacity = "0";
  77792. this._loadingDiv.style.transition = "opacity 1.5s ease";
  77793. this._loadingDiv.style.pointerEvents = "none";
  77794. // Loading text
  77795. this._loadingTextDiv = document.createElement("div");
  77796. this._loadingTextDiv.style.position = "absolute";
  77797. this._loadingTextDiv.style.left = "0";
  77798. this._loadingTextDiv.style.top = "50%";
  77799. this._loadingTextDiv.style.marginTop = "80px";
  77800. this._loadingTextDiv.style.width = "100%";
  77801. this._loadingTextDiv.style.height = "20px";
  77802. this._loadingTextDiv.style.fontFamily = "Arial";
  77803. this._loadingTextDiv.style.fontSize = "14px";
  77804. this._loadingTextDiv.style.color = "white";
  77805. this._loadingTextDiv.style.textAlign = "center";
  77806. this._loadingTextDiv.innerHTML = "Loading";
  77807. this._loadingDiv.appendChild(this._loadingTextDiv);
  77808. //set the predefined text
  77809. this._loadingTextDiv.innerHTML = this._loadingText;
  77810. // Generating keyframes
  77811. var style = document.createElement('style');
  77812. style.type = 'text/css';
  77813. 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 }";
  77814. style.innerHTML = keyFrames;
  77815. document.getElementsByTagName('head')[0].appendChild(style);
  77816. // Loading img
  77817. var imgBack = new Image();
  77818. 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";
  77819. imgBack.style.position = "absolute";
  77820. imgBack.style.left = "50%";
  77821. imgBack.style.top = "50%";
  77822. imgBack.style.marginLeft = "-60px";
  77823. imgBack.style.marginTop = "-60px";
  77824. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  77825. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  77826. imgBack.style.transformOrigin = "50% 50%";
  77827. imgBack.style.webkitTransformOrigin = "50% 50%";
  77828. this._loadingDiv.appendChild(imgBack);
  77829. this._resizeLoadingUI();
  77830. window.addEventListener("resize", this._resizeLoadingUI);
  77831. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  77832. document.body.appendChild(this._loadingDiv);
  77833. this._loadingDiv.style.opacity = "1";
  77834. };
  77835. /**
  77836. * Function called to hide the loading screen
  77837. */
  77838. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  77839. var _this = this;
  77840. if (!this._loadingDiv) {
  77841. return;
  77842. }
  77843. var onTransitionEnd = function () {
  77844. if (!_this._loadingDiv) {
  77845. return;
  77846. }
  77847. document.body.removeChild(_this._loadingDiv);
  77848. window.removeEventListener("resize", _this._resizeLoadingUI);
  77849. _this._loadingDiv = null;
  77850. };
  77851. this._loadingDiv.style.opacity = "0";
  77852. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  77853. };
  77854. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  77855. get: function () {
  77856. return this._loadingText;
  77857. },
  77858. /**
  77859. * Gets or sets the text to display while loading
  77860. */
  77861. set: function (text) {
  77862. this._loadingText = text;
  77863. if (this._loadingTextDiv) {
  77864. this._loadingTextDiv.innerHTML = this._loadingText;
  77865. }
  77866. },
  77867. enumerable: true,
  77868. configurable: true
  77869. });
  77870. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  77871. /**
  77872. * Gets or sets the color to use for the background
  77873. */
  77874. get: function () {
  77875. return this._loadingDivBackgroundColor;
  77876. },
  77877. set: function (color) {
  77878. this._loadingDivBackgroundColor = color;
  77879. if (!this._loadingDiv) {
  77880. return;
  77881. }
  77882. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  77883. },
  77884. enumerable: true,
  77885. configurable: true
  77886. });
  77887. return DefaultLoadingScreen;
  77888. }());
  77889. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  77890. })(BABYLON || (BABYLON = {}));
  77891. //# sourceMappingURL=babylon.loadingScreen.js.map
  77892. var BABYLON;
  77893. (function (BABYLON) {
  77894. /**
  77895. * Class used to represent data loading progression
  77896. */
  77897. var SceneLoaderProgressEvent = /** @class */ (function () {
  77898. /**
  77899. * Create a new progress event
  77900. * @param lengthComputable defines if data length to load can be evaluated
  77901. * @param loaded defines the loaded data length
  77902. * @param total defines the data length to load
  77903. */
  77904. function SceneLoaderProgressEvent(
  77905. /** defines if data length to load can be evaluated */
  77906. lengthComputable,
  77907. /** defines the loaded data length */
  77908. loaded,
  77909. /** defines the data length to load */
  77910. total) {
  77911. this.lengthComputable = lengthComputable;
  77912. this.loaded = loaded;
  77913. this.total = total;
  77914. }
  77915. /**
  77916. * Creates a new SceneLoaderProgressEvent from a ProgressEvent
  77917. * @param event defines the source event
  77918. * @returns a new SceneLoaderProgressEvent
  77919. */
  77920. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  77921. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  77922. };
  77923. return SceneLoaderProgressEvent;
  77924. }());
  77925. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  77926. /**
  77927. * Class used to load scene from various file formats using registered plugins
  77928. * @see http://doc.babylonjs.com/how_to/load_from_any_file_type
  77929. */
  77930. var SceneLoader = /** @class */ (function () {
  77931. function SceneLoader() {
  77932. }
  77933. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  77934. /**
  77935. * Gets or sets a boolean indicating if entire scene must be loaded even if scene contains incremental data
  77936. */
  77937. get: function () {
  77938. return SceneLoader._ForceFullSceneLoadingForIncremental;
  77939. },
  77940. set: function (value) {
  77941. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  77942. },
  77943. enumerable: true,
  77944. configurable: true
  77945. });
  77946. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  77947. /**
  77948. * Gets or sets a boolean indicating if loading screen must be displayed while loading a scene
  77949. */
  77950. get: function () {
  77951. return SceneLoader._ShowLoadingScreen;
  77952. },
  77953. set: function (value) {
  77954. SceneLoader._ShowLoadingScreen = value;
  77955. },
  77956. enumerable: true,
  77957. configurable: true
  77958. });
  77959. Object.defineProperty(SceneLoader, "loggingLevel", {
  77960. /**
  77961. * Defines the current logging level (while loading the scene)
  77962. * @ignorenaming
  77963. */
  77964. get: function () {
  77965. return SceneLoader._loggingLevel;
  77966. },
  77967. set: function (value) {
  77968. SceneLoader._loggingLevel = value;
  77969. },
  77970. enumerable: true,
  77971. configurable: true
  77972. });
  77973. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  77974. /**
  77975. * Gets or set a boolean indicating if matrix weights must be cleaned upon loading
  77976. */
  77977. get: function () {
  77978. return SceneLoader._CleanBoneMatrixWeights;
  77979. },
  77980. set: function (value) {
  77981. SceneLoader._CleanBoneMatrixWeights = value;
  77982. },
  77983. enumerable: true,
  77984. configurable: true
  77985. });
  77986. SceneLoader._getDefaultPlugin = function () {
  77987. return SceneLoader._registeredPlugins[".babylon"];
  77988. };
  77989. SceneLoader._getPluginForExtension = function (extension) {
  77990. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  77991. if (registeredPlugin) {
  77992. return registeredPlugin;
  77993. }
  77994. 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");
  77995. return SceneLoader._getDefaultPlugin();
  77996. };
  77997. SceneLoader._getPluginForDirectLoad = function (data) {
  77998. for (var extension in SceneLoader._registeredPlugins) {
  77999. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  78000. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  78001. return SceneLoader._registeredPlugins[extension];
  78002. }
  78003. }
  78004. return SceneLoader._getDefaultPlugin();
  78005. };
  78006. SceneLoader._getPluginForFilename = function (sceneFilename) {
  78007. var queryStringPosition = sceneFilename.indexOf("?");
  78008. if (queryStringPosition !== -1) {
  78009. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  78010. }
  78011. var dotPosition = sceneFilename.lastIndexOf(".");
  78012. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  78013. return SceneLoader._getPluginForExtension(extension);
  78014. };
  78015. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  78016. SceneLoader._getDirectLoad = function (sceneFilename) {
  78017. if (sceneFilename.substr(0, 5) === "data:") {
  78018. return sceneFilename.substr(5);
  78019. }
  78020. return null;
  78021. };
  78022. SceneLoader._loadData = function (fileInfo, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  78023. var directLoad = SceneLoader._getDirectLoad(fileInfo.name);
  78024. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(fileInfo.name) : SceneLoader._getPluginForFilename(fileInfo.name));
  78025. var plugin;
  78026. if (registeredPlugin.plugin.createPlugin) {
  78027. plugin = registeredPlugin.plugin.createPlugin();
  78028. }
  78029. else {
  78030. plugin = registeredPlugin.plugin;
  78031. }
  78032. var useArrayBuffer = registeredPlugin.isBinary;
  78033. var offlineProvider;
  78034. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  78035. var dataCallback = function (data, responseURL) {
  78036. if (scene.isDisposed) {
  78037. onError("Scene has been disposed");
  78038. return;
  78039. }
  78040. scene.offlineProvider = offlineProvider;
  78041. onSuccess(plugin, data, responseURL);
  78042. };
  78043. var request = null;
  78044. var pluginDisposed = false;
  78045. var onDisposeObservable = plugin.onDisposeObservable;
  78046. if (onDisposeObservable) {
  78047. onDisposeObservable.add(function () {
  78048. pluginDisposed = true;
  78049. if (request) {
  78050. request.abort();
  78051. request = null;
  78052. }
  78053. onDispose();
  78054. });
  78055. }
  78056. var manifestChecked = function () {
  78057. if (pluginDisposed) {
  78058. return;
  78059. }
  78060. request = BABYLON.Tools.LoadFile(fileInfo.url, dataCallback, onProgress ? function (event) {
  78061. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  78062. } : undefined, offlineProvider, useArrayBuffer, function (request, exception) {
  78063. onError("Failed to load scene." + (exception ? " " + exception.message : ""), exception);
  78064. });
  78065. };
  78066. if (directLoad) {
  78067. dataCallback(directLoad);
  78068. return plugin;
  78069. }
  78070. var file = BABYLON.FilesInput.FilesToLoad[fileInfo.name.toLowerCase()];
  78071. if (fileInfo.rootUrl.indexOf("file:") === -1 || (fileInfo.rootUrl.indexOf("file:") !== -1 && !file)) {
  78072. var engine = scene.getEngine();
  78073. var canUseOfflineSupport = engine.enableOfflineSupport;
  78074. if (canUseOfflineSupport) {
  78075. // Also check for exceptions
  78076. var exceptionFound = false;
  78077. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  78078. var regex = _a[_i];
  78079. if (regex.test(fileInfo.url)) {
  78080. exceptionFound = true;
  78081. break;
  78082. }
  78083. }
  78084. canUseOfflineSupport = !exceptionFound;
  78085. }
  78086. if (canUseOfflineSupport && BABYLON.Engine.OfflineProviderFactory) {
  78087. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  78088. offlineProvider = BABYLON.Engine.OfflineProviderFactory(fileInfo.url, manifestChecked, engine.disableManifestCheck);
  78089. }
  78090. else {
  78091. manifestChecked();
  78092. }
  78093. }
  78094. // Loading file from disk via input file or drag'n'drop
  78095. else {
  78096. if (file) {
  78097. request = BABYLON.Tools.ReadFile(file, dataCallback, onProgress, useArrayBuffer);
  78098. }
  78099. else {
  78100. onError("Unable to find file named " + fileInfo.name);
  78101. }
  78102. }
  78103. return plugin;
  78104. };
  78105. SceneLoader._getFileInfo = function (rootUrl, sceneFilename) {
  78106. var url;
  78107. var name;
  78108. if (!sceneFilename) {
  78109. url = rootUrl;
  78110. name = BABYLON.Tools.GetFilename(rootUrl);
  78111. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  78112. }
  78113. else {
  78114. if (sceneFilename.substr(0, 1) === "/") {
  78115. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  78116. return null;
  78117. }
  78118. url = rootUrl + sceneFilename;
  78119. name = sceneFilename;
  78120. }
  78121. return {
  78122. url: url,
  78123. rootUrl: rootUrl,
  78124. name: name
  78125. };
  78126. };
  78127. // Public functions
  78128. /**
  78129. * Gets a plugin that can load the given extension
  78130. * @param extension defines the extension to load
  78131. * @returns a plugin or null if none works
  78132. */
  78133. SceneLoader.GetPluginForExtension = function (extension) {
  78134. return SceneLoader._getPluginForExtension(extension).plugin;
  78135. };
  78136. /**
  78137. * Gets a boolean indicating that the given extension can be loaded
  78138. * @param extension defines the extension to load
  78139. * @returns true if the extension is supported
  78140. */
  78141. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  78142. return !!SceneLoader._registeredPlugins[extension];
  78143. };
  78144. /**
  78145. * Adds a new plugin to the list of registered plugins
  78146. * @param plugin defines the plugin to add
  78147. */
  78148. SceneLoader.RegisterPlugin = function (plugin) {
  78149. if (typeof plugin.extensions === "string") {
  78150. var extension = plugin.extensions;
  78151. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  78152. plugin: plugin,
  78153. isBinary: false
  78154. };
  78155. }
  78156. else {
  78157. var extensions = plugin.extensions;
  78158. Object.keys(extensions).forEach(function (extension) {
  78159. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  78160. plugin: plugin,
  78161. isBinary: extensions[extension].isBinary
  78162. };
  78163. });
  78164. }
  78165. };
  78166. /**
  78167. * Import meshes into a scene
  78168. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  78169. * @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)
  78170. * @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)
  78171. * @param scene the instance of BABYLON.Scene to append to
  78172. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  78173. * @param onProgress a callback with a progress event for each file being loaded
  78174. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  78175. * @param pluginExtension the extension used to determine the plugin
  78176. * @returns The loaded plugin
  78177. */
  78178. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  78179. if (sceneFilename === void 0) { sceneFilename = ""; }
  78180. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  78181. if (onSuccess === void 0) { onSuccess = null; }
  78182. if (onProgress === void 0) { onProgress = null; }
  78183. if (onError === void 0) { onError = null; }
  78184. if (pluginExtension === void 0) { pluginExtension = null; }
  78185. if (!scene) {
  78186. BABYLON.Tools.Error("No scene available to import mesh to");
  78187. return null;
  78188. }
  78189. var fileInfo = SceneLoader._getFileInfo(rootUrl, sceneFilename);
  78190. if (!fileInfo) {
  78191. return null;
  78192. }
  78193. var loadingToken = {};
  78194. scene._addPendingData(loadingToken);
  78195. var disposeHandler = function () {
  78196. scene._removePendingData(loadingToken);
  78197. };
  78198. var errorHandler = function (message, exception) {
  78199. var errorMessage = "Unable to import meshes from " + fileInfo.url + ": " + message;
  78200. if (onError) {
  78201. onError(scene, errorMessage, exception);
  78202. }
  78203. else {
  78204. BABYLON.Tools.Error(errorMessage);
  78205. // should the exception be thrown?
  78206. }
  78207. disposeHandler();
  78208. };
  78209. var progressHandler = onProgress ? function (event) {
  78210. try {
  78211. onProgress(event);
  78212. }
  78213. catch (e) {
  78214. errorHandler("Error in onProgress callback", e);
  78215. }
  78216. } : undefined;
  78217. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  78218. scene.importedMeshesFiles.push(fileInfo.url);
  78219. if (onSuccess) {
  78220. try {
  78221. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  78222. }
  78223. catch (e) {
  78224. errorHandler("Error in onSuccess callback", e);
  78225. }
  78226. }
  78227. scene._removePendingData(loadingToken);
  78228. };
  78229. return SceneLoader._loadData(fileInfo, scene, function (plugin, data, responseURL) {
  78230. if (plugin.rewriteRootURL) {
  78231. fileInfo.rootUrl = plugin.rewriteRootURL(fileInfo.rootUrl, responseURL);
  78232. }
  78233. if (plugin.importMesh) {
  78234. var syncedPlugin = plugin;
  78235. var meshes = new Array();
  78236. var particleSystems = new Array();
  78237. var skeletons = new Array();
  78238. if (!syncedPlugin.importMesh(meshNames, scene, data, fileInfo.rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  78239. return;
  78240. }
  78241. scene.loadingPluginName = plugin.name;
  78242. successHandler(meshes, particleSystems, skeletons, []);
  78243. }
  78244. else {
  78245. var asyncedPlugin = plugin;
  78246. asyncedPlugin.importMeshAsync(meshNames, scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then(function (result) {
  78247. scene.loadingPluginName = plugin.name;
  78248. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  78249. }).catch(function (error) {
  78250. errorHandler(error.message, error);
  78251. });
  78252. }
  78253. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  78254. };
  78255. /**
  78256. * Import meshes into a scene
  78257. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  78258. * @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)
  78259. * @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)
  78260. * @param scene the instance of BABYLON.Scene to append to
  78261. * @param onProgress a callback with a progress event for each file being loaded
  78262. * @param pluginExtension the extension used to determine the plugin
  78263. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  78264. */
  78265. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  78266. if (sceneFilename === void 0) { sceneFilename = ""; }
  78267. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  78268. if (onProgress === void 0) { onProgress = null; }
  78269. if (pluginExtension === void 0) { pluginExtension = null; }
  78270. return new Promise(function (resolve, reject) {
  78271. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  78272. resolve({
  78273. meshes: meshes,
  78274. particleSystems: particleSystems,
  78275. skeletons: skeletons,
  78276. animationGroups: animationGroups
  78277. });
  78278. }, onProgress, function (scene, message, exception) {
  78279. reject(exception || new Error(message));
  78280. }, pluginExtension);
  78281. });
  78282. };
  78283. /**
  78284. * Load a scene
  78285. * @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)
  78286. * @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)
  78287. * @param engine is the instance of BABYLON.Engine to use to create the scene
  78288. * @param onSuccess a callback with the scene when import succeeds
  78289. * @param onProgress a callback with a progress event for each file being loaded
  78290. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  78291. * @param pluginExtension the extension used to determine the plugin
  78292. * @returns The loaded plugin
  78293. */
  78294. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  78295. if (onSuccess === void 0) { onSuccess = null; }
  78296. if (onProgress === void 0) { onProgress = null; }
  78297. if (onError === void 0) { onError = null; }
  78298. if (pluginExtension === void 0) { pluginExtension = null; }
  78299. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  78300. };
  78301. /**
  78302. * Load a scene
  78303. * @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)
  78304. * @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)
  78305. * @param engine is the instance of BABYLON.Engine to use to create the scene
  78306. * @param onProgress a callback with a progress event for each file being loaded
  78307. * @param pluginExtension the extension used to determine the plugin
  78308. * @returns The loaded scene
  78309. */
  78310. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  78311. if (onProgress === void 0) { onProgress = null; }
  78312. if (pluginExtension === void 0) { pluginExtension = null; }
  78313. return new Promise(function (resolve, reject) {
  78314. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  78315. resolve(scene);
  78316. }, onProgress, function (scene, message, exception) {
  78317. reject(exception || new Error(message));
  78318. }, pluginExtension);
  78319. });
  78320. };
  78321. /**
  78322. * Append a scene
  78323. * @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)
  78324. * @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)
  78325. * @param scene is the instance of BABYLON.Scene to append to
  78326. * @param onSuccess a callback with the scene when import succeeds
  78327. * @param onProgress a callback with a progress event for each file being loaded
  78328. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  78329. * @param pluginExtension the extension used to determine the plugin
  78330. * @returns The loaded plugin
  78331. */
  78332. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  78333. if (sceneFilename === void 0) { sceneFilename = ""; }
  78334. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  78335. if (onSuccess === void 0) { onSuccess = null; }
  78336. if (onProgress === void 0) { onProgress = null; }
  78337. if (onError === void 0) { onError = null; }
  78338. if (pluginExtension === void 0) { pluginExtension = null; }
  78339. if (!scene) {
  78340. BABYLON.Tools.Error("No scene available to append to");
  78341. return null;
  78342. }
  78343. var fileInfo = SceneLoader._getFileInfo(rootUrl, sceneFilename);
  78344. if (!fileInfo) {
  78345. return null;
  78346. }
  78347. if (SceneLoader.ShowLoadingScreen) {
  78348. scene.getEngine().displayLoadingUI();
  78349. }
  78350. var loadingToken = {};
  78351. scene._addPendingData(loadingToken);
  78352. var disposeHandler = function () {
  78353. scene._removePendingData(loadingToken);
  78354. scene.getEngine().hideLoadingUI();
  78355. };
  78356. var errorHandler = function (message, exception) {
  78357. var errorMessage = "Unable to load from " + fileInfo.url + (message ? ": " + message : "");
  78358. if (onError) {
  78359. onError(scene, errorMessage, exception);
  78360. }
  78361. else {
  78362. BABYLON.Tools.Error(errorMessage);
  78363. // should the exception be thrown?
  78364. }
  78365. disposeHandler();
  78366. };
  78367. var progressHandler = onProgress ? function (event) {
  78368. try {
  78369. onProgress(event);
  78370. }
  78371. catch (e) {
  78372. errorHandler("Error in onProgress callback", e);
  78373. }
  78374. } : undefined;
  78375. var successHandler = function () {
  78376. if (onSuccess) {
  78377. try {
  78378. onSuccess(scene);
  78379. }
  78380. catch (e) {
  78381. errorHandler("Error in onSuccess callback", e);
  78382. }
  78383. }
  78384. scene._removePendingData(loadingToken);
  78385. };
  78386. return SceneLoader._loadData(fileInfo, scene, function (plugin, data, responseURL) {
  78387. if (plugin.load) {
  78388. var syncedPlugin = plugin;
  78389. if (!syncedPlugin.load(scene, data, fileInfo.rootUrl, errorHandler)) {
  78390. return;
  78391. }
  78392. scene.loadingPluginName = plugin.name;
  78393. successHandler();
  78394. }
  78395. else {
  78396. var asyncedPlugin = plugin;
  78397. asyncedPlugin.loadAsync(scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then(function () {
  78398. scene.loadingPluginName = plugin.name;
  78399. successHandler();
  78400. }).catch(function (error) {
  78401. errorHandler(error.message, error);
  78402. });
  78403. }
  78404. if (SceneLoader.ShowLoadingScreen) {
  78405. scene.executeWhenReady(function () {
  78406. scene.getEngine().hideLoadingUI();
  78407. });
  78408. }
  78409. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  78410. };
  78411. /**
  78412. * Append a scene
  78413. * @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)
  78414. * @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)
  78415. * @param scene is the instance of BABYLON.Scene to append to
  78416. * @param onProgress a callback with a progress event for each file being loaded
  78417. * @param pluginExtension the extension used to determine the plugin
  78418. * @returns The given scene
  78419. */
  78420. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  78421. if (sceneFilename === void 0) { sceneFilename = ""; }
  78422. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  78423. if (onProgress === void 0) { onProgress = null; }
  78424. if (pluginExtension === void 0) { pluginExtension = null; }
  78425. return new Promise(function (resolve, reject) {
  78426. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  78427. resolve(scene);
  78428. }, onProgress, function (scene, message, exception) {
  78429. reject(exception || new Error(message));
  78430. }, pluginExtension);
  78431. });
  78432. };
  78433. /**
  78434. * Load a scene into an asset container
  78435. * @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)
  78436. * @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)
  78437. * @param scene is the instance of BABYLON.Scene to append to (default: last created scene)
  78438. * @param onSuccess a callback with the scene when import succeeds
  78439. * @param onProgress a callback with a progress event for each file being loaded
  78440. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  78441. * @param pluginExtension the extension used to determine the plugin
  78442. * @returns The loaded plugin
  78443. */
  78444. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  78445. if (sceneFilename === void 0) { sceneFilename = ""; }
  78446. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  78447. if (onSuccess === void 0) { onSuccess = null; }
  78448. if (onProgress === void 0) { onProgress = null; }
  78449. if (onError === void 0) { onError = null; }
  78450. if (pluginExtension === void 0) { pluginExtension = null; }
  78451. if (!scene) {
  78452. BABYLON.Tools.Error("No scene available to load asset container to");
  78453. return null;
  78454. }
  78455. var fileInfo = SceneLoader._getFileInfo(rootUrl, sceneFilename);
  78456. if (!fileInfo) {
  78457. return null;
  78458. }
  78459. var loadingToken = {};
  78460. scene._addPendingData(loadingToken);
  78461. var disposeHandler = function () {
  78462. scene._removePendingData(loadingToken);
  78463. };
  78464. var errorHandler = function (message, exception) {
  78465. var errorMessage = "Unable to load assets from " + fileInfo.url + (message ? ": " + message : "");
  78466. if (onError) {
  78467. onError(scene, errorMessage, exception);
  78468. }
  78469. else {
  78470. BABYLON.Tools.Error(errorMessage);
  78471. // should the exception be thrown?
  78472. }
  78473. disposeHandler();
  78474. };
  78475. var progressHandler = onProgress ? function (event) {
  78476. try {
  78477. onProgress(event);
  78478. }
  78479. catch (e) {
  78480. errorHandler("Error in onProgress callback", e);
  78481. }
  78482. } : undefined;
  78483. var successHandler = function (assets) {
  78484. if (onSuccess) {
  78485. try {
  78486. onSuccess(assets);
  78487. }
  78488. catch (e) {
  78489. errorHandler("Error in onSuccess callback", e);
  78490. }
  78491. }
  78492. scene._removePendingData(loadingToken);
  78493. };
  78494. return SceneLoader._loadData(fileInfo, scene, function (plugin, data, responseURL) {
  78495. if (plugin.loadAssetContainer) {
  78496. var syncedPlugin = plugin;
  78497. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, fileInfo.rootUrl, errorHandler);
  78498. if (!assetContainer) {
  78499. return;
  78500. }
  78501. scene.loadingPluginName = plugin.name;
  78502. successHandler(assetContainer);
  78503. }
  78504. else if (plugin.loadAssetContainerAsync) {
  78505. var asyncedPlugin = plugin;
  78506. asyncedPlugin.loadAssetContainerAsync(scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then(function (assetContainer) {
  78507. scene.loadingPluginName = plugin.name;
  78508. successHandler(assetContainer);
  78509. }).catch(function (error) {
  78510. errorHandler(error.message, error);
  78511. });
  78512. }
  78513. else {
  78514. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  78515. }
  78516. if (SceneLoader.ShowLoadingScreen) {
  78517. scene.executeWhenReady(function () {
  78518. scene.getEngine().hideLoadingUI();
  78519. });
  78520. }
  78521. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  78522. };
  78523. /**
  78524. * Load a scene into an asset container
  78525. * @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)
  78526. * @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)
  78527. * @param scene is the instance of BABYLON.Scene to append to
  78528. * @param onProgress a callback with a progress event for each file being loaded
  78529. * @param pluginExtension the extension used to determine the plugin
  78530. * @returns The loaded asset container
  78531. */
  78532. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  78533. if (sceneFilename === void 0) { sceneFilename = ""; }
  78534. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  78535. if (onProgress === void 0) { onProgress = null; }
  78536. if (pluginExtension === void 0) { pluginExtension = null; }
  78537. return new Promise(function (resolve, reject) {
  78538. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  78539. resolve(assetContainer);
  78540. }, onProgress, function (scene, message, exception) {
  78541. reject(exception || new Error(message));
  78542. }, pluginExtension);
  78543. });
  78544. };
  78545. // Flags
  78546. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  78547. SceneLoader._ShowLoadingScreen = true;
  78548. SceneLoader._CleanBoneMatrixWeights = false;
  78549. /**
  78550. * No logging while loading
  78551. */
  78552. SceneLoader.NO_LOGGING = 0;
  78553. /**
  78554. * Minimal logging while loading
  78555. */
  78556. SceneLoader.MINIMAL_LOGGING = 1;
  78557. /**
  78558. * Summary logging while loading
  78559. */
  78560. SceneLoader.SUMMARY_LOGGING = 2;
  78561. /**
  78562. * Detailled logging while loading
  78563. */
  78564. SceneLoader.DETAILED_LOGGING = 3;
  78565. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  78566. // Members
  78567. /**
  78568. * Event raised when a plugin is used to load a scene
  78569. */
  78570. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  78571. SceneLoader._registeredPlugins = {};
  78572. return SceneLoader;
  78573. }());
  78574. BABYLON.SceneLoader = SceneLoader;
  78575. })(BABYLON || (BABYLON = {}));
  78576. //# sourceMappingURL=babylon.sceneLoader.js.map
  78577. var BABYLON;
  78578. (function (BABYLON) {
  78579. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  78580. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  78581. var parsedMaterial = parsedData.materials[index];
  78582. if (parsedMaterial.id === id) {
  78583. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  78584. }
  78585. }
  78586. return null;
  78587. };
  78588. var isDescendantOf = function (mesh, names, hierarchyIds) {
  78589. for (var i in names) {
  78590. if (mesh.name === names[i]) {
  78591. hierarchyIds.push(mesh.id);
  78592. return true;
  78593. }
  78594. }
  78595. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  78596. hierarchyIds.push(mesh.id);
  78597. return true;
  78598. }
  78599. return false;
  78600. };
  78601. var logOperation = function (operation, producer) {
  78602. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  78603. };
  78604. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  78605. if (addToScene === void 0) { addToScene = false; }
  78606. var container = new BABYLON.AssetContainer(scene);
  78607. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  78608. // when SceneLoader.debugLogging = true (default), or exception encountered.
  78609. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  78610. // and avoid problems with multiple concurrent .babylon loads.
  78611. var log = "importScene has failed JSON parse";
  78612. try {
  78613. var parsedData = JSON.parse(data);
  78614. log = "";
  78615. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  78616. var index;
  78617. var cache;
  78618. // Lights
  78619. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  78620. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  78621. var parsedLight = parsedData.lights[index];
  78622. var light = BABYLON.Light.Parse(parsedLight, scene);
  78623. if (light) {
  78624. container.lights.push(light);
  78625. log += (index === 0 ? "\n\tLights:" : "");
  78626. log += "\n\t\t" + light.toString(fullDetails);
  78627. }
  78628. }
  78629. }
  78630. // Animations
  78631. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  78632. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  78633. var parsedAnimation = parsedData.animations[index];
  78634. var animation = BABYLON.Animation.Parse(parsedAnimation);
  78635. scene.animations.push(animation);
  78636. container.animations.push(animation);
  78637. log += (index === 0 ? "\n\tAnimations:" : "");
  78638. log += "\n\t\t" + animation.toString(fullDetails);
  78639. }
  78640. }
  78641. // Materials
  78642. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  78643. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  78644. var parsedMaterial = parsedData.materials[index];
  78645. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  78646. container.materials.push(mat);
  78647. log += (index === 0 ? "\n\tMaterials:" : "");
  78648. log += "\n\t\t" + mat.toString(fullDetails);
  78649. }
  78650. }
  78651. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  78652. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  78653. var parsedMultiMaterial = parsedData.multiMaterials[index];
  78654. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  78655. container.multiMaterials.push(mmat);
  78656. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  78657. log += "\n\t\t" + mmat.toString(fullDetails);
  78658. }
  78659. }
  78660. // Morph targets
  78661. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  78662. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  78663. var managerData = _a[_i];
  78664. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  78665. }
  78666. }
  78667. // Skeletons
  78668. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  78669. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  78670. var parsedSkeleton = parsedData.skeletons[index];
  78671. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  78672. container.skeletons.push(skeleton);
  78673. log += (index === 0 ? "\n\tSkeletons:" : "");
  78674. log += "\n\t\t" + skeleton.toString(fullDetails);
  78675. }
  78676. }
  78677. // Geometries
  78678. var geometries = parsedData.geometries;
  78679. if (geometries !== undefined && geometries !== null) {
  78680. var addedGeometry = new Array();
  78681. // Boxes
  78682. var boxes = geometries.boxes;
  78683. if (boxes !== undefined && boxes !== null) {
  78684. for (index = 0, cache = boxes.length; index < cache; index++) {
  78685. var parsedBox = boxes[index];
  78686. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  78687. }
  78688. }
  78689. // Spheres
  78690. var spheres = geometries.spheres;
  78691. if (spheres !== undefined && spheres !== null) {
  78692. for (index = 0, cache = spheres.length; index < cache; index++) {
  78693. var parsedSphere = spheres[index];
  78694. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  78695. }
  78696. }
  78697. // Cylinders
  78698. var cylinders = geometries.cylinders;
  78699. if (cylinders !== undefined && cylinders !== null) {
  78700. for (index = 0, cache = cylinders.length; index < cache; index++) {
  78701. var parsedCylinder = cylinders[index];
  78702. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  78703. }
  78704. }
  78705. // Toruses
  78706. var toruses = geometries.toruses;
  78707. if (toruses !== undefined && toruses !== null) {
  78708. for (index = 0, cache = toruses.length; index < cache; index++) {
  78709. var parsedTorus = toruses[index];
  78710. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  78711. }
  78712. }
  78713. // Grounds
  78714. var grounds = geometries.grounds;
  78715. if (grounds !== undefined && grounds !== null) {
  78716. for (index = 0, cache = grounds.length; index < cache; index++) {
  78717. var parsedGround = grounds[index];
  78718. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  78719. }
  78720. }
  78721. // Planes
  78722. var planes = geometries.planes;
  78723. if (planes !== undefined && planes !== null) {
  78724. for (index = 0, cache = planes.length; index < cache; index++) {
  78725. var parsedPlane = planes[index];
  78726. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  78727. }
  78728. }
  78729. // TorusKnots
  78730. var torusKnots = geometries.torusKnots;
  78731. if (torusKnots !== undefined && torusKnots !== null) {
  78732. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  78733. var parsedTorusKnot = torusKnots[index];
  78734. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  78735. }
  78736. }
  78737. // VertexData
  78738. var vertexData = geometries.vertexData;
  78739. if (vertexData !== undefined && vertexData !== null) {
  78740. for (index = 0, cache = vertexData.length; index < cache; index++) {
  78741. var parsedVertexData = vertexData[index];
  78742. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  78743. }
  78744. }
  78745. addedGeometry.forEach(function (g) {
  78746. if (g) {
  78747. container.geometries.push(g);
  78748. }
  78749. });
  78750. }
  78751. // Transform nodes
  78752. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  78753. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  78754. var parsedTransformNode = parsedData.transformNodes[index];
  78755. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  78756. container.transformNodes.push(node);
  78757. }
  78758. }
  78759. // Meshes
  78760. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  78761. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  78762. var parsedMesh = parsedData.meshes[index];
  78763. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  78764. container.meshes.push(mesh);
  78765. log += (index === 0 ? "\n\tMeshes:" : "");
  78766. log += "\n\t\t" + mesh.toString(fullDetails);
  78767. }
  78768. }
  78769. // Cameras
  78770. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  78771. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  78772. var parsedCamera = parsedData.cameras[index];
  78773. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  78774. container.cameras.push(camera);
  78775. log += (index === 0 ? "\n\tCameras:" : "");
  78776. log += "\n\t\t" + camera.toString(fullDetails);
  78777. }
  78778. }
  78779. // Animation Groups
  78780. if (parsedData.animationGroups !== undefined && parsedData.animationGroups !== null) {
  78781. for (index = 0, cache = parsedData.animationGroups.length; index < cache; index++) {
  78782. var parsedAnimationGroup = parsedData.animationGroups[index];
  78783. var animationGroup = BABYLON.AnimationGroup.Parse(parsedAnimationGroup, scene);
  78784. container.animationGroups.push(animationGroup);
  78785. log += (index === 0 ? "\n\tAnimationGroups:" : "");
  78786. log += "\n\t\t" + animationGroup.toString(fullDetails);
  78787. }
  78788. }
  78789. // Browsing all the graph to connect the dots
  78790. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  78791. var camera = scene.cameras[index];
  78792. if (camera._waitingParentId) {
  78793. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  78794. camera._waitingParentId = null;
  78795. }
  78796. }
  78797. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  78798. var light_1 = scene.lights[index];
  78799. if (light_1 && light_1._waitingParentId) {
  78800. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  78801. light_1._waitingParentId = null;
  78802. }
  78803. }
  78804. // Connect parents & children and parse actions
  78805. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  78806. var transformNode = scene.transformNodes[index];
  78807. if (transformNode._waitingParentId) {
  78808. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  78809. transformNode._waitingParentId = null;
  78810. }
  78811. }
  78812. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  78813. var mesh = scene.meshes[index];
  78814. if (mesh._waitingParentId) {
  78815. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  78816. mesh._waitingParentId = null;
  78817. }
  78818. }
  78819. // freeze world matrix application
  78820. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  78821. var currentMesh = scene.meshes[index];
  78822. if (currentMesh._waitingFreezeWorldMatrix) {
  78823. currentMesh.freezeWorldMatrix();
  78824. currentMesh._waitingFreezeWorldMatrix = null;
  78825. }
  78826. else {
  78827. currentMesh.computeWorldMatrix(true);
  78828. }
  78829. }
  78830. // Lights exclusions / inclusions
  78831. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  78832. var light_2 = scene.lights[index];
  78833. // Excluded check
  78834. if (light_2._excludedMeshesIds.length > 0) {
  78835. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  78836. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  78837. if (excludedMesh) {
  78838. light_2.excludedMeshes.push(excludedMesh);
  78839. }
  78840. }
  78841. light_2._excludedMeshesIds = [];
  78842. }
  78843. // Included check
  78844. if (light_2._includedOnlyMeshesIds.length > 0) {
  78845. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  78846. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  78847. if (includedOnlyMesh) {
  78848. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  78849. }
  78850. }
  78851. light_2._includedOnlyMeshesIds = [];
  78852. }
  78853. }
  78854. BABYLON.AbstractScene.Parse(parsedData, scene, container, rootUrl);
  78855. // Actions (scene) Done last as it can access other objects.
  78856. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  78857. var mesh = scene.meshes[index];
  78858. if (mesh._waitingActions) {
  78859. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  78860. mesh._waitingActions = null;
  78861. }
  78862. }
  78863. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  78864. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  78865. }
  78866. if (!addToScene) {
  78867. container.removeAllFromScene();
  78868. }
  78869. }
  78870. catch (err) {
  78871. var msg = logOperation("loadAssets", parsedData ? parsedData.producer : "Unknown") + log;
  78872. if (onError) {
  78873. onError(msg, err);
  78874. }
  78875. else {
  78876. BABYLON.Tools.Log(msg);
  78877. throw err;
  78878. }
  78879. }
  78880. finally {
  78881. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  78882. BABYLON.Tools.Log(logOperation("loadAssets", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  78883. }
  78884. }
  78885. return container;
  78886. };
  78887. BABYLON.SceneLoader.RegisterPlugin({
  78888. name: "babylon.js",
  78889. extensions: ".babylon",
  78890. canDirectLoad: function (data) {
  78891. if (data.indexOf("babylon") !== -1) { // We consider that the producer string is filled
  78892. return true;
  78893. }
  78894. return false;
  78895. },
  78896. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  78897. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  78898. // when SceneLoader.debugLogging = true (default), or exception encountered.
  78899. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  78900. // and avoid problems with multiple concurrent .babylon loads.
  78901. var log = "importMesh has failed JSON parse";
  78902. try {
  78903. var parsedData = JSON.parse(data);
  78904. log = "";
  78905. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  78906. if (!meshesNames) {
  78907. meshesNames = null;
  78908. }
  78909. else if (!Array.isArray(meshesNames)) {
  78910. meshesNames = [meshesNames];
  78911. }
  78912. var hierarchyIds = new Array();
  78913. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  78914. var loadedSkeletonsIds = [];
  78915. var loadedMaterialsIds = [];
  78916. var index;
  78917. var cache;
  78918. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  78919. var parsedMesh = parsedData.meshes[index];
  78920. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  78921. if (meshesNames !== null) {
  78922. // Remove found mesh name from list.
  78923. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  78924. }
  78925. //Geometry?
  78926. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  78927. //does the file contain geometries?
  78928. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  78929. //find the correct geometry and add it to the scene
  78930. var found = false;
  78931. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  78932. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  78933. return;
  78934. }
  78935. else {
  78936. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  78937. if (parsedGeometryData.id === parsedMesh.geometryId) {
  78938. switch (geometryType) {
  78939. case "boxes":
  78940. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  78941. break;
  78942. case "spheres":
  78943. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  78944. break;
  78945. case "cylinders":
  78946. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  78947. break;
  78948. case "toruses":
  78949. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  78950. break;
  78951. case "grounds":
  78952. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  78953. break;
  78954. case "planes":
  78955. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  78956. break;
  78957. case "torusKnots":
  78958. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  78959. break;
  78960. case "vertexData":
  78961. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  78962. break;
  78963. }
  78964. found = true;
  78965. }
  78966. });
  78967. }
  78968. });
  78969. if (found === false) {
  78970. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  78971. }
  78972. }
  78973. }
  78974. // Material ?
  78975. if (parsedMesh.materialId) {
  78976. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  78977. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  78978. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  78979. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  78980. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  78981. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  78982. var subMatId = parsedMultiMaterial.materials[matIndex];
  78983. loadedMaterialsIds.push(subMatId);
  78984. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  78985. if (mat) {
  78986. log += "\n\tMaterial " + mat.toString(fullDetails);
  78987. }
  78988. }
  78989. loadedMaterialsIds.push(parsedMultiMaterial.id);
  78990. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  78991. if (mmat) {
  78992. materialFound = true;
  78993. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  78994. }
  78995. break;
  78996. }
  78997. }
  78998. }
  78999. if (materialFound === false) {
  79000. loadedMaterialsIds.push(parsedMesh.materialId);
  79001. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  79002. if (!mat) {
  79003. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  79004. }
  79005. else {
  79006. log += "\n\tMaterial " + mat.toString(fullDetails);
  79007. }
  79008. }
  79009. }
  79010. // Skeleton ?
  79011. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  79012. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  79013. if (skeletonAlreadyLoaded === false) {
  79014. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  79015. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  79016. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  79017. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  79018. skeletons.push(skeleton);
  79019. loadedSkeletonsIds.push(parsedSkeleton.id);
  79020. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  79021. }
  79022. }
  79023. }
  79024. }
  79025. // Morph targets ?
  79026. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  79027. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  79028. var managerData = _a[_i];
  79029. BABYLON.MorphTargetManager.Parse(managerData, scene);
  79030. }
  79031. }
  79032. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  79033. meshes.push(mesh);
  79034. log += "\n\tMesh " + mesh.toString(fullDetails);
  79035. }
  79036. }
  79037. // Connecting parents
  79038. var currentMesh;
  79039. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  79040. currentMesh = scene.meshes[index];
  79041. if (currentMesh._waitingParentId) {
  79042. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  79043. currentMesh._waitingParentId = null;
  79044. }
  79045. }
  79046. // freeze and compute world matrix application
  79047. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  79048. currentMesh = scene.meshes[index];
  79049. if (currentMesh._waitingFreezeWorldMatrix) {
  79050. currentMesh.freezeWorldMatrix();
  79051. currentMesh._waitingFreezeWorldMatrix = null;
  79052. }
  79053. else {
  79054. currentMesh.computeWorldMatrix(true);
  79055. }
  79056. }
  79057. }
  79058. // Particles
  79059. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  79060. var parser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);
  79061. if (parser) {
  79062. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  79063. var parsedParticleSystem = parsedData.particleSystems[index];
  79064. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  79065. particleSystems.push(parser(parsedParticleSystem, scene, rootUrl));
  79066. }
  79067. }
  79068. }
  79069. }
  79070. return true;
  79071. }
  79072. catch (err) {
  79073. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  79074. if (onError) {
  79075. onError(msg, err);
  79076. }
  79077. else {
  79078. BABYLON.Tools.Log(msg);
  79079. throw err;
  79080. }
  79081. }
  79082. finally {
  79083. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  79084. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  79085. }
  79086. }
  79087. return false;
  79088. },
  79089. load: function (scene, data, rootUrl, onError) {
  79090. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  79091. // when SceneLoader.debugLogging = true (default), or exception encountered.
  79092. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  79093. // and avoid problems with multiple concurrent .babylon loads.
  79094. var log = "importScene has failed JSON parse";
  79095. try {
  79096. var parsedData = JSON.parse(data);
  79097. log = "";
  79098. // Scene
  79099. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  79100. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  79101. }
  79102. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  79103. scene.autoClear = parsedData.autoClear;
  79104. }
  79105. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  79106. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  79107. }
  79108. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  79109. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  79110. }
  79111. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  79112. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  79113. }
  79114. // Fog
  79115. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  79116. scene.fogMode = parsedData.fogMode;
  79117. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  79118. scene.fogStart = parsedData.fogStart;
  79119. scene.fogEnd = parsedData.fogEnd;
  79120. scene.fogDensity = parsedData.fogDensity;
  79121. log += "\tFog mode for scene: ";
  79122. switch (scene.fogMode) {
  79123. // getters not compiling, so using hardcoded
  79124. case 1:
  79125. log += "exp\n";
  79126. break;
  79127. case 2:
  79128. log += "exp2\n";
  79129. break;
  79130. case 3:
  79131. log += "linear\n";
  79132. break;
  79133. }
  79134. }
  79135. //Physics
  79136. if (parsedData.physicsEnabled) {
  79137. var physicsPlugin;
  79138. if (parsedData.physicsEngine === "cannon") {
  79139. physicsPlugin = new BABYLON.CannonJSPlugin();
  79140. }
  79141. else if (parsedData.physicsEngine === "oimo") {
  79142. physicsPlugin = new BABYLON.OimoJSPlugin();
  79143. }
  79144. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  79145. //else - default engine, which is currently oimo
  79146. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  79147. scene.enablePhysics(physicsGravity, physicsPlugin);
  79148. }
  79149. // Metadata
  79150. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  79151. scene.metadata = parsedData.metadata;
  79152. }
  79153. //collisions, if defined. otherwise, default is true
  79154. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  79155. scene.collisionsEnabled = parsedData.collisionsEnabled;
  79156. }
  79157. scene.workerCollisions = !!parsedData.workerCollisions;
  79158. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  79159. if (!container) {
  79160. return false;
  79161. }
  79162. if (parsedData.autoAnimate) {
  79163. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  79164. }
  79165. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  79166. scene.setActiveCameraByID(parsedData.activeCameraID);
  79167. }
  79168. // Environment texture
  79169. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  79170. if (parsedData.environmentTextureType && parsedData.environmentTextureType === "BABYLON.HDRCubeTexture") {
  79171. var hdrSize = (parsedData.environmentTextureSize) ? parsedData.environmentTextureSize : 128;
  79172. var hdrTexture = new BABYLON.HDRCubeTexture(rootUrl + parsedData.environmentTexture, scene, hdrSize);
  79173. if (parsedData.environmentTextureRotationY) {
  79174. hdrTexture.rotationY = parsedData.environmentTextureRotationY;
  79175. }
  79176. scene.environmentTexture = hdrTexture;
  79177. }
  79178. else {
  79179. var cubeTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  79180. if (parsedData.environmentTextureRotationY) {
  79181. cubeTexture.rotationY = parsedData.environmentTextureRotationY;
  79182. }
  79183. scene.environmentTexture = cubeTexture;
  79184. }
  79185. if (parsedData.createDefaultSkybox === true) {
  79186. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  79187. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  79188. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  79189. }
  79190. }
  79191. // Finish
  79192. return true;
  79193. }
  79194. catch (err) {
  79195. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  79196. if (onError) {
  79197. onError(msg, err);
  79198. }
  79199. else {
  79200. BABYLON.Tools.Log(msg);
  79201. throw err;
  79202. }
  79203. }
  79204. finally {
  79205. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  79206. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  79207. }
  79208. }
  79209. return false;
  79210. },
  79211. loadAssetContainer: function (scene, data, rootUrl, onError) {
  79212. var container = loadAssetContainer(scene, data, rootUrl, onError);
  79213. return container;
  79214. }
  79215. });
  79216. })(BABYLON || (BABYLON = {}));
  79217. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  79218. var BABYLON;
  79219. (function (BABYLON) {
  79220. /**
  79221. * Class used to help managing file picking and drag'n'drop
  79222. */
  79223. var FilesInput = /** @class */ (function () {
  79224. /**
  79225. * Creates a new FilesInput
  79226. * @param engine defines the rendering engine
  79227. * @param scene defines the hosting scene
  79228. * @param sceneLoadedCallback callback called when scene is loaded
  79229. * @param progressCallback callback called to track progress
  79230. * @param additionalRenderLoopLogicCallback callback called to add user logic to the rendering loop
  79231. * @param textureLoadingCallback callback called when a texture is loading
  79232. * @param startingProcessingFilesCallback callback called when the system is about to process all files
  79233. * @param onReloadCallback callback called when a reload is requested
  79234. * @param errorCallback callback call if an error occurs
  79235. */
  79236. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  79237. /**
  79238. * Callback called when a file is processed
  79239. */
  79240. this.onProcessFileCallback = function () { return true; };
  79241. this._engine = engine;
  79242. this._currentScene = scene;
  79243. this._sceneLoadedCallback = sceneLoadedCallback;
  79244. this._progressCallback = progressCallback;
  79245. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  79246. this._textureLoadingCallback = textureLoadingCallback;
  79247. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  79248. this._onReloadCallback = onReloadCallback;
  79249. this._errorCallback = errorCallback;
  79250. }
  79251. /**
  79252. * Calls this function to listen to drag'n'drop events on a specific DOM element
  79253. * @param elementToMonitor defines the DOM element to track
  79254. */
  79255. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  79256. var _this = this;
  79257. if (elementToMonitor) {
  79258. this._elementToMonitor = elementToMonitor;
  79259. this._dragEnterHandler = function (e) { _this.drag(e); };
  79260. this._dragOverHandler = function (e) { _this.drag(e); };
  79261. this._dropHandler = function (e) { _this.drop(e); };
  79262. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  79263. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  79264. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  79265. }
  79266. };
  79267. /**
  79268. * Release all associated resources
  79269. */
  79270. FilesInput.prototype.dispose = function () {
  79271. if (!this._elementToMonitor) {
  79272. return;
  79273. }
  79274. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  79275. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  79276. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  79277. };
  79278. FilesInput.prototype.renderFunction = function () {
  79279. if (this._additionalRenderLoopLogicCallback) {
  79280. this._additionalRenderLoopLogicCallback();
  79281. }
  79282. if (this._currentScene) {
  79283. if (this._textureLoadingCallback) {
  79284. var remaining = this._currentScene.getWaitingItemsCount();
  79285. if (remaining > 0) {
  79286. this._textureLoadingCallback(remaining);
  79287. }
  79288. }
  79289. this._currentScene.render();
  79290. }
  79291. };
  79292. FilesInput.prototype.drag = function (e) {
  79293. e.stopPropagation();
  79294. e.preventDefault();
  79295. };
  79296. FilesInput.prototype.drop = function (eventDrop) {
  79297. eventDrop.stopPropagation();
  79298. eventDrop.preventDefault();
  79299. this.loadFiles(eventDrop);
  79300. };
  79301. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  79302. var _this = this;
  79303. var reader = folder.createReader();
  79304. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  79305. reader.readEntries(function (entries) {
  79306. remaining.count += entries.length;
  79307. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  79308. var entry = entries_1[_i];
  79309. if (entry.isFile) {
  79310. entry.file(function (file) {
  79311. file.correctName = relativePath + file.name;
  79312. files.push(file);
  79313. if (--remaining.count === 0) {
  79314. callback();
  79315. }
  79316. });
  79317. }
  79318. else if (entry.isDirectory) {
  79319. _this._traverseFolder(entry, files, remaining, callback);
  79320. }
  79321. }
  79322. if (--remaining.count) {
  79323. callback();
  79324. }
  79325. });
  79326. };
  79327. FilesInput.prototype._processFiles = function (files) {
  79328. for (var i = 0; i < files.length; i++) {
  79329. var name = files[i].correctName.toLowerCase();
  79330. var extension = name.split('.').pop();
  79331. if (!this.onProcessFileCallback(files[i], name, extension)) {
  79332. continue;
  79333. }
  79334. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  79335. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  79336. this._sceneFileToLoad = files[i];
  79337. }
  79338. FilesInput.FilesToLoad[name] = files[i];
  79339. }
  79340. };
  79341. /**
  79342. * Load files from a drop event
  79343. * @param event defines the drop event to use as source
  79344. */
  79345. FilesInput.prototype.loadFiles = function (event) {
  79346. var _this = this;
  79347. // Handling data transfer via drag'n'drop
  79348. if (event && event.dataTransfer && event.dataTransfer.files) {
  79349. this._filesToLoad = event.dataTransfer.files;
  79350. }
  79351. // Handling files from input files
  79352. if (event && event.target && event.target.files) {
  79353. this._filesToLoad = event.target.files;
  79354. }
  79355. if (!this._filesToLoad || this._filesToLoad.length === 0) {
  79356. return;
  79357. }
  79358. if (this._startingProcessingFilesCallback) {
  79359. this._startingProcessingFilesCallback(this._filesToLoad);
  79360. }
  79361. if (this._filesToLoad && this._filesToLoad.length > 0) {
  79362. var files_1 = new Array();
  79363. var folders = [];
  79364. var items = event.dataTransfer ? event.dataTransfer.items : null;
  79365. for (var i = 0; i < this._filesToLoad.length; i++) {
  79366. var fileToLoad = this._filesToLoad[i];
  79367. var name_1 = fileToLoad.name.toLowerCase();
  79368. var entry = void 0;
  79369. fileToLoad.correctName = name_1;
  79370. if (items) {
  79371. var item = items[i];
  79372. if (item.getAsEntry) {
  79373. entry = item.getAsEntry();
  79374. }
  79375. else if (item.webkitGetAsEntry) {
  79376. entry = item.webkitGetAsEntry();
  79377. }
  79378. }
  79379. if (!entry) {
  79380. files_1.push(fileToLoad);
  79381. }
  79382. else {
  79383. if (entry.isDirectory) {
  79384. folders.push(entry);
  79385. }
  79386. else {
  79387. files_1.push(fileToLoad);
  79388. }
  79389. }
  79390. }
  79391. if (folders.length === 0) {
  79392. this._processFiles(files_1);
  79393. this._processReload();
  79394. }
  79395. else {
  79396. var remaining = { count: folders.length };
  79397. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  79398. var folder = folders_1[_i];
  79399. this._traverseFolder(folder, files_1, remaining, function () {
  79400. _this._processFiles(files_1);
  79401. if (remaining.count === 0) {
  79402. _this._processReload();
  79403. }
  79404. });
  79405. }
  79406. }
  79407. }
  79408. };
  79409. FilesInput.prototype._processReload = function () {
  79410. if (this._onReloadCallback) {
  79411. this._onReloadCallback(this._sceneFileToLoad);
  79412. }
  79413. else {
  79414. this.reload();
  79415. }
  79416. };
  79417. /**
  79418. * Reload the current scene from the loaded files
  79419. */
  79420. FilesInput.prototype.reload = function () {
  79421. var _this = this;
  79422. // If a scene file has been provided
  79423. if (this._sceneFileToLoad) {
  79424. if (this._currentScene) {
  79425. if (BABYLON.Tools.errorsCount > 0) {
  79426. BABYLON.Tools.ClearLogCache();
  79427. }
  79428. this._engine.stopRenderLoop();
  79429. }
  79430. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad.name, this._engine, function (progress) {
  79431. if (_this._progressCallback) {
  79432. _this._progressCallback(progress);
  79433. }
  79434. }).then(function (scene) {
  79435. if (_this._currentScene) {
  79436. _this._currentScene.dispose();
  79437. }
  79438. _this._currentScene = scene;
  79439. if (_this._sceneLoadedCallback) {
  79440. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  79441. }
  79442. // Wait for textures and shaders to be ready
  79443. _this._currentScene.executeWhenReady(function () {
  79444. _this._engine.runRenderLoop(function () {
  79445. _this.renderFunction();
  79446. });
  79447. });
  79448. }).catch(function (error) {
  79449. if (_this._errorCallback) {
  79450. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  79451. }
  79452. });
  79453. }
  79454. else {
  79455. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  79456. }
  79457. };
  79458. /**
  79459. * List of files ready to be loaded
  79460. */
  79461. FilesInput.FilesToLoad = {};
  79462. return FilesInput;
  79463. }());
  79464. BABYLON.FilesInput = FilesInput;
  79465. })(BABYLON || (BABYLON = {}));
  79466. //# sourceMappingURL=babylon.filesInput.js.map
  79467. var BABYLON;
  79468. (function (BABYLON) {
  79469. /**
  79470. * Class used to store custom tags
  79471. */
  79472. var Tags = /** @class */ (function () {
  79473. function Tags() {
  79474. }
  79475. /**
  79476. * Adds support for tags on the given object
  79477. * @param obj defines the object to use
  79478. */
  79479. Tags.EnableFor = function (obj) {
  79480. obj._tags = obj._tags || {};
  79481. obj.hasTags = function () {
  79482. return Tags.HasTags(obj);
  79483. };
  79484. obj.addTags = function (tagsString) {
  79485. return Tags.AddTagsTo(obj, tagsString);
  79486. };
  79487. obj.removeTags = function (tagsString) {
  79488. return Tags.RemoveTagsFrom(obj, tagsString);
  79489. };
  79490. obj.matchesTagsQuery = function (tagsQuery) {
  79491. return Tags.MatchesQuery(obj, tagsQuery);
  79492. };
  79493. };
  79494. /**
  79495. * Removes tags support
  79496. * @param obj defines the object to use
  79497. */
  79498. Tags.DisableFor = function (obj) {
  79499. delete obj._tags;
  79500. delete obj.hasTags;
  79501. delete obj.addTags;
  79502. delete obj.removeTags;
  79503. delete obj.matchesTagsQuery;
  79504. };
  79505. /**
  79506. * Gets a boolean indicating if the given object has tags
  79507. * @param obj defines the object to use
  79508. * @returns a boolean
  79509. */
  79510. Tags.HasTags = function (obj) {
  79511. if (!obj._tags) {
  79512. return false;
  79513. }
  79514. return !BABYLON.Tools.IsEmpty(obj._tags);
  79515. };
  79516. /**
  79517. * Gets the tags available on a given object
  79518. * @param obj defines the object to use
  79519. * @param asString defines if the tags must be returned as a string instead of an array of strings
  79520. * @returns the tags
  79521. */
  79522. Tags.GetTags = function (obj, asString) {
  79523. if (asString === void 0) { asString = true; }
  79524. if (!obj._tags) {
  79525. return null;
  79526. }
  79527. if (asString) {
  79528. var tagsArray = [];
  79529. for (var tag in obj._tags) {
  79530. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  79531. tagsArray.push(tag);
  79532. }
  79533. }
  79534. return tagsArray.join(" ");
  79535. }
  79536. else {
  79537. return obj._tags;
  79538. }
  79539. };
  79540. /**
  79541. * Adds tags to an object
  79542. * @param obj defines the object to use
  79543. * @param tagsString defines the tag string. The tags 'true' and 'false' are reserved and cannot be used as tags.
  79544. * A tag cannot start with '||', '&&', and '!'. It cannot contain whitespaces
  79545. */
  79546. Tags.AddTagsTo = function (obj, tagsString) {
  79547. if (!tagsString) {
  79548. return;
  79549. }
  79550. if (typeof tagsString !== "string") {
  79551. return;
  79552. }
  79553. var tags = tagsString.split(" ");
  79554. tags.forEach(function (tag, index, array) {
  79555. Tags._AddTagTo(obj, tag);
  79556. });
  79557. };
  79558. /**
  79559. * @hidden
  79560. */
  79561. Tags._AddTagTo = function (obj, tag) {
  79562. tag = tag.trim();
  79563. if (tag === "" || tag === "true" || tag === "false") {
  79564. return;
  79565. }
  79566. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  79567. return;
  79568. }
  79569. Tags.EnableFor(obj);
  79570. obj._tags[tag] = true;
  79571. };
  79572. /**
  79573. * Removes specific tags from a specific object
  79574. * @param obj defines the object to use
  79575. * @param tagsString defines the tags to remove
  79576. */
  79577. Tags.RemoveTagsFrom = function (obj, tagsString) {
  79578. if (!Tags.HasTags(obj)) {
  79579. return;
  79580. }
  79581. var tags = tagsString.split(" ");
  79582. for (var t in tags) {
  79583. Tags._RemoveTagFrom(obj, tags[t]);
  79584. }
  79585. };
  79586. /**
  79587. * @hidden
  79588. */
  79589. Tags._RemoveTagFrom = function (obj, tag) {
  79590. delete obj._tags[tag];
  79591. };
  79592. /**
  79593. * Defines if tags hosted on an object match a given query
  79594. * @param obj defines the object to use
  79595. * @param tagsQuery defines the tag query
  79596. * @returns a boolean
  79597. */
  79598. Tags.MatchesQuery = function (obj, tagsQuery) {
  79599. if (tagsQuery === undefined) {
  79600. return true;
  79601. }
  79602. if (tagsQuery === "") {
  79603. return Tags.HasTags(obj);
  79604. }
  79605. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  79606. };
  79607. return Tags;
  79608. }());
  79609. BABYLON.Tags = Tags;
  79610. })(BABYLON || (BABYLON = {}));
  79611. //# sourceMappingURL=babylon.tags.js.map
  79612. var BABYLON;
  79613. (function (BABYLON) {
  79614. /**
  79615. * Class used to evalaute queries containing `and` and `or` operators
  79616. */
  79617. var AndOrNotEvaluator = /** @class */ (function () {
  79618. function AndOrNotEvaluator() {
  79619. }
  79620. /**
  79621. * Evaluate a query
  79622. * @param query defines the query to evaluate
  79623. * @param evaluateCallback defines the callback used to filter result
  79624. * @returns true if the query matches
  79625. */
  79626. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  79627. if (!query.match(/\([^\(\)]*\)/g)) {
  79628. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  79629. }
  79630. else {
  79631. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  79632. // remove parenthesis
  79633. r = r.slice(1, r.length - 1);
  79634. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  79635. });
  79636. }
  79637. if (query === "true") {
  79638. return true;
  79639. }
  79640. if (query === "false") {
  79641. return false;
  79642. }
  79643. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  79644. };
  79645. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  79646. evaluateCallback = evaluateCallback || (function (r) {
  79647. return r === "true" ? true : false;
  79648. });
  79649. var result;
  79650. var or = parenthesisContent.split("||");
  79651. for (var i in or) {
  79652. if (or.hasOwnProperty(i)) {
  79653. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  79654. var and = ori.split("&&");
  79655. if (and.length > 1) {
  79656. for (var j = 0; j < and.length; ++j) {
  79657. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  79658. if (andj !== "true" && andj !== "false") {
  79659. if (andj[0] === "!") {
  79660. result = !evaluateCallback(andj.substring(1));
  79661. }
  79662. else {
  79663. result = evaluateCallback(andj);
  79664. }
  79665. }
  79666. else {
  79667. result = andj === "true" ? true : false;
  79668. }
  79669. if (!result) { // no need to continue since 'false && ... && ...' will always return false
  79670. ori = "false";
  79671. break;
  79672. }
  79673. }
  79674. }
  79675. if (result || ori === "true") { // no need to continue since 'true || ... || ...' will always return true
  79676. result = true;
  79677. break;
  79678. }
  79679. // result equals false (or undefined)
  79680. if (ori !== "true" && ori !== "false") {
  79681. if (ori[0] === "!") {
  79682. result = !evaluateCallback(ori.substring(1));
  79683. }
  79684. else {
  79685. result = evaluateCallback(ori);
  79686. }
  79687. }
  79688. else {
  79689. result = ori === "true" ? true : false;
  79690. }
  79691. }
  79692. }
  79693. // the whole parenthesis scope is replaced by 'true' or 'false'
  79694. return result ? "true" : "false";
  79695. };
  79696. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  79697. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  79698. // remove whitespaces
  79699. r = r.replace(/[\s]/g, function () { return ""; });
  79700. return r.length % 2 ? "!" : "";
  79701. });
  79702. booleanString = booleanString.trim();
  79703. if (booleanString === "!true") {
  79704. booleanString = "false";
  79705. }
  79706. else if (booleanString === "!false") {
  79707. booleanString = "true";
  79708. }
  79709. return booleanString;
  79710. };
  79711. return AndOrNotEvaluator;
  79712. }());
  79713. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  79714. })(BABYLON || (BABYLON = {}));
  79715. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  79716. var BABYLON;
  79717. (function (BABYLON) {
  79718. // Sets the default offline provider to Babylon.js
  79719. BABYLON.Engine.OfflineProviderFactory = function (urlToScene, callbackManifestChecked, disableManifestCheck) {
  79720. if (disableManifestCheck === void 0) { disableManifestCheck = false; }
  79721. return new Database(urlToScene, callbackManifestChecked, disableManifestCheck);
  79722. };
  79723. /**
  79724. * Class used to enable access to IndexedDB
  79725. * @see http://doc.babylonjs.com/how_to/caching_resources_in_indexeddb
  79726. */
  79727. var Database = /** @class */ (function () {
  79728. /**
  79729. * Creates a new Database
  79730. * @param urlToScene defines the url to load the scene
  79731. * @param callbackManifestChecked defines the callback to use when manifest is checked
  79732. * @param disableManifestCheck defines a boolean indicating that we want to skip the manifest validation (it will be considered validated and up to date)
  79733. */
  79734. function Database(urlToScene, callbackManifestChecked, disableManifestCheck) {
  79735. if (disableManifestCheck === void 0) { disableManifestCheck = false; }
  79736. var _this = this;
  79737. // Handling various flavors of prefixed version of IndexedDB
  79738. this._idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  79739. this._callbackManifestChecked = callbackManifestChecked;
  79740. this._currentSceneUrl = Database._ReturnFullUrlLocation(urlToScene);
  79741. this._db = null;
  79742. this._enableSceneOffline = false;
  79743. this._enableTexturesOffline = false;
  79744. this._manifestVersionFound = 0;
  79745. this._mustUpdateRessources = false;
  79746. this._hasReachedQuota = false;
  79747. if (!Database.IDBStorageEnabled) {
  79748. this._callbackManifestChecked(true);
  79749. }
  79750. else {
  79751. if (disableManifestCheck) {
  79752. this._enableSceneOffline = true;
  79753. this._enableTexturesOffline = true;
  79754. this._manifestVersionFound = 1;
  79755. BABYLON.Tools.SetImmediate(function () {
  79756. _this._callbackManifestChecked(true);
  79757. });
  79758. }
  79759. else {
  79760. this._checkManifestFile();
  79761. }
  79762. }
  79763. }
  79764. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  79765. /**
  79766. * Gets a boolean indicating if scene must be saved in the database
  79767. */
  79768. get: function () {
  79769. return this._enableSceneOffline;
  79770. },
  79771. enumerable: true,
  79772. configurable: true
  79773. });
  79774. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  79775. /**
  79776. * Gets a boolean indicating if textures must be saved in the database
  79777. */
  79778. get: function () {
  79779. return this._enableTexturesOffline;
  79780. },
  79781. enumerable: true,
  79782. configurable: true
  79783. });
  79784. Database.prototype._checkManifestFile = function () {
  79785. var _this = this;
  79786. var noManifestFile = function () {
  79787. _this._enableSceneOffline = false;
  79788. _this._enableTexturesOffline = false;
  79789. _this._callbackManifestChecked(false);
  79790. };
  79791. var timeStampUsed = false;
  79792. var manifestURL = this._currentSceneUrl + ".manifest";
  79793. var xhr = new XMLHttpRequest();
  79794. if (navigator.onLine) {
  79795. // Adding a timestamp to by-pass browsers' cache
  79796. timeStampUsed = true;
  79797. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + Date.now();
  79798. }
  79799. xhr.open("GET", manifestURL, true);
  79800. xhr.addEventListener("load", function () {
  79801. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  79802. try {
  79803. var manifestFile = JSON.parse(xhr.response);
  79804. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  79805. _this._enableTexturesOffline = manifestFile.enableTexturesOffline && Database.IsUASupportingBlobStorage;
  79806. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  79807. _this._manifestVersionFound = manifestFile.version;
  79808. }
  79809. if (_this._callbackManifestChecked) {
  79810. _this._callbackManifestChecked(true);
  79811. }
  79812. }
  79813. catch (ex) {
  79814. noManifestFile();
  79815. }
  79816. }
  79817. else {
  79818. noManifestFile();
  79819. }
  79820. }, false);
  79821. xhr.addEventListener("error", function (event) {
  79822. if (timeStampUsed) {
  79823. timeStampUsed = false;
  79824. // Let's retry without the timeStamp
  79825. // It could fail when coupled with HTML5 Offline API
  79826. var retryManifestURL = _this._currentSceneUrl + ".manifest";
  79827. xhr.open("GET", retryManifestURL, true);
  79828. xhr.send();
  79829. }
  79830. else {
  79831. noManifestFile();
  79832. }
  79833. }, false);
  79834. try {
  79835. xhr.send();
  79836. }
  79837. catch (ex) {
  79838. BABYLON.Tools.Error("Error on XHR send request.");
  79839. this._callbackManifestChecked(false);
  79840. }
  79841. };
  79842. /**
  79843. * Open the database and make it available
  79844. * @param successCallback defines the callback to call on success
  79845. * @param errorCallback defines the callback to call on error
  79846. */
  79847. Database.prototype.open = function (successCallback, errorCallback) {
  79848. var _this = this;
  79849. var handleError = function () {
  79850. _this._isSupported = false;
  79851. if (errorCallback) {
  79852. errorCallback();
  79853. }
  79854. };
  79855. if (!this._idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  79856. // Your browser doesn't support IndexedDB
  79857. this._isSupported = false;
  79858. if (errorCallback) {
  79859. errorCallback();
  79860. }
  79861. }
  79862. else {
  79863. // If the DB hasn't been opened or created yet
  79864. if (!this._db) {
  79865. this._hasReachedQuota = false;
  79866. this._isSupported = true;
  79867. var request = this._idbFactory.open("babylonjs", 1);
  79868. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  79869. request.onerror = function (event) {
  79870. handleError();
  79871. };
  79872. // executes when a version change transaction cannot complete due to other active transactions
  79873. request.onblocked = function (event) {
  79874. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  79875. handleError();
  79876. };
  79877. // DB has been opened successfully
  79878. request.onsuccess = function (event) {
  79879. _this._db = request.result;
  79880. successCallback();
  79881. };
  79882. // Initialization of the DB. Creating Scenes & Textures stores
  79883. request.onupgradeneeded = function (event) {
  79884. _this._db = (event.target).result;
  79885. if (_this._db) {
  79886. try {
  79887. _this._db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  79888. _this._db.createObjectStore("versions", { keyPath: "sceneUrl" });
  79889. _this._db.createObjectStore("textures", { keyPath: "textureUrl" });
  79890. }
  79891. catch (ex) {
  79892. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  79893. handleError();
  79894. }
  79895. }
  79896. };
  79897. }
  79898. // DB has already been created and opened
  79899. else {
  79900. if (successCallback) {
  79901. successCallback();
  79902. }
  79903. }
  79904. }
  79905. };
  79906. /**
  79907. * Loads an image from the database
  79908. * @param url defines the url to load from
  79909. * @param image defines the target DOM image
  79910. */
  79911. Database.prototype.loadImage = function (url, image) {
  79912. var _this = this;
  79913. var completeURL = Database._ReturnFullUrlLocation(url);
  79914. var saveAndLoadImage = function () {
  79915. if (!_this._hasReachedQuota && _this._db !== null) {
  79916. // the texture is not yet in the DB, let's try to save it
  79917. _this._saveImageIntoDBAsync(completeURL, image);
  79918. }
  79919. // If the texture is not in the DB and we've reached the DB quota limit
  79920. // let's load it directly from the web
  79921. else {
  79922. image.src = url;
  79923. }
  79924. };
  79925. if (!this._mustUpdateRessources) {
  79926. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  79927. }
  79928. // First time we're download the images or update requested in the manifest file by a version change
  79929. else {
  79930. saveAndLoadImage();
  79931. }
  79932. };
  79933. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  79934. if (this._isSupported && this._db !== null) {
  79935. var texture;
  79936. var transaction = this._db.transaction(["textures"]);
  79937. transaction.onabort = function (event) {
  79938. image.src = url;
  79939. };
  79940. transaction.oncomplete = function (event) {
  79941. var blobTextureURL;
  79942. if (texture) {
  79943. var URL = window.URL || window.webkitURL;
  79944. blobTextureURL = URL.createObjectURL(texture.data);
  79945. image.onerror = function () {
  79946. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  79947. image.src = url;
  79948. };
  79949. image.src = blobTextureURL;
  79950. }
  79951. else {
  79952. notInDBCallback();
  79953. }
  79954. };
  79955. var getRequest = transaction.objectStore("textures").get(url);
  79956. getRequest.onsuccess = function (event) {
  79957. texture = (event.target).result;
  79958. };
  79959. getRequest.onerror = function (event) {
  79960. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  79961. image.src = url;
  79962. };
  79963. }
  79964. else {
  79965. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  79966. image.src = url;
  79967. }
  79968. };
  79969. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  79970. var _this = this;
  79971. if (this._isSupported) {
  79972. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  79973. var generateBlobUrl = function () {
  79974. var blobTextureURL;
  79975. if (blob) {
  79976. var URL = window.URL || window.webkitURL;
  79977. try {
  79978. blobTextureURL = URL.createObjectURL(blob);
  79979. }
  79980. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  79981. catch (ex) {
  79982. blobTextureURL = URL.createObjectURL(blob);
  79983. }
  79984. }
  79985. if (blobTextureURL) {
  79986. image.src = blobTextureURL;
  79987. }
  79988. };
  79989. if (Database.IsUASupportingBlobStorage) { // Create XHR
  79990. var xhr = new XMLHttpRequest(), blob;
  79991. xhr.open("GET", url, true);
  79992. xhr.responseType = "blob";
  79993. xhr.addEventListener("load", function () {
  79994. if (xhr.status === 200 && _this._db) {
  79995. // Blob as response (XHR2)
  79996. blob = xhr.response;
  79997. var transaction = _this._db.transaction(["textures"], "readwrite");
  79998. // the transaction could abort because of a QuotaExceededError error
  79999. transaction.onabort = function (event) {
  80000. try {
  80001. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  80002. var srcElement = (event.srcElement || event.target);
  80003. var error = srcElement.error;
  80004. if (error && error.name === "QuotaExceededError") {
  80005. _this._hasReachedQuota = true;
  80006. }
  80007. }
  80008. catch (ex) { }
  80009. generateBlobUrl();
  80010. };
  80011. transaction.oncomplete = function (event) {
  80012. generateBlobUrl();
  80013. };
  80014. var newTexture = { textureUrl: url, data: blob };
  80015. try {
  80016. // Put the blob into the dabase
  80017. var addRequest = transaction.objectStore("textures").put(newTexture);
  80018. addRequest.onsuccess = function (event) {
  80019. };
  80020. addRequest.onerror = function (event) {
  80021. generateBlobUrl();
  80022. };
  80023. }
  80024. catch (ex) {
  80025. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  80026. if (ex.code === 25) {
  80027. Database.IsUASupportingBlobStorage = false;
  80028. _this._enableTexturesOffline = false;
  80029. }
  80030. image.src = url;
  80031. }
  80032. }
  80033. else {
  80034. image.src = url;
  80035. }
  80036. }, false);
  80037. xhr.addEventListener("error", function (event) {
  80038. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  80039. image.src = url;
  80040. }, false);
  80041. xhr.send();
  80042. }
  80043. else {
  80044. image.src = url;
  80045. }
  80046. }
  80047. else {
  80048. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  80049. image.src = url;
  80050. }
  80051. };
  80052. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  80053. var _this = this;
  80054. var updateVersion = function () {
  80055. // the version is not yet in the DB or we need to update it
  80056. _this._saveVersionIntoDBAsync(url, versionLoaded);
  80057. };
  80058. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  80059. };
  80060. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  80061. var _this = this;
  80062. if (this._isSupported && this._db) {
  80063. var version;
  80064. try {
  80065. var transaction = this._db.transaction(["versions"]);
  80066. transaction.oncomplete = function (event) {
  80067. if (version) {
  80068. // If the version in the JSON file is different from the version in DB
  80069. if (_this._manifestVersionFound !== version.data) {
  80070. _this._mustUpdateRessources = true;
  80071. updateInDBCallback();
  80072. }
  80073. else {
  80074. callback(version.data);
  80075. }
  80076. }
  80077. // version was not found in DB
  80078. else {
  80079. _this._mustUpdateRessources = true;
  80080. updateInDBCallback();
  80081. }
  80082. };
  80083. transaction.onabort = function (event) {
  80084. callback(-1);
  80085. };
  80086. var getRequest = transaction.objectStore("versions").get(url);
  80087. getRequest.onsuccess = function (event) {
  80088. version = (event.target).result;
  80089. };
  80090. getRequest.onerror = function (event) {
  80091. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  80092. callback(-1);
  80093. };
  80094. }
  80095. catch (ex) {
  80096. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  80097. callback(-1);
  80098. }
  80099. }
  80100. else {
  80101. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  80102. callback(-1);
  80103. }
  80104. };
  80105. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  80106. var _this = this;
  80107. if (this._isSupported && !this._hasReachedQuota && this._db) {
  80108. try {
  80109. // Open a transaction to the database
  80110. var transaction = this._db.transaction(["versions"], "readwrite");
  80111. // the transaction could abort because of a QuotaExceededError error
  80112. transaction.onabort = function (event) {
  80113. try { //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  80114. var error = event.srcElement['error'];
  80115. if (error && error.name === "QuotaExceededError") {
  80116. _this._hasReachedQuota = true;
  80117. }
  80118. }
  80119. catch (ex) { }
  80120. callback(-1);
  80121. };
  80122. transaction.oncomplete = function (event) {
  80123. callback(_this._manifestVersionFound);
  80124. };
  80125. var newVersion = { sceneUrl: url, data: this._manifestVersionFound };
  80126. // Put the scene into the database
  80127. var addRequest = transaction.objectStore("versions").put(newVersion);
  80128. addRequest.onsuccess = function (event) {
  80129. };
  80130. addRequest.onerror = function (event) {
  80131. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  80132. };
  80133. }
  80134. catch (ex) {
  80135. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  80136. callback(-1);
  80137. }
  80138. }
  80139. else {
  80140. callback(-1);
  80141. }
  80142. };
  80143. /**
  80144. * Loads a file from database
  80145. * @param url defines the URL to load from
  80146. * @param sceneLoaded defines a callback to call on success
  80147. * @param progressCallBack defines a callback to call when progress changed
  80148. * @param errorCallback defines a callback to call on error
  80149. * @param useArrayBuffer defines a boolean to use array buffer instead of text string
  80150. */
  80151. Database.prototype.loadFile = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  80152. var _this = this;
  80153. var completeUrl = Database._ReturnFullUrlLocation(url);
  80154. var saveAndLoadFile = function () {
  80155. // the scene is not yet in the DB, let's try to save it
  80156. _this._saveFileAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
  80157. };
  80158. this._checkVersionFromDB(completeUrl, function (version) {
  80159. if (version !== -1) {
  80160. if (!_this._mustUpdateRessources) {
  80161. _this._loadFileAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  80162. }
  80163. else {
  80164. _this._saveFileAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
  80165. }
  80166. }
  80167. else {
  80168. if (errorCallback) {
  80169. errorCallback();
  80170. }
  80171. }
  80172. });
  80173. };
  80174. Database.prototype._loadFileAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  80175. if (this._isSupported && this._db) {
  80176. var targetStore;
  80177. if (url.indexOf(".babylon") !== -1) {
  80178. targetStore = "scenes";
  80179. }
  80180. else {
  80181. targetStore = "textures";
  80182. }
  80183. var file;
  80184. var transaction = this._db.transaction([targetStore]);
  80185. transaction.oncomplete = function (event) {
  80186. if (file) {
  80187. callback(file.data);
  80188. }
  80189. // file was not found in DB
  80190. else {
  80191. notInDBCallback();
  80192. }
  80193. };
  80194. transaction.onabort = function (event) {
  80195. notInDBCallback();
  80196. };
  80197. var getRequest = transaction.objectStore(targetStore).get(url);
  80198. getRequest.onsuccess = function (event) {
  80199. file = (event.target).result;
  80200. };
  80201. getRequest.onerror = function (event) {
  80202. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  80203. notInDBCallback();
  80204. };
  80205. }
  80206. else {
  80207. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  80208. callback();
  80209. }
  80210. };
  80211. Database.prototype._saveFileAsync = function (url, callback, progressCallback, useArrayBuffer, errorCallback) {
  80212. var _this = this;
  80213. if (this._isSupported) {
  80214. var targetStore;
  80215. if (url.indexOf(".babylon") !== -1) {
  80216. targetStore = "scenes";
  80217. }
  80218. else {
  80219. targetStore = "textures";
  80220. }
  80221. // Create XHR
  80222. var xhr = new XMLHttpRequest();
  80223. var fileData;
  80224. xhr.open("GET", url + "?" + Date.now(), true);
  80225. if (useArrayBuffer) {
  80226. xhr.responseType = "arraybuffer";
  80227. }
  80228. if (progressCallback) {
  80229. xhr.onprogress = progressCallback;
  80230. }
  80231. xhr.addEventListener("load", function () {
  80232. if (xhr.status === 200 || (xhr.status < 400 && BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6))) {
  80233. // Blob as response (XHR2)
  80234. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  80235. if (!_this._hasReachedQuota && _this._db) {
  80236. // Open a transaction to the database
  80237. var transaction = _this._db.transaction([targetStore], "readwrite");
  80238. // the transaction could abort because of a QuotaExceededError error
  80239. transaction.onabort = function (event) {
  80240. try {
  80241. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  80242. var error = event.srcElement['error'];
  80243. if (error && error.name === "QuotaExceededError") {
  80244. _this._hasReachedQuota = true;
  80245. }
  80246. }
  80247. catch (ex) { }
  80248. callback(fileData);
  80249. };
  80250. transaction.oncomplete = function (event) {
  80251. callback(fileData);
  80252. };
  80253. var newFile;
  80254. if (targetStore === "scenes") {
  80255. newFile = { sceneUrl: url, data: fileData, version: _this._manifestVersionFound };
  80256. }
  80257. else {
  80258. newFile = { textureUrl: url, data: fileData };
  80259. }
  80260. try {
  80261. // Put the scene into the database
  80262. var addRequest = transaction.objectStore(targetStore).put(newFile);
  80263. addRequest.onsuccess = function (event) {
  80264. };
  80265. addRequest.onerror = function (event) {
  80266. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  80267. };
  80268. }
  80269. catch (ex) {
  80270. callback(fileData);
  80271. }
  80272. }
  80273. else {
  80274. callback(fileData);
  80275. }
  80276. }
  80277. else {
  80278. if (xhr.status >= 400 && errorCallback) {
  80279. errorCallback(xhr);
  80280. }
  80281. else {
  80282. callback();
  80283. }
  80284. }
  80285. }, false);
  80286. xhr.addEventListener("error", function (event) {
  80287. BABYLON.Tools.Error("error on XHR request.");
  80288. callback();
  80289. }, false);
  80290. xhr.send();
  80291. }
  80292. else {
  80293. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or Babylon.js Database is not open.");
  80294. callback();
  80295. }
  80296. };
  80297. /** Gets a boolean indicating if the user agent supports blob storage (this value will be updated after creating the first Database object) */
  80298. Database.IsUASupportingBlobStorage = true;
  80299. /**
  80300. * Gets a boolean indicating if Database storate is enabled (off by default)
  80301. */
  80302. Database.IDBStorageEnabled = false;
  80303. Database._ParseURL = function (url) {
  80304. var a = document.createElement('a');
  80305. a.href = url;
  80306. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  80307. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  80308. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  80309. return absLocation;
  80310. };
  80311. Database._ReturnFullUrlLocation = function (url) {
  80312. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  80313. return (Database._ParseURL(window.location.href) + url);
  80314. }
  80315. else {
  80316. return url;
  80317. }
  80318. };
  80319. return Database;
  80320. }());
  80321. BABYLON.Database = Database;
  80322. })(BABYLON || (BABYLON = {}));
  80323. //# sourceMappingURL=babylon.database.js.map
  80324. var BABYLON;
  80325. (function (BABYLON) {
  80326. /**
  80327. * This represents all the required information to add a fresnel effect on a material:
  80328. * @see http://doc.babylonjs.com/how_to/how_to_use_fresnelparameters
  80329. */
  80330. var FresnelParameters = /** @class */ (function () {
  80331. function FresnelParameters() {
  80332. this._isEnabled = true;
  80333. /**
  80334. * Define the color used on edges (grazing angle)
  80335. */
  80336. this.leftColor = BABYLON.Color3.White();
  80337. /**
  80338. * Define the color used on center
  80339. */
  80340. this.rightColor = BABYLON.Color3.Black();
  80341. /**
  80342. * Define bias applied to computed fresnel term
  80343. */
  80344. this.bias = 0;
  80345. /**
  80346. * Defined the power exponent applied to fresnel term
  80347. */
  80348. this.power = 1;
  80349. }
  80350. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  80351. /**
  80352. * Define if the fresnel effect is enable or not.
  80353. */
  80354. get: function () {
  80355. return this._isEnabled;
  80356. },
  80357. set: function (value) {
  80358. if (this._isEnabled === value) {
  80359. return;
  80360. }
  80361. this._isEnabled = value;
  80362. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  80363. },
  80364. enumerable: true,
  80365. configurable: true
  80366. });
  80367. /**
  80368. * Clones the current fresnel and its valuues
  80369. * @returns a clone fresnel configuration
  80370. */
  80371. FresnelParameters.prototype.clone = function () {
  80372. var newFresnelParameters = new FresnelParameters();
  80373. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  80374. return newFresnelParameters;
  80375. };
  80376. /**
  80377. * Serializes the current fresnel parameters to a JSON representation.
  80378. * @return the JSON serialization
  80379. */
  80380. FresnelParameters.prototype.serialize = function () {
  80381. var serializationObject = {};
  80382. serializationObject.isEnabled = this.isEnabled;
  80383. serializationObject.leftColor = this.leftColor.asArray();
  80384. serializationObject.rightColor = this.rightColor.asArray();
  80385. serializationObject.bias = this.bias;
  80386. serializationObject.power = this.power;
  80387. return serializationObject;
  80388. };
  80389. /**
  80390. * Parse a JSON object and deserialize it to a new Fresnel parameter object.
  80391. * @param parsedFresnelParameters Define the JSON representation
  80392. * @returns the parsed parameters
  80393. */
  80394. FresnelParameters.Parse = function (parsedFresnelParameters) {
  80395. var fresnelParameters = new FresnelParameters();
  80396. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  80397. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  80398. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  80399. fresnelParameters.bias = parsedFresnelParameters.bias;
  80400. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  80401. return fresnelParameters;
  80402. };
  80403. return FresnelParameters;
  80404. }());
  80405. BABYLON.FresnelParameters = FresnelParameters;
  80406. })(BABYLON || (BABYLON = {}));
  80407. //# sourceMappingURL=babylon.fresnelParameters.js.map
  80408. var BABYLON;
  80409. (function (BABYLON) {
  80410. /**
  80411. * A multi-material is used to apply different materials to different parts of the same object without the need of
  80412. * separate meshes. This can be use to improve performances.
  80413. * @see http://doc.babylonjs.com/how_to/multi_materials
  80414. */
  80415. var MultiMaterial = /** @class */ (function (_super) {
  80416. __extends(MultiMaterial, _super);
  80417. /**
  80418. * Instantiates a new Multi Material
  80419. * A multi-material is used to apply different materials to different parts of the same object without the need of
  80420. * separate meshes. This can be use to improve performances.
  80421. * @see http://doc.babylonjs.com/how_to/multi_materials
  80422. * @param name Define the name in the scene
  80423. * @param scene Define the scene the material belongs to
  80424. */
  80425. function MultiMaterial(name, scene) {
  80426. var _this = _super.call(this, name, scene, true) || this;
  80427. scene.multiMaterials.push(_this);
  80428. _this.subMaterials = new Array();
  80429. _this._storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  80430. return _this;
  80431. }
  80432. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  80433. /**
  80434. * Gets or Sets the list of Materials used within the multi material.
  80435. * They need to be ordered according to the submeshes order in the associated mesh
  80436. */
  80437. get: function () {
  80438. return this._subMaterials;
  80439. },
  80440. set: function (value) {
  80441. this._subMaterials = value;
  80442. this._hookArray(value);
  80443. },
  80444. enumerable: true,
  80445. configurable: true
  80446. });
  80447. /**
  80448. * Function used to align with Node.getChildren()
  80449. * @returns the list of Materials used within the multi material
  80450. */
  80451. MultiMaterial.prototype.getChildren = function () {
  80452. return this.subMaterials;
  80453. };
  80454. MultiMaterial.prototype._hookArray = function (array) {
  80455. var _this = this;
  80456. var oldPush = array.push;
  80457. array.push = function () {
  80458. var items = [];
  80459. for (var _i = 0; _i < arguments.length; _i++) {
  80460. items[_i] = arguments[_i];
  80461. }
  80462. var result = oldPush.apply(array, items);
  80463. _this._markAllSubMeshesAsTexturesDirty();
  80464. return result;
  80465. };
  80466. var oldSplice = array.splice;
  80467. array.splice = function (index, deleteCount) {
  80468. var deleted = oldSplice.apply(array, [index, deleteCount]);
  80469. _this._markAllSubMeshesAsTexturesDirty();
  80470. return deleted;
  80471. };
  80472. };
  80473. /**
  80474. * Get one of the submaterial by its index in the submaterials array
  80475. * @param index The index to look the sub material at
  80476. * @returns The Material if the index has been defined
  80477. */
  80478. MultiMaterial.prototype.getSubMaterial = function (index) {
  80479. if (index < 0 || index >= this.subMaterials.length) {
  80480. return this.getScene().defaultMaterial;
  80481. }
  80482. return this.subMaterials[index];
  80483. };
  80484. /**
  80485. * Get the list of active textures for the whole sub materials list.
  80486. * @returns All the textures that will be used during the rendering
  80487. */
  80488. MultiMaterial.prototype.getActiveTextures = function () {
  80489. var _a;
  80490. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  80491. if (subMaterial) {
  80492. return subMaterial.getActiveTextures();
  80493. }
  80494. else {
  80495. return [];
  80496. }
  80497. }));
  80498. };
  80499. /**
  80500. * Gets the current class name of the material e.g. "MultiMaterial"
  80501. * Mainly use in serialization.
  80502. * @returns the class name
  80503. */
  80504. MultiMaterial.prototype.getClassName = function () {
  80505. return "MultiMaterial";
  80506. };
  80507. /**
  80508. * Checks if the material is ready to render the requested sub mesh
  80509. * @param mesh Define the mesh the submesh belongs to
  80510. * @param subMesh Define the sub mesh to look readyness for
  80511. * @param useInstances Define whether or not the material is used with instances
  80512. * @returns true if ready, otherwise false
  80513. */
  80514. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  80515. for (var index = 0; index < this.subMaterials.length; index++) {
  80516. var subMaterial = this.subMaterials[index];
  80517. if (subMaterial) {
  80518. if (subMaterial._storeEffectOnSubMeshes) {
  80519. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  80520. return false;
  80521. }
  80522. continue;
  80523. }
  80524. if (!subMaterial.isReady(mesh)) {
  80525. return false;
  80526. }
  80527. }
  80528. }
  80529. return true;
  80530. };
  80531. /**
  80532. * Clones the current material and its related sub materials
  80533. * @param name Define the name of the newly cloned material
  80534. * @param cloneChildren Define if submaterial will be cloned or shared with the parent instance
  80535. * @returns the cloned material
  80536. */
  80537. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  80538. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  80539. for (var index = 0; index < this.subMaterials.length; index++) {
  80540. var subMaterial = null;
  80541. var current = this.subMaterials[index];
  80542. if (cloneChildren && current) {
  80543. subMaterial = current.clone(name + "-" + current.name);
  80544. }
  80545. else {
  80546. subMaterial = this.subMaterials[index];
  80547. }
  80548. newMultiMaterial.subMaterials.push(subMaterial);
  80549. }
  80550. return newMultiMaterial;
  80551. };
  80552. /**
  80553. * Serializes the materials into a JSON representation.
  80554. * @returns the JSON representation
  80555. */
  80556. MultiMaterial.prototype.serialize = function () {
  80557. var serializationObject = {};
  80558. serializationObject.name = this.name;
  80559. serializationObject.id = this.id;
  80560. if (BABYLON.Tags) {
  80561. serializationObject.tags = BABYLON.Tags.GetTags(this);
  80562. }
  80563. serializationObject.materials = [];
  80564. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  80565. var subMat = this.subMaterials[matIndex];
  80566. if (subMat) {
  80567. serializationObject.materials.push(subMat.id);
  80568. }
  80569. else {
  80570. serializationObject.materials.push(null);
  80571. }
  80572. }
  80573. return serializationObject;
  80574. };
  80575. /**
  80576. * Dispose the material and release its associated resources
  80577. * @param forceDisposeEffect Define if we want to force disposing the associated effect (if false the shader is not released and could be reuse later on)
  80578. * @param forceDisposeTextures Define if we want to force disposing the associated textures (if false, they will not be disposed and can still be use elsewhere in the app)
  80579. */
  80580. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  80581. var scene = this.getScene();
  80582. if (!scene) {
  80583. return;
  80584. }
  80585. var index = scene.multiMaterials.indexOf(this);
  80586. if (index >= 0) {
  80587. scene.multiMaterials.splice(index, 1);
  80588. }
  80589. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  80590. };
  80591. return MultiMaterial;
  80592. }(BABYLON.Material));
  80593. BABYLON.MultiMaterial = MultiMaterial;
  80594. })(BABYLON || (BABYLON = {}));
  80595. //# sourceMappingURL=babylon.multiMaterial.js.map
  80596. var BABYLON;
  80597. (function (BABYLON) {
  80598. /**
  80599. * Manage the touch inputs to control the movement of a free camera.
  80600. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  80601. */
  80602. var FreeCameraTouchInput = /** @class */ (function () {
  80603. function FreeCameraTouchInput() {
  80604. /**
  80605. * Defines the touch sensibility for rotation.
  80606. * The higher the faster.
  80607. */
  80608. this.touchAngularSensibility = 200000.0;
  80609. /**
  80610. * Defines the touch sensibility for move.
  80611. * The higher the faster.
  80612. */
  80613. this.touchMoveSensibility = 250.0;
  80614. this._offsetX = null;
  80615. this._offsetY = null;
  80616. this._pointerPressed = new Array();
  80617. }
  80618. /**
  80619. * Attach the input controls to a specific dom element to get the input from.
  80620. * @param element Defines the element the controls should be listened from
  80621. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  80622. */
  80623. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  80624. var _this = this;
  80625. var previousPosition = null;
  80626. if (this._pointerInput === undefined) {
  80627. this._onLostFocus = function (evt) {
  80628. _this._offsetX = null;
  80629. _this._offsetY = null;
  80630. };
  80631. this._pointerInput = function (p, s) {
  80632. var evt = p.event;
  80633. if (evt.pointerType === "mouse") {
  80634. return;
  80635. }
  80636. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  80637. if (!noPreventDefault) {
  80638. evt.preventDefault();
  80639. }
  80640. _this._pointerPressed.push(evt.pointerId);
  80641. if (_this._pointerPressed.length !== 1) {
  80642. return;
  80643. }
  80644. previousPosition = {
  80645. x: evt.clientX,
  80646. y: evt.clientY
  80647. };
  80648. }
  80649. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  80650. if (!noPreventDefault) {
  80651. evt.preventDefault();
  80652. }
  80653. var index = _this._pointerPressed.indexOf(evt.pointerId);
  80654. if (index === -1) {
  80655. return;
  80656. }
  80657. _this._pointerPressed.splice(index, 1);
  80658. if (index != 0) {
  80659. return;
  80660. }
  80661. previousPosition = null;
  80662. _this._offsetX = null;
  80663. _this._offsetY = null;
  80664. }
  80665. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  80666. if (!noPreventDefault) {
  80667. evt.preventDefault();
  80668. }
  80669. if (!previousPosition) {
  80670. return;
  80671. }
  80672. var index = _this._pointerPressed.indexOf(evt.pointerId);
  80673. if (index != 0) {
  80674. return;
  80675. }
  80676. _this._offsetX = evt.clientX - previousPosition.x;
  80677. _this._offsetY = -(evt.clientY - previousPosition.y);
  80678. }
  80679. };
  80680. }
  80681. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  80682. if (this._onLostFocus) {
  80683. element.addEventListener("blur", this._onLostFocus);
  80684. }
  80685. };
  80686. /**
  80687. * Detach the current controls from the specified dom element.
  80688. * @param element Defines the element to stop listening the inputs from
  80689. */
  80690. FreeCameraTouchInput.prototype.detachControl = function (element) {
  80691. if (this._pointerInput && element) {
  80692. if (this._observer) {
  80693. this.camera.getScene().onPointerObservable.remove(this._observer);
  80694. this._observer = null;
  80695. }
  80696. if (this._onLostFocus) {
  80697. element.removeEventListener("blur", this._onLostFocus);
  80698. this._onLostFocus = null;
  80699. }
  80700. this._pointerPressed = [];
  80701. this._offsetX = null;
  80702. this._offsetY = null;
  80703. }
  80704. };
  80705. /**
  80706. * Update the current camera state depending on the inputs that have been used this frame.
  80707. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  80708. */
  80709. FreeCameraTouchInput.prototype.checkInputs = function () {
  80710. if (this._offsetX && this._offsetY) {
  80711. var camera = this.camera;
  80712. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  80713. if (this._pointerPressed.length > 1) {
  80714. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  80715. }
  80716. else {
  80717. var speed = camera._computeLocalCameraSpeed();
  80718. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  80719. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  80720. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  80721. }
  80722. }
  80723. };
  80724. /**
  80725. * Gets the class name of the current intput.
  80726. * @returns the class name
  80727. */
  80728. FreeCameraTouchInput.prototype.getClassName = function () {
  80729. return "FreeCameraTouchInput";
  80730. };
  80731. /**
  80732. * Get the friendly name associated with the input class.
  80733. * @returns the input friendly name
  80734. */
  80735. FreeCameraTouchInput.prototype.getSimpleName = function () {
  80736. return "touch";
  80737. };
  80738. __decorate([
  80739. BABYLON.serialize()
  80740. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  80741. __decorate([
  80742. BABYLON.serialize()
  80743. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  80744. return FreeCameraTouchInput;
  80745. }());
  80746. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  80747. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  80748. })(BABYLON || (BABYLON = {}));
  80749. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  80750. var BABYLON;
  80751. (function (BABYLON) {
  80752. BABYLON.Node.AddNodeConstructor("TouchCamera", function (name, scene) {
  80753. return function () { return new TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  80754. });
  80755. /**
  80756. * This represents a FPS type of camera controlled by touch.
  80757. * This is like a universal camera minus the Gamepad controls.
  80758. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  80759. */
  80760. var TouchCamera = /** @class */ (function (_super) {
  80761. __extends(TouchCamera, _super);
  80762. /**
  80763. * Instantiates a new touch camera.
  80764. * This represents a FPS type of camera controlled by touch.
  80765. * This is like a universal camera minus the Gamepad controls.
  80766. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  80767. * @param name Define the name of the camera in the scene
  80768. * @param position Define the start position of the camera in the scene
  80769. * @param scene Define the scene the camera belongs to
  80770. */
  80771. function TouchCamera(name, position, scene) {
  80772. var _this = _super.call(this, name, position, scene) || this;
  80773. _this.inputs.addTouch();
  80774. _this._setupInputs();
  80775. return _this;
  80776. }
  80777. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  80778. /**
  80779. * Defines the touch sensibility for rotation.
  80780. * The higher the faster.
  80781. */
  80782. get: function () {
  80783. var touch = this.inputs.attached["touch"];
  80784. if (touch) {
  80785. return touch.touchAngularSensibility;
  80786. }
  80787. return 0;
  80788. },
  80789. set: function (value) {
  80790. var touch = this.inputs.attached["touch"];
  80791. if (touch) {
  80792. touch.touchAngularSensibility = value;
  80793. }
  80794. },
  80795. enumerable: true,
  80796. configurable: true
  80797. });
  80798. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  80799. /**
  80800. * Defines the touch sensibility for move.
  80801. * The higher the faster.
  80802. */
  80803. get: function () {
  80804. var touch = this.inputs.attached["touch"];
  80805. if (touch) {
  80806. return touch.touchMoveSensibility;
  80807. }
  80808. return 0;
  80809. },
  80810. set: function (value) {
  80811. var touch = this.inputs.attached["touch"];
  80812. if (touch) {
  80813. touch.touchMoveSensibility = value;
  80814. }
  80815. },
  80816. enumerable: true,
  80817. configurable: true
  80818. });
  80819. /**
  80820. * Gets the current object class name.
  80821. * @return the class name
  80822. */
  80823. TouchCamera.prototype.getClassName = function () {
  80824. return "TouchCamera";
  80825. };
  80826. /** @hidden */
  80827. TouchCamera.prototype._setupInputs = function () {
  80828. var mouse = this.inputs.attached["mouse"];
  80829. if (mouse) {
  80830. mouse.touchEnabled = false;
  80831. }
  80832. };
  80833. return TouchCamera;
  80834. }(BABYLON.FreeCamera));
  80835. BABYLON.TouchCamera = TouchCamera;
  80836. })(BABYLON || (BABYLON = {}));
  80837. //# sourceMappingURL=babylon.touchCamera.js.map
  80838. var BABYLON;
  80839. (function (BABYLON) {
  80840. /**
  80841. * Procedural texturing is a way to programmatically create a texture. There are 2 types of procedural textures: code-only, and code that references some classic 2D images, sometimes called 'refMaps' or 'sampler' images.
  80842. * This is the base class of any Procedural texture and contains most of the shareable code.
  80843. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  80844. */
  80845. var ProceduralTexture = /** @class */ (function (_super) {
  80846. __extends(ProceduralTexture, _super);
  80847. /**
  80848. * Instantiates a new procedural texture.
  80849. * Procedural texturing is a way to programmatically create a texture. There are 2 types of procedural textures: code-only, and code that references some classic 2D images, sometimes called 'refMaps' or 'sampler' images.
  80850. * This is the base class of any Procedural texture and contains most of the shareable code.
  80851. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  80852. * @param name Define the name of the texture
  80853. * @param size Define the size of the texture to create
  80854. * @param fragment Define the fragment shader to use to generate the texture or null if it is defined later
  80855. * @param scene Define the scene the texture belongs to
  80856. * @param fallbackTexture Define a fallback texture in case there were issues to create the custom texture
  80857. * @param generateMipMaps Define if the texture should creates mip maps or not
  80858. * @param isCube Define if the texture is a cube texture or not (this will render each faces of the cube)
  80859. */
  80860. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  80861. if (fallbackTexture === void 0) { fallbackTexture = null; }
  80862. if (generateMipMaps === void 0) { generateMipMaps = true; }
  80863. if (isCube === void 0) { isCube = false; }
  80864. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  80865. _this.isCube = isCube;
  80866. /**
  80867. * Define if the texture is enabled or not (disabled texture will not render)
  80868. */
  80869. _this.isEnabled = true;
  80870. /**
  80871. * Define if the texture must be cleared before rendering (default is true)
  80872. */
  80873. _this.autoClear = true;
  80874. /**
  80875. * Event raised when the texture is generated
  80876. */
  80877. _this.onGeneratedObservable = new BABYLON.Observable();
  80878. /** @hidden */
  80879. _this._textures = {};
  80880. _this._currentRefreshId = -1;
  80881. _this._refreshRate = 1;
  80882. _this._vertexBuffers = {};
  80883. _this._uniforms = new Array();
  80884. _this._samplers = new Array();
  80885. _this._floats = {};
  80886. _this._ints = {};
  80887. _this._floatsArrays = {};
  80888. _this._colors3 = {};
  80889. _this._colors4 = {};
  80890. _this._vectors2 = {};
  80891. _this._vectors3 = {};
  80892. _this._matrices = {};
  80893. _this._fallbackTextureUsed = false;
  80894. _this._cachedDefines = "";
  80895. _this._contentUpdateId = -1;
  80896. scene = _this.getScene();
  80897. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_PROCEDURALTEXTURE);
  80898. if (!component) {
  80899. component = new BABYLON.ProceduralTextureSceneComponent(scene);
  80900. scene._addComponent(component);
  80901. }
  80902. scene.proceduralTextures.push(_this);
  80903. _this._engine = scene.getEngine();
  80904. _this.name = name;
  80905. _this.isRenderTarget = true;
  80906. _this._size = size;
  80907. _this._generateMipMaps = generateMipMaps;
  80908. _this.setFragment(fragment);
  80909. _this._fallbackTexture = fallbackTexture;
  80910. if (isCube) {
  80911. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps, generateDepthBuffer: false, generateStencilBuffer: false });
  80912. _this.setFloat("face", 0);
  80913. }
  80914. else {
  80915. _this._texture = _this._engine.createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, generateDepthBuffer: false, generateStencilBuffer: false });
  80916. }
  80917. // VBO
  80918. var vertices = [];
  80919. vertices.push(1, 1);
  80920. vertices.push(-1, 1);
  80921. vertices.push(-1, -1);
  80922. vertices.push(1, -1);
  80923. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  80924. _this._createIndexBuffer();
  80925. return _this;
  80926. }
  80927. /**
  80928. * The effect that is created when initializing the post process.
  80929. * @returns The created effect corrisponding the the postprocess.
  80930. */
  80931. ProceduralTexture.prototype.getEffect = function () {
  80932. return this._effect;
  80933. };
  80934. /**
  80935. * Gets texture content (Use this function wisely as reading from a texture can be slow)
  80936. * @returns an ArrayBufferView (Uint8Array or Float32Array)
  80937. */
  80938. ProceduralTexture.prototype.getContent = function () {
  80939. if (this._contentData && this._currentRefreshId == this._contentUpdateId) {
  80940. return this._contentData;
  80941. }
  80942. this._contentData = this.readPixels(0, 0, this._contentData);
  80943. this._contentUpdateId = this._currentRefreshId;
  80944. return this._contentData;
  80945. };
  80946. ProceduralTexture.prototype._createIndexBuffer = function () {
  80947. var engine = this._engine;
  80948. // Indices
  80949. var indices = [];
  80950. indices.push(0);
  80951. indices.push(1);
  80952. indices.push(2);
  80953. indices.push(0);
  80954. indices.push(2);
  80955. indices.push(3);
  80956. this._indexBuffer = engine.createIndexBuffer(indices);
  80957. };
  80958. /** @hidden */
  80959. ProceduralTexture.prototype._rebuild = function () {
  80960. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  80961. if (vb) {
  80962. vb._rebuild();
  80963. }
  80964. this._createIndexBuffer();
  80965. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  80966. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  80967. }
  80968. };
  80969. /**
  80970. * Resets the texture in order to recreate its associated resources.
  80971. * This can be called in case of context loss
  80972. */
  80973. ProceduralTexture.prototype.reset = function () {
  80974. if (this._effect === undefined) {
  80975. return;
  80976. }
  80977. var engine = this._engine;
  80978. engine._releaseEffect(this._effect);
  80979. };
  80980. ProceduralTexture.prototype._getDefines = function () {
  80981. return "";
  80982. };
  80983. /**
  80984. * Is the texture ready to be used ? (rendered at least once)
  80985. * @returns true if ready, otherwise, false.
  80986. */
  80987. ProceduralTexture.prototype.isReady = function () {
  80988. var _this = this;
  80989. var engine = this._engine;
  80990. var shaders;
  80991. if (!this._fragment) {
  80992. return false;
  80993. }
  80994. if (this._fallbackTextureUsed) {
  80995. return true;
  80996. }
  80997. var defines = this._getDefines();
  80998. if (this._effect && defines === this._cachedDefines && this._effect.isReady()) {
  80999. return true;
  81000. }
  81001. if (this._fragment.fragmentElement !== undefined) {
  81002. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  81003. }
  81004. else {
  81005. shaders = { vertex: "procedural", fragment: this._fragment };
  81006. }
  81007. this._cachedDefines = defines;
  81008. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, defines, undefined, undefined, function () {
  81009. _this.releaseInternalTexture();
  81010. if (_this._fallbackTexture) {
  81011. _this._texture = _this._fallbackTexture._texture;
  81012. if (_this._texture) {
  81013. _this._texture.incrementReferences();
  81014. }
  81015. }
  81016. _this._fallbackTextureUsed = true;
  81017. });
  81018. return this._effect.isReady();
  81019. };
  81020. /**
  81021. * Resets the refresh counter of the texture and start bak from scratch.
  81022. * Could be usefull to regenerate the texture if it is setup to render only once.
  81023. */
  81024. ProceduralTexture.prototype.resetRefreshCounter = function () {
  81025. this._currentRefreshId = -1;
  81026. };
  81027. /**
  81028. * Set the fragment shader to use in order to render the texture.
  81029. * @param fragment This can be set to a path (into the shader store) or to a json object containing a fragmentElement property.
  81030. */
  81031. ProceduralTexture.prototype.setFragment = function (fragment) {
  81032. this._fragment = fragment;
  81033. };
  81034. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  81035. /**
  81036. * Define the refresh rate of the texture or the rendering frequency.
  81037. * Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  81038. */
  81039. get: function () {
  81040. return this._refreshRate;
  81041. },
  81042. set: function (value) {
  81043. this._refreshRate = value;
  81044. this.resetRefreshCounter();
  81045. },
  81046. enumerable: true,
  81047. configurable: true
  81048. });
  81049. /** @hidden */
  81050. ProceduralTexture.prototype._shouldRender = function () {
  81051. if (!this.isEnabled || !this.isReady() || !this._texture) {
  81052. if (this._texture) {
  81053. this._texture.isReady = false;
  81054. }
  81055. return false;
  81056. }
  81057. if (this._fallbackTextureUsed) {
  81058. return false;
  81059. }
  81060. if (this._currentRefreshId === -1) { // At least render once
  81061. this._currentRefreshId = 1;
  81062. return true;
  81063. }
  81064. if (this.refreshRate === this._currentRefreshId) {
  81065. this._currentRefreshId = 1;
  81066. return true;
  81067. }
  81068. this._currentRefreshId++;
  81069. return false;
  81070. };
  81071. /**
  81072. * Get the size the texture is rendering at.
  81073. * @returns the size (texture is always squared)
  81074. */
  81075. ProceduralTexture.prototype.getRenderSize = function () {
  81076. return this._size;
  81077. };
  81078. /**
  81079. * Resize the texture to new value.
  81080. * @param size Define the new size the texture should have
  81081. * @param generateMipMaps Define whether the new texture should create mip maps
  81082. */
  81083. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  81084. if (this._fallbackTextureUsed) {
  81085. return;
  81086. }
  81087. this.releaseInternalTexture();
  81088. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  81089. // Update properties
  81090. this._size = size;
  81091. this._generateMipMaps = generateMipMaps;
  81092. };
  81093. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  81094. if (this._uniforms.indexOf(uniformName) === -1) {
  81095. this._uniforms.push(uniformName);
  81096. }
  81097. };
  81098. /**
  81099. * Set a texture in the shader program used to render.
  81100. * @param name Define the name of the uniform samplers as defined in the shader
  81101. * @param texture Define the texture to bind to this sampler
  81102. * @return the texture itself allowing "fluent" like uniform updates
  81103. */
  81104. ProceduralTexture.prototype.setTexture = function (name, texture) {
  81105. if (this._samplers.indexOf(name) === -1) {
  81106. this._samplers.push(name);
  81107. }
  81108. this._textures[name] = texture;
  81109. return this;
  81110. };
  81111. /**
  81112. * Set a float in the shader.
  81113. * @param name Define the name of the uniform as defined in the shader
  81114. * @param value Define the value to give to the uniform
  81115. * @return the texture itself allowing "fluent" like uniform updates
  81116. */
  81117. ProceduralTexture.prototype.setFloat = function (name, value) {
  81118. this._checkUniform(name);
  81119. this._floats[name] = value;
  81120. return this;
  81121. };
  81122. /**
  81123. * Set a int in the shader.
  81124. * @param name Define the name of the uniform as defined in the shader
  81125. * @param value Define the value to give to the uniform
  81126. * @return the texture itself allowing "fluent" like uniform updates
  81127. */
  81128. ProceduralTexture.prototype.setInt = function (name, value) {
  81129. this._checkUniform(name);
  81130. this._ints[name] = value;
  81131. return this;
  81132. };
  81133. /**
  81134. * Set an array of floats in the shader.
  81135. * @param name Define the name of the uniform as defined in the shader
  81136. * @param value Define the value to give to the uniform
  81137. * @return the texture itself allowing "fluent" like uniform updates
  81138. */
  81139. ProceduralTexture.prototype.setFloats = function (name, value) {
  81140. this._checkUniform(name);
  81141. this._floatsArrays[name] = value;
  81142. return this;
  81143. };
  81144. /**
  81145. * Set a vec3 in the shader from a Color3.
  81146. * @param name Define the name of the uniform as defined in the shader
  81147. * @param value Define the value to give to the uniform
  81148. * @return the texture itself allowing "fluent" like uniform updates
  81149. */
  81150. ProceduralTexture.prototype.setColor3 = function (name, value) {
  81151. this._checkUniform(name);
  81152. this._colors3[name] = value;
  81153. return this;
  81154. };
  81155. /**
  81156. * Set a vec4 in the shader from a Color4.
  81157. * @param name Define the name of the uniform as defined in the shader
  81158. * @param value Define the value to give to the uniform
  81159. * @return the texture itself allowing "fluent" like uniform updates
  81160. */
  81161. ProceduralTexture.prototype.setColor4 = function (name, value) {
  81162. this._checkUniform(name);
  81163. this._colors4[name] = value;
  81164. return this;
  81165. };
  81166. /**
  81167. * Set a vec2 in the shader from a Vector2.
  81168. * @param name Define the name of the uniform as defined in the shader
  81169. * @param value Define the value to give to the uniform
  81170. * @return the texture itself allowing "fluent" like uniform updates
  81171. */
  81172. ProceduralTexture.prototype.setVector2 = function (name, value) {
  81173. this._checkUniform(name);
  81174. this._vectors2[name] = value;
  81175. return this;
  81176. };
  81177. /**
  81178. * Set a vec3 in the shader from a Vector3.
  81179. * @param name Define the name of the uniform as defined in the shader
  81180. * @param value Define the value to give to the uniform
  81181. * @return the texture itself allowing "fluent" like uniform updates
  81182. */
  81183. ProceduralTexture.prototype.setVector3 = function (name, value) {
  81184. this._checkUniform(name);
  81185. this._vectors3[name] = value;
  81186. return this;
  81187. };
  81188. /**
  81189. * Set a mat4 in the shader from a MAtrix.
  81190. * @param name Define the name of the uniform as defined in the shader
  81191. * @param value Define the value to give to the uniform
  81192. * @return the texture itself allowing "fluent" like uniform updates
  81193. */
  81194. ProceduralTexture.prototype.setMatrix = function (name, value) {
  81195. this._checkUniform(name);
  81196. this._matrices[name] = value;
  81197. return this;
  81198. };
  81199. /**
  81200. * Render the texture to its associated render target.
  81201. * @param useCameraPostProcess Define if camera post process should be applied to the texture
  81202. */
  81203. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  81204. var scene = this.getScene();
  81205. if (!scene) {
  81206. return;
  81207. }
  81208. var engine = this._engine;
  81209. // Render
  81210. engine.enableEffect(this._effect);
  81211. engine.setState(false);
  81212. // Texture
  81213. for (var name in this._textures) {
  81214. this._effect.setTexture(name, this._textures[name]);
  81215. }
  81216. // Float
  81217. for (name in this._ints) {
  81218. this._effect.setInt(name, this._ints[name]);
  81219. }
  81220. // Float
  81221. for (name in this._floats) {
  81222. this._effect.setFloat(name, this._floats[name]);
  81223. }
  81224. // Floats
  81225. for (name in this._floatsArrays) {
  81226. this._effect.setArray(name, this._floatsArrays[name]);
  81227. }
  81228. // Color3
  81229. for (name in this._colors3) {
  81230. this._effect.setColor3(name, this._colors3[name]);
  81231. }
  81232. // Color4
  81233. for (name in this._colors4) {
  81234. var color = this._colors4[name];
  81235. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  81236. }
  81237. // Vector2
  81238. for (name in this._vectors2) {
  81239. this._effect.setVector2(name, this._vectors2[name]);
  81240. }
  81241. // Vector3
  81242. for (name in this._vectors3) {
  81243. this._effect.setVector3(name, this._vectors3[name]);
  81244. }
  81245. // Matrix
  81246. for (name in this._matrices) {
  81247. this._effect.setMatrix(name, this._matrices[name]);
  81248. }
  81249. if (!this._texture) {
  81250. return;
  81251. }
  81252. if (this.isCube) {
  81253. for (var face = 0; face < 6; face++) {
  81254. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  81255. // VBOs
  81256. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  81257. this._effect.setFloat("face", face);
  81258. // Clear
  81259. if (this.autoClear) {
  81260. engine.clear(scene.clearColor, true, false, false);
  81261. }
  81262. // Draw order
  81263. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  81264. // Mipmaps
  81265. if (face === 5) {
  81266. engine.generateMipMapsForCubemap(this._texture);
  81267. }
  81268. }
  81269. }
  81270. else {
  81271. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  81272. // VBOs
  81273. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  81274. // Clear
  81275. if (this.autoClear) {
  81276. engine.clear(scene.clearColor, true, false, false);
  81277. }
  81278. // Draw order
  81279. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  81280. }
  81281. // Unbind
  81282. engine.unBindFramebuffer(this._texture, this.isCube);
  81283. if (this.onGenerated) {
  81284. this.onGenerated();
  81285. }
  81286. this.onGeneratedObservable.notifyObservers(this);
  81287. };
  81288. /**
  81289. * Clone the texture.
  81290. * @returns the cloned texture
  81291. */
  81292. ProceduralTexture.prototype.clone = function () {
  81293. var textureSize = this.getSize();
  81294. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  81295. // Base texture
  81296. newTexture.hasAlpha = this.hasAlpha;
  81297. newTexture.level = this.level;
  81298. // RenderTarget Texture
  81299. newTexture.coordinatesMode = this.coordinatesMode;
  81300. return newTexture;
  81301. };
  81302. /**
  81303. * Dispose the texture and release its asoociated resources.
  81304. */
  81305. ProceduralTexture.prototype.dispose = function () {
  81306. var scene = this.getScene();
  81307. if (!scene) {
  81308. return;
  81309. }
  81310. var index = scene.proceduralTextures.indexOf(this);
  81311. if (index >= 0) {
  81312. scene.proceduralTextures.splice(index, 1);
  81313. }
  81314. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  81315. if (vertexBuffer) {
  81316. vertexBuffer.dispose();
  81317. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  81318. }
  81319. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  81320. this._indexBuffer = null;
  81321. }
  81322. _super.prototype.dispose.call(this);
  81323. };
  81324. __decorate([
  81325. BABYLON.serialize()
  81326. ], ProceduralTexture.prototype, "isEnabled", void 0);
  81327. __decorate([
  81328. BABYLON.serialize()
  81329. ], ProceduralTexture.prototype, "autoClear", void 0);
  81330. __decorate([
  81331. BABYLON.serialize()
  81332. ], ProceduralTexture.prototype, "_generateMipMaps", void 0);
  81333. __decorate([
  81334. BABYLON.serialize()
  81335. ], ProceduralTexture.prototype, "_size", void 0);
  81336. __decorate([
  81337. BABYLON.serialize()
  81338. ], ProceduralTexture.prototype, "refreshRate", null);
  81339. return ProceduralTexture;
  81340. }(BABYLON.Texture));
  81341. BABYLON.ProceduralTexture = ProceduralTexture;
  81342. })(BABYLON || (BABYLON = {}));
  81343. //# sourceMappingURL=babylon.proceduralTexture.js.map
  81344. var BABYLON;
  81345. (function (BABYLON) {
  81346. /**
  81347. * Defines the Procedural Texture scene component responsible to manage any Procedural Texture
  81348. * in a given scene.
  81349. */
  81350. var ProceduralTextureSceneComponent = /** @class */ (function () {
  81351. /**
  81352. * Creates a new instance of the component for the given scene
  81353. * @param scene Defines the scene to register the component in
  81354. */
  81355. function ProceduralTextureSceneComponent(scene) {
  81356. /**
  81357. * The component name helpfull to identify the component in the list of scene components.
  81358. */
  81359. this.name = BABYLON.SceneComponentConstants.NAME_PROCEDURALTEXTURE;
  81360. this.scene = scene;
  81361. this.scene.proceduralTextures = new Array();
  81362. scene.layers = new Array();
  81363. }
  81364. /**
  81365. * Registers the component in a given scene
  81366. */
  81367. ProceduralTextureSceneComponent.prototype.register = function () {
  81368. this.scene._beforeClearStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECLEAR_PROCEDURALTEXTURE, this, this._beforeClear);
  81369. };
  81370. /**
  81371. * Rebuilds the elements related to this component in case of
  81372. * context lost for instance.
  81373. */
  81374. ProceduralTextureSceneComponent.prototype.rebuild = function () {
  81375. // Nothing to do here.
  81376. };
  81377. /**
  81378. * Disposes the component and the associated ressources.
  81379. */
  81380. ProceduralTextureSceneComponent.prototype.dispose = function () {
  81381. // Nothing to do here.
  81382. };
  81383. ProceduralTextureSceneComponent.prototype._beforeClear = function () {
  81384. if (this.scene.proceduralTexturesEnabled) {
  81385. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.scene.proceduralTextures.length > 0);
  81386. for (var proceduralIndex = 0; proceduralIndex < this.scene.proceduralTextures.length; proceduralIndex++) {
  81387. var proceduralTexture = this.scene.proceduralTextures[proceduralIndex];
  81388. if (proceduralTexture._shouldRender()) {
  81389. proceduralTexture.render();
  81390. }
  81391. }
  81392. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.scene.proceduralTextures.length > 0);
  81393. }
  81394. };
  81395. return ProceduralTextureSceneComponent;
  81396. }());
  81397. BABYLON.ProceduralTextureSceneComponent = ProceduralTextureSceneComponent;
  81398. })(BABYLON || (BABYLON = {}));
  81399. //# sourceMappingURL=babylon.proceduralTextureSceneComponent.js.map
  81400. var BABYLON;
  81401. (function (BABYLON) {
  81402. /**
  81403. * Procedural texturing is a way to programmatically create a texture. There are 2 types of procedural textures: code-only, and code that references some classic 2D images, sometimes called 'refMaps' or 'sampler' images.
  81404. * Custom Procedural textures are the easiest way to create your own procedural in your application.
  81405. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures#creating-custom-procedural-textures
  81406. */
  81407. var CustomProceduralTexture = /** @class */ (function (_super) {
  81408. __extends(CustomProceduralTexture, _super);
  81409. /**
  81410. * Instantiates a new Custom Procedural Texture.
  81411. * Procedural texturing is a way to programmatically create a texture. There are 2 types of procedural textures: code-only, and code that references some classic 2D images, sometimes called 'refMaps' or 'sampler' images.
  81412. * Custom Procedural textures are the easiest way to create your own procedural in your application.
  81413. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures#creating-custom-procedural-textures
  81414. * @param name Define the name of the texture
  81415. * @param texturePath Define the folder path containing all the cutom texture related files (config, shaders...)
  81416. * @param size Define the size of the texture to create
  81417. * @param scene Define the scene the texture belongs to
  81418. * @param fallbackTexture Define a fallback texture in case there were issues to create the custom texture
  81419. * @param generateMipMaps Define if the texture should creates mip maps or not
  81420. */
  81421. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  81422. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  81423. _this._animate = true;
  81424. _this._time = 0;
  81425. _this._texturePath = texturePath;
  81426. //Try to load json
  81427. _this._loadJson(texturePath);
  81428. _this.refreshRate = 1;
  81429. return _this;
  81430. }
  81431. CustomProceduralTexture.prototype._loadJson = function (jsonUrl) {
  81432. var _this = this;
  81433. var noConfigFile = function () {
  81434. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  81435. try {
  81436. _this.setFragment(_this._texturePath);
  81437. }
  81438. catch (ex) {
  81439. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  81440. }
  81441. };
  81442. var configFileUrl = jsonUrl + "/config.json";
  81443. var xhr = new XMLHttpRequest();
  81444. xhr.open("GET", configFileUrl, true);
  81445. xhr.addEventListener("load", function () {
  81446. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  81447. try {
  81448. _this._config = JSON.parse(xhr.response);
  81449. _this.updateShaderUniforms();
  81450. _this.updateTextures();
  81451. _this.setFragment(_this._texturePath + "/custom");
  81452. _this._animate = _this._config.animate;
  81453. _this.refreshRate = _this._config.refreshrate;
  81454. }
  81455. catch (ex) {
  81456. noConfigFile();
  81457. }
  81458. }
  81459. else {
  81460. noConfigFile();
  81461. }
  81462. }, false);
  81463. xhr.addEventListener("error", function () {
  81464. noConfigFile();
  81465. }, false);
  81466. try {
  81467. xhr.send();
  81468. }
  81469. catch (ex) {
  81470. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  81471. }
  81472. };
  81473. /**
  81474. * Is the texture ready to be used ? (rendered at least once)
  81475. * @returns true if ready, otherwise, false.
  81476. */
  81477. CustomProceduralTexture.prototype.isReady = function () {
  81478. if (!_super.prototype.isReady.call(this)) {
  81479. return false;
  81480. }
  81481. for (var name in this._textures) {
  81482. var texture = this._textures[name];
  81483. if (!texture.isReady()) {
  81484. return false;
  81485. }
  81486. }
  81487. return true;
  81488. };
  81489. /**
  81490. * Render the texture to its associated render target.
  81491. * @param useCameraPostProcess Define if camera post process should be applied to the texture
  81492. */
  81493. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  81494. var scene = this.getScene();
  81495. if (this._animate && scene) {
  81496. this._time += scene.getAnimationRatio() * 0.03;
  81497. this.updateShaderUniforms();
  81498. }
  81499. _super.prototype.render.call(this, useCameraPostProcess);
  81500. };
  81501. /**
  81502. * Update the list of dependant textures samplers in the shader.
  81503. */
  81504. CustomProceduralTexture.prototype.updateTextures = function () {
  81505. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  81506. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  81507. }
  81508. };
  81509. /**
  81510. * Update the uniform values of the procedural texture in the shader.
  81511. */
  81512. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  81513. if (this._config) {
  81514. for (var j = 0; j < this._config.uniforms.length; j++) {
  81515. var uniform = this._config.uniforms[j];
  81516. switch (uniform.type) {
  81517. case "float":
  81518. this.setFloat(uniform.name, uniform.value);
  81519. break;
  81520. case "color3":
  81521. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  81522. break;
  81523. case "color4":
  81524. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  81525. break;
  81526. case "vector2":
  81527. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  81528. break;
  81529. case "vector3":
  81530. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  81531. break;
  81532. }
  81533. }
  81534. }
  81535. this.setFloat("time", this._time);
  81536. };
  81537. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  81538. /**
  81539. * Define if the texture animates or not.
  81540. */
  81541. get: function () {
  81542. return this._animate;
  81543. },
  81544. set: function (value) {
  81545. this._animate = value;
  81546. },
  81547. enumerable: true,
  81548. configurable: true
  81549. });
  81550. return CustomProceduralTexture;
  81551. }(BABYLON.ProceduralTexture));
  81552. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  81553. })(BABYLON || (BABYLON = {}));
  81554. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  81555. var BABYLON;
  81556. (function (BABYLON) {
  81557. /**
  81558. * Manage the gamepad inputs to control a free camera.
  81559. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  81560. */
  81561. var FreeCameraGamepadInput = /** @class */ (function () {
  81562. function FreeCameraGamepadInput() {
  81563. /**
  81564. * Defines the gamepad rotation sensiblity.
  81565. * This is the threshold from when rotation starts to be accounted for to prevent jittering.
  81566. */
  81567. this.gamepadAngularSensibility = 200;
  81568. /**
  81569. * Defines the gamepad move sensiblity.
  81570. * This is the threshold from when moving starts to be accounted for for to prevent jittering.
  81571. */
  81572. this.gamepadMoveSensibility = 40;
  81573. this._cameraTransform = BABYLON.Matrix.Identity();
  81574. this._deltaTransform = BABYLON.Vector3.Zero();
  81575. this._vector3 = BABYLON.Vector3.Zero();
  81576. this._vector2 = BABYLON.Vector2.Zero();
  81577. }
  81578. /**
  81579. * Attach the input controls to a specific dom element to get the input from.
  81580. * @param element Defines the element the controls should be listened from
  81581. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  81582. */
  81583. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  81584. var _this = this;
  81585. var manager = this.camera.getScene().gamepadManager;
  81586. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  81587. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  81588. // prioritize XBOX gamepads.
  81589. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  81590. _this.gamepad = gamepad;
  81591. }
  81592. }
  81593. });
  81594. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  81595. if (_this.gamepad === gamepad) {
  81596. _this.gamepad = null;
  81597. }
  81598. });
  81599. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  81600. };
  81601. /**
  81602. * Detach the current controls from the specified dom element.
  81603. * @param element Defines the element to stop listening the inputs from
  81604. */
  81605. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  81606. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  81607. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  81608. this.gamepad = null;
  81609. };
  81610. /**
  81611. * Update the current camera state depending on the inputs that have been used this frame.
  81612. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  81613. */
  81614. FreeCameraGamepadInput.prototype.checkInputs = function () {
  81615. if (this.gamepad && this.gamepad.leftStick) {
  81616. var camera = this.camera;
  81617. var LSValues = this.gamepad.leftStick;
  81618. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  81619. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  81620. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  81621. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  81622. var RSValues = this.gamepad.rightStick;
  81623. if (RSValues) {
  81624. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  81625. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  81626. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  81627. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  81628. }
  81629. else {
  81630. RSValues = { x: 0, y: 0 };
  81631. }
  81632. if (!camera.rotationQuaternion) {
  81633. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  81634. }
  81635. else {
  81636. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  81637. }
  81638. var speed = camera._computeLocalCameraSpeed() * 50.0;
  81639. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  81640. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  81641. camera.cameraDirection.addInPlace(this._deltaTransform);
  81642. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  81643. camera.cameraRotation.addInPlace(this._vector2);
  81644. }
  81645. };
  81646. /**
  81647. * Gets the class name of the current intput.
  81648. * @returns the class name
  81649. */
  81650. FreeCameraGamepadInput.prototype.getClassName = function () {
  81651. return "FreeCameraGamepadInput";
  81652. };
  81653. /**
  81654. * Get the friendly name associated with the input class.
  81655. * @returns the input friendly name
  81656. */
  81657. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  81658. return "gamepad";
  81659. };
  81660. __decorate([
  81661. BABYLON.serialize()
  81662. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  81663. __decorate([
  81664. BABYLON.serialize()
  81665. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  81666. return FreeCameraGamepadInput;
  81667. }());
  81668. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  81669. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  81670. })(BABYLON || (BABYLON = {}));
  81671. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  81672. var BABYLON;
  81673. (function (BABYLON) {
  81674. /**
  81675. * Manage the gamepad inputs to control an arc rotate camera.
  81676. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  81677. */
  81678. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  81679. function ArcRotateCameraGamepadInput() {
  81680. /**
  81681. * Defines the gamepad rotation sensiblity.
  81682. * This is the threshold from when rotation starts to be accounted for to prevent jittering.
  81683. */
  81684. this.gamepadRotationSensibility = 80;
  81685. /**
  81686. * Defines the gamepad move sensiblity.
  81687. * This is the threshold from when moving starts to be accounted for for to prevent jittering.
  81688. */
  81689. this.gamepadMoveSensibility = 40;
  81690. }
  81691. /**
  81692. * Attach the input controls to a specific dom element to get the input from.
  81693. * @param element Defines the element the controls should be listened from
  81694. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  81695. */
  81696. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  81697. var _this = this;
  81698. var manager = this.camera.getScene().gamepadManager;
  81699. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  81700. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  81701. // prioritize XBOX gamepads.
  81702. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  81703. _this.gamepad = gamepad;
  81704. }
  81705. }
  81706. });
  81707. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  81708. if (_this.gamepad === gamepad) {
  81709. _this.gamepad = null;
  81710. }
  81711. });
  81712. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  81713. };
  81714. /**
  81715. * Detach the current controls from the specified dom element.
  81716. * @param element Defines the element to stop listening the inputs from
  81717. */
  81718. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  81719. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  81720. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  81721. this.gamepad = null;
  81722. };
  81723. /**
  81724. * Update the current camera state depending on the inputs that have been used this frame.
  81725. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  81726. */
  81727. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  81728. if (this.gamepad) {
  81729. var camera = this.camera;
  81730. var RSValues = this.gamepad.rightStick;
  81731. if (RSValues) {
  81732. if (RSValues.x != 0) {
  81733. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  81734. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  81735. camera.inertialAlphaOffset += normalizedRX;
  81736. }
  81737. }
  81738. if (RSValues.y != 0) {
  81739. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  81740. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  81741. camera.inertialBetaOffset += normalizedRY;
  81742. }
  81743. }
  81744. }
  81745. var LSValues = this.gamepad.leftStick;
  81746. if (LSValues && LSValues.y != 0) {
  81747. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  81748. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  81749. this.camera.inertialRadiusOffset -= normalizedLY;
  81750. }
  81751. }
  81752. }
  81753. };
  81754. /**
  81755. * Gets the class name of the current intput.
  81756. * @returns the class name
  81757. */
  81758. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  81759. return "ArcRotateCameraGamepadInput";
  81760. };
  81761. /**
  81762. * Get the friendly name associated with the input class.
  81763. * @returns the input friendly name
  81764. */
  81765. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  81766. return "gamepad";
  81767. };
  81768. __decorate([
  81769. BABYLON.serialize()
  81770. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  81771. __decorate([
  81772. BABYLON.serialize()
  81773. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  81774. return ArcRotateCameraGamepadInput;
  81775. }());
  81776. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  81777. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  81778. })(BABYLON || (BABYLON = {}));
  81779. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  81780. var BABYLON;
  81781. (function (BABYLON) {
  81782. /**
  81783. * Manager for handling gamepads
  81784. */
  81785. var GamepadManager = /** @class */ (function () {
  81786. /**
  81787. * Initializes the gamepad manager
  81788. * @param _scene BabylonJS scene
  81789. */
  81790. function GamepadManager(_scene) {
  81791. var _this = this;
  81792. this._scene = _scene;
  81793. this._babylonGamepads = [];
  81794. this._oneGamepadConnected = false;
  81795. /** @hidden */
  81796. this._isMonitoring = false;
  81797. /**
  81798. * observable to be triggered when the gamepad controller has been disconnected
  81799. */
  81800. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  81801. if (!BABYLON.Tools.IsWindowObjectExist()) {
  81802. this._gamepadEventSupported = false;
  81803. }
  81804. else {
  81805. this._gamepadEventSupported = 'GamepadEvent' in window;
  81806. this._gamepadSupport = (navigator.getGamepads ||
  81807. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  81808. }
  81809. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  81810. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  81811. for (var i in _this._babylonGamepads) {
  81812. var gamepad = _this._babylonGamepads[i];
  81813. if (gamepad && gamepad._isConnected) {
  81814. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  81815. }
  81816. }
  81817. });
  81818. this._onGamepadConnectedEvent = function (evt) {
  81819. var gamepad = evt.gamepad;
  81820. if (gamepad.index in _this._babylonGamepads) {
  81821. if (_this._babylonGamepads[gamepad.index].isConnected) {
  81822. return;
  81823. }
  81824. }
  81825. var newGamepad;
  81826. if (_this._babylonGamepads[gamepad.index]) {
  81827. newGamepad = _this._babylonGamepads[gamepad.index];
  81828. newGamepad.browserGamepad = gamepad;
  81829. newGamepad._isConnected = true;
  81830. }
  81831. else {
  81832. newGamepad = _this._addNewGamepad(gamepad);
  81833. }
  81834. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  81835. _this._startMonitoringGamepads();
  81836. };
  81837. this._onGamepadDisconnectedEvent = function (evt) {
  81838. var gamepad = evt.gamepad;
  81839. // Remove the gamepad from the list of gamepads to monitor.
  81840. for (var i in _this._babylonGamepads) {
  81841. if (_this._babylonGamepads[i].index === gamepad.index) {
  81842. var disconnectedGamepad = _this._babylonGamepads[i];
  81843. disconnectedGamepad._isConnected = false;
  81844. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  81845. break;
  81846. }
  81847. }
  81848. };
  81849. if (this._gamepadSupport) {
  81850. //first add already-connected gamepads
  81851. this._updateGamepadObjects();
  81852. if (this._babylonGamepads.length) {
  81853. this._startMonitoringGamepads();
  81854. }
  81855. // Checking if the gamepad connected event is supported (like in Firefox)
  81856. if (this._gamepadEventSupported) {
  81857. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  81858. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  81859. }
  81860. else {
  81861. this._startMonitoringGamepads();
  81862. }
  81863. }
  81864. }
  81865. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  81866. /**
  81867. * The gamepads in the game pad manager
  81868. */
  81869. get: function () {
  81870. return this._babylonGamepads;
  81871. },
  81872. enumerable: true,
  81873. configurable: true
  81874. });
  81875. /**
  81876. * Get the gamepad controllers based on type
  81877. * @param type The type of gamepad controller
  81878. * @returns Nullable gamepad
  81879. */
  81880. GamepadManager.prototype.getGamepadByType = function (type) {
  81881. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  81882. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  81883. var gamepad = _a[_i];
  81884. if (gamepad && gamepad.type === type) {
  81885. return gamepad;
  81886. }
  81887. }
  81888. return null;
  81889. };
  81890. /**
  81891. * Disposes the gamepad manager
  81892. */
  81893. GamepadManager.prototype.dispose = function () {
  81894. if (this._gamepadEventSupported) {
  81895. if (this._onGamepadConnectedEvent) {
  81896. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  81897. }
  81898. if (this._onGamepadDisconnectedEvent) {
  81899. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  81900. }
  81901. this._onGamepadConnectedEvent = null;
  81902. this._onGamepadDisconnectedEvent = null;
  81903. }
  81904. this._babylonGamepads.forEach(function (gamepad) {
  81905. gamepad.dispose();
  81906. });
  81907. this.onGamepadConnectedObservable.clear();
  81908. this.onGamepadDisconnectedObservable.clear();
  81909. this._oneGamepadConnected = false;
  81910. this._stopMonitoringGamepads();
  81911. this._babylonGamepads = [];
  81912. };
  81913. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  81914. if (!this._oneGamepadConnected) {
  81915. this._oneGamepadConnected = true;
  81916. }
  81917. var newGamepad;
  81918. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  81919. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  81920. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  81921. }
  81922. // if pose is supported, use the (WebVR) pose enabled controller
  81923. else if (gamepad.pose) {
  81924. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  81925. }
  81926. else {
  81927. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  81928. }
  81929. this._babylonGamepads[newGamepad.index] = newGamepad;
  81930. return newGamepad;
  81931. };
  81932. GamepadManager.prototype._startMonitoringGamepads = function () {
  81933. if (!this._isMonitoring) {
  81934. this._isMonitoring = true;
  81935. //back-comp
  81936. if (!this._scene) {
  81937. this._checkGamepadsStatus();
  81938. }
  81939. }
  81940. };
  81941. GamepadManager.prototype._stopMonitoringGamepads = function () {
  81942. this._isMonitoring = false;
  81943. };
  81944. /** @hidden */
  81945. GamepadManager.prototype._checkGamepadsStatus = function () {
  81946. var _this = this;
  81947. // Hack to be compatible Chrome
  81948. this._updateGamepadObjects();
  81949. for (var i in this._babylonGamepads) {
  81950. var gamepad = this._babylonGamepads[i];
  81951. if (!gamepad || !gamepad.isConnected) {
  81952. continue;
  81953. }
  81954. gamepad.update();
  81955. }
  81956. if (this._isMonitoring && !this._scene) {
  81957. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  81958. }
  81959. };
  81960. // This function is called only on Chrome, which does not properly support
  81961. // connection/disconnection events and forces you to recopy again the gamepad object
  81962. GamepadManager.prototype._updateGamepadObjects = function () {
  81963. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  81964. for (var i = 0; i < gamepads.length; i++) {
  81965. var gamepad = gamepads[i];
  81966. if (gamepad) {
  81967. if (!this._babylonGamepads[gamepad.index]) {
  81968. var newGamepad = this._addNewGamepad(gamepad);
  81969. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  81970. }
  81971. else {
  81972. // Forced to copy again this object for Chrome for unknown reason
  81973. this._babylonGamepads[i].browserGamepad = gamepad;
  81974. if (!this._babylonGamepads[i].isConnected) {
  81975. this._babylonGamepads[i]._isConnected = true;
  81976. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  81977. }
  81978. }
  81979. }
  81980. }
  81981. };
  81982. return GamepadManager;
  81983. }());
  81984. BABYLON.GamepadManager = GamepadManager;
  81985. })(BABYLON || (BABYLON = {}));
  81986. //# sourceMappingURL=babylon.gamepadManager.js.map
  81987. var BABYLON;
  81988. (function (BABYLON) {
  81989. /**
  81990. * Represents a gamepad control stick position
  81991. */
  81992. var StickValues = /** @class */ (function () {
  81993. /**
  81994. * Initializes the gamepad x and y control stick values
  81995. * @param x The x component of the gamepad control stick value
  81996. * @param y The y component of the gamepad control stick value
  81997. */
  81998. function StickValues(
  81999. /**
  82000. * The x component of the control stick
  82001. */
  82002. x,
  82003. /**
  82004. * The y component of the control stick
  82005. */
  82006. y) {
  82007. this.x = x;
  82008. this.y = y;
  82009. }
  82010. return StickValues;
  82011. }());
  82012. BABYLON.StickValues = StickValues;
  82013. /**
  82014. * Represents a gamepad
  82015. */
  82016. var Gamepad = /** @class */ (function () {
  82017. /**
  82018. * Initializes the gamepad
  82019. * @param id The id of the gamepad
  82020. * @param index The index of the gamepad
  82021. * @param browserGamepad The browser gamepad
  82022. * @param leftStickX The x component of the left joystick
  82023. * @param leftStickY The y component of the left joystick
  82024. * @param rightStickX The x component of the right joystick
  82025. * @param rightStickY The y component of the right joystick
  82026. */
  82027. function Gamepad(
  82028. /**
  82029. * The id of the gamepad
  82030. */
  82031. id,
  82032. /**
  82033. * The index of the gamepad
  82034. */
  82035. index,
  82036. /**
  82037. * The browser gamepad
  82038. */
  82039. browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  82040. if (leftStickX === void 0) { leftStickX = 0; }
  82041. if (leftStickY === void 0) { leftStickY = 1; }
  82042. if (rightStickX === void 0) { rightStickX = 2; }
  82043. if (rightStickY === void 0) { rightStickY = 3; }
  82044. this.id = id;
  82045. this.index = index;
  82046. this.browserGamepad = browserGamepad;
  82047. this._leftStick = { x: 0, y: 0 };
  82048. this._rightStick = { x: 0, y: 0 };
  82049. /** @hidden */
  82050. this._isConnected = true;
  82051. /**
  82052. * Specifies whether the left control stick should be Y-inverted
  82053. */
  82054. this._invertLeftStickY = false;
  82055. this.type = Gamepad.GAMEPAD;
  82056. this._leftStickAxisX = leftStickX;
  82057. this._leftStickAxisY = leftStickY;
  82058. this._rightStickAxisX = rightStickX;
  82059. this._rightStickAxisY = rightStickY;
  82060. if (this.browserGamepad.axes.length >= 2) {
  82061. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  82062. }
  82063. if (this.browserGamepad.axes.length >= 4) {
  82064. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  82065. }
  82066. }
  82067. Object.defineProperty(Gamepad.prototype, "isConnected", {
  82068. /**
  82069. * Specifies if the gamepad has been connected
  82070. */
  82071. get: function () {
  82072. return this._isConnected;
  82073. },
  82074. enumerable: true,
  82075. configurable: true
  82076. });
  82077. /**
  82078. * Callback triggered when the left joystick has changed
  82079. * @param callback
  82080. */
  82081. Gamepad.prototype.onleftstickchanged = function (callback) {
  82082. this._onleftstickchanged = callback;
  82083. };
  82084. /**
  82085. * Callback triggered when the right joystick has changed
  82086. * @param callback
  82087. */
  82088. Gamepad.prototype.onrightstickchanged = function (callback) {
  82089. this._onrightstickchanged = callback;
  82090. };
  82091. Object.defineProperty(Gamepad.prototype, "leftStick", {
  82092. /**
  82093. * Gets the left joystick
  82094. */
  82095. get: function () {
  82096. return this._leftStick;
  82097. },
  82098. /**
  82099. * Sets the left joystick values
  82100. */
  82101. set: function (newValues) {
  82102. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  82103. this._onleftstickchanged(newValues);
  82104. }
  82105. this._leftStick = newValues;
  82106. },
  82107. enumerable: true,
  82108. configurable: true
  82109. });
  82110. Object.defineProperty(Gamepad.prototype, "rightStick", {
  82111. /**
  82112. * Gets the right joystick
  82113. */
  82114. get: function () {
  82115. return this._rightStick;
  82116. },
  82117. /**
  82118. * Sets the right joystick value
  82119. */
  82120. set: function (newValues) {
  82121. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  82122. this._onrightstickchanged(newValues);
  82123. }
  82124. this._rightStick = newValues;
  82125. },
  82126. enumerable: true,
  82127. configurable: true
  82128. });
  82129. /**
  82130. * Updates the gamepad joystick positions
  82131. */
  82132. Gamepad.prototype.update = function () {
  82133. if (this._leftStick) {
  82134. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  82135. if (this._invertLeftStickY) {
  82136. this.leftStick.y *= -1;
  82137. }
  82138. }
  82139. if (this._rightStick) {
  82140. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  82141. }
  82142. };
  82143. /**
  82144. * Disposes the gamepad
  82145. */
  82146. Gamepad.prototype.dispose = function () {
  82147. };
  82148. /**
  82149. * Represents a gamepad controller
  82150. */
  82151. Gamepad.GAMEPAD = 0;
  82152. /**
  82153. * Represents a generic controller
  82154. */
  82155. Gamepad.GENERIC = 1;
  82156. /**
  82157. * Represents an XBox controller
  82158. */
  82159. Gamepad.XBOX = 2;
  82160. /**
  82161. * Represents a pose-enabled controller
  82162. */
  82163. Gamepad.POSE_ENABLED = 3;
  82164. return Gamepad;
  82165. }());
  82166. BABYLON.Gamepad = Gamepad;
  82167. /**
  82168. * Represents a generic gamepad
  82169. */
  82170. var GenericPad = /** @class */ (function (_super) {
  82171. __extends(GenericPad, _super);
  82172. /**
  82173. * Initializes the generic gamepad
  82174. * @param id The id of the generic gamepad
  82175. * @param index The index of the generic gamepad
  82176. * @param browserGamepad The browser gamepad
  82177. */
  82178. function GenericPad(id, index, browserGamepad) {
  82179. var _this = _super.call(this, id, index, browserGamepad) || this;
  82180. /**
  82181. * Observable triggered when a button has been pressed
  82182. */
  82183. _this.onButtonDownObservable = new BABYLON.Observable();
  82184. /**
  82185. * Observable triggered when a button has been released
  82186. */
  82187. _this.onButtonUpObservable = new BABYLON.Observable();
  82188. _this.type = Gamepad.GENERIC;
  82189. _this._buttons = new Array(browserGamepad.buttons.length);
  82190. return _this;
  82191. }
  82192. /**
  82193. * Callback triggered when a button has been pressed
  82194. * @param callback Called when a button has been pressed
  82195. */
  82196. GenericPad.prototype.onbuttondown = function (callback) {
  82197. this._onbuttondown = callback;
  82198. };
  82199. /**
  82200. * Callback triggered when a button has been released
  82201. * @param callback Called when a button has been released
  82202. */
  82203. GenericPad.prototype.onbuttonup = function (callback) {
  82204. this._onbuttonup = callback;
  82205. };
  82206. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  82207. if (newValue !== currentValue) {
  82208. if (newValue === 1) {
  82209. if (this._onbuttondown) {
  82210. this._onbuttondown(buttonIndex);
  82211. }
  82212. this.onButtonDownObservable.notifyObservers(buttonIndex);
  82213. }
  82214. if (newValue === 0) {
  82215. if (this._onbuttonup) {
  82216. this._onbuttonup(buttonIndex);
  82217. }
  82218. this.onButtonUpObservable.notifyObservers(buttonIndex);
  82219. }
  82220. }
  82221. return newValue;
  82222. };
  82223. /**
  82224. * Updates the generic gamepad
  82225. */
  82226. GenericPad.prototype.update = function () {
  82227. _super.prototype.update.call(this);
  82228. for (var index = 0; index < this._buttons.length; index++) {
  82229. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  82230. }
  82231. };
  82232. /**
  82233. * Disposes the generic gamepad
  82234. */
  82235. GenericPad.prototype.dispose = function () {
  82236. _super.prototype.dispose.call(this);
  82237. this.onButtonDownObservable.clear();
  82238. this.onButtonUpObservable.clear();
  82239. };
  82240. return GenericPad;
  82241. }(Gamepad));
  82242. BABYLON.GenericPad = GenericPad;
  82243. })(BABYLON || (BABYLON = {}));
  82244. //# sourceMappingURL=babylon.gamepad.js.map
  82245. var BABYLON;
  82246. (function (BABYLON) {
  82247. /**
  82248. * Defines supported buttons for XBox360 compatible gamepads
  82249. */
  82250. var Xbox360Button;
  82251. (function (Xbox360Button) {
  82252. /** A */
  82253. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  82254. /** B */
  82255. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  82256. /** X */
  82257. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  82258. /** Y */
  82259. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  82260. /** Start */
  82261. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  82262. /** Back */
  82263. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  82264. /** Left button */
  82265. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  82266. /** Right button */
  82267. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  82268. /** Left stick */
  82269. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  82270. /** Right stick */
  82271. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  82272. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  82273. /** Defines values for XBox360 DPad */
  82274. var Xbox360Dpad;
  82275. (function (Xbox360Dpad) {
  82276. /** Up */
  82277. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  82278. /** Down */
  82279. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  82280. /** Left */
  82281. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  82282. /** Right */
  82283. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  82284. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  82285. /**
  82286. * Defines a XBox360 gamepad
  82287. */
  82288. var Xbox360Pad = /** @class */ (function (_super) {
  82289. __extends(Xbox360Pad, _super);
  82290. /**
  82291. * Creates a new XBox360 gamepad object
  82292. * @param id defines the id of this gamepad
  82293. * @param index defines its index
  82294. * @param gamepad defines the internal HTML gamepad object
  82295. * @param xboxOne defines if it is a XBox One gamepad
  82296. */
  82297. function Xbox360Pad(id, index, gamepad, xboxOne) {
  82298. if (xboxOne === void 0) { xboxOne = false; }
  82299. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  82300. _this._leftTrigger = 0;
  82301. _this._rightTrigger = 0;
  82302. /** Observable raised when a button is pressed */
  82303. _this.onButtonDownObservable = new BABYLON.Observable();
  82304. /** Observable raised when a button is released */
  82305. _this.onButtonUpObservable = new BABYLON.Observable();
  82306. /** Observable raised when a pad is pressed */
  82307. _this.onPadDownObservable = new BABYLON.Observable();
  82308. /** Observable raised when a pad is released */
  82309. _this.onPadUpObservable = new BABYLON.Observable();
  82310. _this._buttonA = 0;
  82311. _this._buttonB = 0;
  82312. _this._buttonX = 0;
  82313. _this._buttonY = 0;
  82314. _this._buttonBack = 0;
  82315. _this._buttonStart = 0;
  82316. _this._buttonLB = 0;
  82317. _this._buttonRB = 0;
  82318. _this._buttonLeftStick = 0;
  82319. _this._buttonRightStick = 0;
  82320. _this._dPadUp = 0;
  82321. _this._dPadDown = 0;
  82322. _this._dPadLeft = 0;
  82323. _this._dPadRight = 0;
  82324. _this._isXboxOnePad = false;
  82325. _this.type = BABYLON.Gamepad.XBOX;
  82326. _this._isXboxOnePad = xboxOne;
  82327. return _this;
  82328. }
  82329. /**
  82330. * Defines the callback to call when left trigger is pressed
  82331. * @param callback defines the callback to use
  82332. */
  82333. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  82334. this._onlefttriggerchanged = callback;
  82335. };
  82336. /**
  82337. * Defines the callback to call when right trigger is pressed
  82338. * @param callback defines the callback to use
  82339. */
  82340. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  82341. this._onrighttriggerchanged = callback;
  82342. };
  82343. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  82344. /**
  82345. * Gets the left trigger value
  82346. */
  82347. get: function () {
  82348. return this._leftTrigger;
  82349. },
  82350. /**
  82351. * Sets the left trigger value
  82352. */
  82353. set: function (newValue) {
  82354. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  82355. this._onlefttriggerchanged(newValue);
  82356. }
  82357. this._leftTrigger = newValue;
  82358. },
  82359. enumerable: true,
  82360. configurable: true
  82361. });
  82362. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  82363. /**
  82364. * Gets the right trigger value
  82365. */
  82366. get: function () {
  82367. return this._rightTrigger;
  82368. },
  82369. /**
  82370. * Sets the right trigger value
  82371. */
  82372. set: function (newValue) {
  82373. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  82374. this._onrighttriggerchanged(newValue);
  82375. }
  82376. this._rightTrigger = newValue;
  82377. },
  82378. enumerable: true,
  82379. configurable: true
  82380. });
  82381. /**
  82382. * Defines the callback to call when a button is pressed
  82383. * @param callback defines the callback to use
  82384. */
  82385. Xbox360Pad.prototype.onbuttondown = function (callback) {
  82386. this._onbuttondown = callback;
  82387. };
  82388. /**
  82389. * Defines the callback to call when a button is released
  82390. * @param callback defines the callback to use
  82391. */
  82392. Xbox360Pad.prototype.onbuttonup = function (callback) {
  82393. this._onbuttonup = callback;
  82394. };
  82395. /**
  82396. * Defines the callback to call when a pad is pressed
  82397. * @param callback defines the callback to use
  82398. */
  82399. Xbox360Pad.prototype.ondpaddown = function (callback) {
  82400. this._ondpaddown = callback;
  82401. };
  82402. /**
  82403. * Defines the callback to call when a pad is released
  82404. * @param callback defines the callback to use
  82405. */
  82406. Xbox360Pad.prototype.ondpadup = function (callback) {
  82407. this._ondpadup = callback;
  82408. };
  82409. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  82410. if (newValue !== currentValue) {
  82411. if (newValue === 1) {
  82412. if (this._onbuttondown) {
  82413. this._onbuttondown(buttonType);
  82414. }
  82415. this.onButtonDownObservable.notifyObservers(buttonType);
  82416. }
  82417. if (newValue === 0) {
  82418. if (this._onbuttonup) {
  82419. this._onbuttonup(buttonType);
  82420. }
  82421. this.onButtonUpObservable.notifyObservers(buttonType);
  82422. }
  82423. }
  82424. return newValue;
  82425. };
  82426. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  82427. if (newValue !== currentValue) {
  82428. if (newValue === 1) {
  82429. if (this._ondpaddown) {
  82430. this._ondpaddown(buttonType);
  82431. }
  82432. this.onPadDownObservable.notifyObservers(buttonType);
  82433. }
  82434. if (newValue === 0) {
  82435. if (this._ondpadup) {
  82436. this._ondpadup(buttonType);
  82437. }
  82438. this.onPadUpObservable.notifyObservers(buttonType);
  82439. }
  82440. }
  82441. return newValue;
  82442. };
  82443. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  82444. /**
  82445. * Gets the value of the `A` button
  82446. */
  82447. get: function () {
  82448. return this._buttonA;
  82449. },
  82450. /**
  82451. * Sets the value of the `A` button
  82452. */
  82453. set: function (value) {
  82454. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  82455. },
  82456. enumerable: true,
  82457. configurable: true
  82458. });
  82459. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  82460. /**
  82461. * Gets the value of the `B` button
  82462. */
  82463. get: function () {
  82464. return this._buttonB;
  82465. },
  82466. /**
  82467. * Sets the value of the `B` button
  82468. */
  82469. set: function (value) {
  82470. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  82471. },
  82472. enumerable: true,
  82473. configurable: true
  82474. });
  82475. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  82476. /**
  82477. * Gets the value of the `X` button
  82478. */
  82479. get: function () {
  82480. return this._buttonX;
  82481. },
  82482. /**
  82483. * Sets the value of the `X` button
  82484. */
  82485. set: function (value) {
  82486. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  82487. },
  82488. enumerable: true,
  82489. configurable: true
  82490. });
  82491. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  82492. /**
  82493. * Gets the value of the `Y` button
  82494. */
  82495. get: function () {
  82496. return this._buttonY;
  82497. },
  82498. /**
  82499. * Sets the value of the `Y` button
  82500. */
  82501. set: function (value) {
  82502. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  82503. },
  82504. enumerable: true,
  82505. configurable: true
  82506. });
  82507. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  82508. /**
  82509. * Gets the value of the `Start` button
  82510. */
  82511. get: function () {
  82512. return this._buttonStart;
  82513. },
  82514. /**
  82515. * Sets the value of the `Start` button
  82516. */
  82517. set: function (value) {
  82518. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  82519. },
  82520. enumerable: true,
  82521. configurable: true
  82522. });
  82523. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  82524. /**
  82525. * Gets the value of the `Back` button
  82526. */
  82527. get: function () {
  82528. return this._buttonBack;
  82529. },
  82530. /**
  82531. * Sets the value of the `Back` button
  82532. */
  82533. set: function (value) {
  82534. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  82535. },
  82536. enumerable: true,
  82537. configurable: true
  82538. });
  82539. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  82540. /**
  82541. * Gets the value of the `Left` button
  82542. */
  82543. get: function () {
  82544. return this._buttonLB;
  82545. },
  82546. /**
  82547. * Sets the value of the `Left` button
  82548. */
  82549. set: function (value) {
  82550. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  82551. },
  82552. enumerable: true,
  82553. configurable: true
  82554. });
  82555. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  82556. /**
  82557. * Gets the value of the `Right` button
  82558. */
  82559. get: function () {
  82560. return this._buttonRB;
  82561. },
  82562. /**
  82563. * Sets the value of the `Right` button
  82564. */
  82565. set: function (value) {
  82566. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  82567. },
  82568. enumerable: true,
  82569. configurable: true
  82570. });
  82571. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  82572. /**
  82573. * Gets the value of the Left joystick
  82574. */
  82575. get: function () {
  82576. return this._buttonLeftStick;
  82577. },
  82578. /**
  82579. * Sets the value of the Left joystick
  82580. */
  82581. set: function (value) {
  82582. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  82583. },
  82584. enumerable: true,
  82585. configurable: true
  82586. });
  82587. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  82588. /**
  82589. * Gets the value of the Right joystick
  82590. */
  82591. get: function () {
  82592. return this._buttonRightStick;
  82593. },
  82594. /**
  82595. * Sets the value of the Right joystick
  82596. */
  82597. set: function (value) {
  82598. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  82599. },
  82600. enumerable: true,
  82601. configurable: true
  82602. });
  82603. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  82604. /**
  82605. * Gets the value of D-pad up
  82606. */
  82607. get: function () {
  82608. return this._dPadUp;
  82609. },
  82610. /**
  82611. * Sets the value of D-pad up
  82612. */
  82613. set: function (value) {
  82614. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  82615. },
  82616. enumerable: true,
  82617. configurable: true
  82618. });
  82619. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  82620. /**
  82621. * Gets the value of D-pad down
  82622. */
  82623. get: function () {
  82624. return this._dPadDown;
  82625. },
  82626. /**
  82627. * Sets the value of D-pad down
  82628. */
  82629. set: function (value) {
  82630. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  82631. },
  82632. enumerable: true,
  82633. configurable: true
  82634. });
  82635. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  82636. /**
  82637. * Gets the value of D-pad left
  82638. */
  82639. get: function () {
  82640. return this._dPadLeft;
  82641. },
  82642. /**
  82643. * Sets the value of D-pad left
  82644. */
  82645. set: function (value) {
  82646. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  82647. },
  82648. enumerable: true,
  82649. configurable: true
  82650. });
  82651. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  82652. /**
  82653. * Gets the value of D-pad right
  82654. */
  82655. get: function () {
  82656. return this._dPadRight;
  82657. },
  82658. /**
  82659. * Sets the value of D-pad right
  82660. */
  82661. set: function (value) {
  82662. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  82663. },
  82664. enumerable: true,
  82665. configurable: true
  82666. });
  82667. /**
  82668. * Force the gamepad to synchronize with device values
  82669. */
  82670. Xbox360Pad.prototype.update = function () {
  82671. _super.prototype.update.call(this);
  82672. if (this._isXboxOnePad) {
  82673. this.buttonA = this.browserGamepad.buttons[0].value;
  82674. this.buttonB = this.browserGamepad.buttons[1].value;
  82675. this.buttonX = this.browserGamepad.buttons[2].value;
  82676. this.buttonY = this.browserGamepad.buttons[3].value;
  82677. this.buttonLB = this.browserGamepad.buttons[4].value;
  82678. this.buttonRB = this.browserGamepad.buttons[5].value;
  82679. this.leftTrigger = this.browserGamepad.axes[2];
  82680. this.rightTrigger = this.browserGamepad.axes[5];
  82681. this.buttonBack = this.browserGamepad.buttons[9].value;
  82682. this.buttonStart = this.browserGamepad.buttons[8].value;
  82683. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  82684. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  82685. this.dPadUp = this.browserGamepad.buttons[11].value;
  82686. this.dPadDown = this.browserGamepad.buttons[12].value;
  82687. this.dPadLeft = this.browserGamepad.buttons[13].value;
  82688. this.dPadRight = this.browserGamepad.buttons[14].value;
  82689. }
  82690. else {
  82691. this.buttonA = this.browserGamepad.buttons[0].value;
  82692. this.buttonB = this.browserGamepad.buttons[1].value;
  82693. this.buttonX = this.browserGamepad.buttons[2].value;
  82694. this.buttonY = this.browserGamepad.buttons[3].value;
  82695. this.buttonLB = this.browserGamepad.buttons[4].value;
  82696. this.buttonRB = this.browserGamepad.buttons[5].value;
  82697. this.leftTrigger = this.browserGamepad.buttons[6].value;
  82698. this.rightTrigger = this.browserGamepad.buttons[7].value;
  82699. this.buttonBack = this.browserGamepad.buttons[8].value;
  82700. this.buttonStart = this.browserGamepad.buttons[9].value;
  82701. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  82702. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  82703. this.dPadUp = this.browserGamepad.buttons[12].value;
  82704. this.dPadDown = this.browserGamepad.buttons[13].value;
  82705. this.dPadLeft = this.browserGamepad.buttons[14].value;
  82706. this.dPadRight = this.browserGamepad.buttons[15].value;
  82707. }
  82708. };
  82709. /**
  82710. * Disposes the gamepad
  82711. */
  82712. Xbox360Pad.prototype.dispose = function () {
  82713. _super.prototype.dispose.call(this);
  82714. this.onButtonDownObservable.clear();
  82715. this.onButtonUpObservable.clear();
  82716. this.onPadDownObservable.clear();
  82717. this.onPadUpObservable.clear();
  82718. };
  82719. return Xbox360Pad;
  82720. }(BABYLON.Gamepad));
  82721. BABYLON.Xbox360Pad = Xbox360Pad;
  82722. })(BABYLON || (BABYLON = {}));
  82723. //# sourceMappingURL=babylon.xboxGamepad.js.map
  82724. var BABYLON;
  82725. (function (BABYLON) {
  82726. /**
  82727. * Defines the types of pose enabled controllers that are supported
  82728. */
  82729. var PoseEnabledControllerType;
  82730. (function (PoseEnabledControllerType) {
  82731. /**
  82732. * HTC Vive
  82733. */
  82734. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  82735. /**
  82736. * Oculus Rift
  82737. */
  82738. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  82739. /**
  82740. * Windows mixed reality
  82741. */
  82742. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  82743. /**
  82744. * Samsung gear VR
  82745. */
  82746. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  82747. /**
  82748. * Google Daydream
  82749. */
  82750. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  82751. /**
  82752. * Generic
  82753. */
  82754. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  82755. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  82756. /**
  82757. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  82758. */
  82759. var PoseEnabledControllerHelper = /** @class */ (function () {
  82760. function PoseEnabledControllerHelper() {
  82761. }
  82762. /**
  82763. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  82764. * @param vrGamepad the gamepad to initialized
  82765. * @returns a vr controller of the type the gamepad identified as
  82766. */
  82767. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  82768. // Oculus Touch
  82769. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  82770. return new BABYLON.OculusTouchController(vrGamepad);
  82771. }
  82772. // Windows Mixed Reality controllers
  82773. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  82774. return new BABYLON.WindowsMotionController(vrGamepad);
  82775. }
  82776. // HTC Vive
  82777. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  82778. return new BABYLON.ViveController(vrGamepad);
  82779. }
  82780. // Samsung/Oculus Gear VR or Oculus Go
  82781. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0 || vrGamepad.id.indexOf('Oculus Go') !== -1) {
  82782. return new BABYLON.GearVRController(vrGamepad);
  82783. }
  82784. // Google Daydream
  82785. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  82786. return new BABYLON.DaydreamController(vrGamepad);
  82787. }
  82788. // Generic
  82789. else {
  82790. return new BABYLON.GenericController(vrGamepad);
  82791. }
  82792. };
  82793. return PoseEnabledControllerHelper;
  82794. }());
  82795. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  82796. /**
  82797. * Defines the PoseEnabledController object that contains state of a vr capable controller
  82798. */
  82799. var PoseEnabledController = /** @class */ (function (_super) {
  82800. __extends(PoseEnabledController, _super);
  82801. /**
  82802. * Creates a new PoseEnabledController from a gamepad
  82803. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  82804. */
  82805. function PoseEnabledController(browserGamepad) {
  82806. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  82807. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  82808. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  82809. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  82810. /**
  82811. * The device position in babylon space
  82812. */
  82813. _this.devicePosition = BABYLON.Vector3.Zero();
  82814. /**
  82815. * The device rotation in babylon space
  82816. */
  82817. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  82818. /**
  82819. * The scale factor of the device in babylon space
  82820. */
  82821. _this.deviceScaleFactor = 1;
  82822. // Used to convert 6dof controllers to 3dof
  82823. _this._trackPosition = true;
  82824. _this._maxRotationDistFromHeadset = Math.PI / 5;
  82825. _this._draggedRoomRotation = 0;
  82826. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  82827. /**
  82828. * Internal, matrix used to convert room space to babylon space
  82829. * @hidden
  82830. */
  82831. _this._deviceToWorld = BABYLON.Matrix.Identity();
  82832. /**
  82833. * Node to be used when casting a ray from the controller
  82834. * @hidden
  82835. */
  82836. _this._pointingPoseNode = null;
  82837. _this._workingMatrix = BABYLON.Matrix.Identity();
  82838. /**
  82839. * @hidden
  82840. */
  82841. _this._meshAttachedObservable = new BABYLON.Observable();
  82842. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  82843. _this.controllerType = PoseEnabledControllerType.GENERIC;
  82844. _this.position = BABYLON.Vector3.Zero();
  82845. _this.rotationQuaternion = new BABYLON.Quaternion();
  82846. _this._calculatedPosition = BABYLON.Vector3.Zero();
  82847. _this._calculatedRotation = new BABYLON.Quaternion();
  82848. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  82849. return _this;
  82850. }
  82851. /**
  82852. * @hidden
  82853. */
  82854. PoseEnabledController.prototype._disableTrackPosition = function (fixedPosition) {
  82855. if (this._trackPosition) {
  82856. this._calculatedPosition.copyFrom(fixedPosition);
  82857. this._trackPosition = false;
  82858. }
  82859. };
  82860. /**
  82861. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  82862. */
  82863. PoseEnabledController.prototype.update = function () {
  82864. _super.prototype.update.call(this);
  82865. this._updatePoseAndMesh();
  82866. };
  82867. /**
  82868. * Updates only the pose device and mesh without doing any button event checking
  82869. */
  82870. PoseEnabledController.prototype._updatePoseAndMesh = function () {
  82871. var pose = this.browserGamepad.pose;
  82872. this.updateFromDevice(pose);
  82873. if (!this._trackPosition && BABYLON.Engine.LastCreatedScene && BABYLON.Engine.LastCreatedScene.activeCamera && BABYLON.Engine.LastCreatedScene.activeCamera.devicePosition) {
  82874. var camera = BABYLON.Engine.LastCreatedScene.activeCamera;
  82875. camera._computeDevicePosition();
  82876. this._deviceToWorld.setTranslation(camera.devicePosition);
  82877. if (camera.deviceRotationQuaternion) {
  82878. var camera = camera;
  82879. camera._deviceRoomRotationQuaternion.toEulerAnglesToRef(BABYLON.Tmp.Vector3[0]);
  82880. // Find the radian distance away that the headset is from the controllers rotation
  82881. var distanceAway = Math.atan2(Math.sin(BABYLON.Tmp.Vector3[0].y - this._draggedRoomRotation), Math.cos(BABYLON.Tmp.Vector3[0].y - this._draggedRoomRotation));
  82882. if (Math.abs(distanceAway) > this._maxRotationDistFromHeadset) {
  82883. // Only rotate enouph to be within the _maxRotationDistFromHeadset
  82884. var rotationAmount = distanceAway - (distanceAway < 0 ? -this._maxRotationDistFromHeadset : this._maxRotationDistFromHeadset);
  82885. this._draggedRoomRotation += rotationAmount;
  82886. // Rotate controller around headset
  82887. var sin = Math.sin(-rotationAmount);
  82888. var cos = Math.cos(-rotationAmount);
  82889. this._calculatedPosition.x = this._calculatedPosition.x * cos - this._calculatedPosition.z * sin;
  82890. this._calculatedPosition.z = this._calculatedPosition.x * sin + this._calculatedPosition.z * cos;
  82891. }
  82892. }
  82893. }
  82894. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  82895. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  82896. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  82897. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  82898. if (this._mesh) {
  82899. this._mesh.position.copyFrom(this.devicePosition);
  82900. if (this._mesh.rotationQuaternion) {
  82901. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  82902. }
  82903. }
  82904. };
  82905. /**
  82906. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  82907. * @param poseData raw pose fromthe device
  82908. */
  82909. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  82910. if (poseData) {
  82911. this.rawPose = poseData;
  82912. if (poseData.position) {
  82913. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  82914. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  82915. this._deviceRoomPosition.z *= -1;
  82916. }
  82917. if (this._trackPosition) {
  82918. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  82919. }
  82920. this._calculatedPosition.addInPlace(this.position);
  82921. }
  82922. var pose = this.rawPose;
  82923. if (poseData.orientation && pose.orientation) {
  82924. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  82925. if (this._mesh) {
  82926. if (this._mesh.getScene().useRightHandedSystem) {
  82927. this._deviceRoomRotationQuaternion.z *= -1;
  82928. this._deviceRoomRotationQuaternion.w *= -1;
  82929. }
  82930. else {
  82931. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  82932. }
  82933. }
  82934. // if the camera is set, rotate to the camera's rotation
  82935. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  82936. }
  82937. }
  82938. };
  82939. /**
  82940. * Attaches a mesh to the controller
  82941. * @param mesh the mesh to be attached
  82942. */
  82943. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  82944. if (this._mesh) {
  82945. this._mesh.parent = null;
  82946. }
  82947. this._mesh = mesh;
  82948. if (this._poseControlledCamera) {
  82949. this._mesh.parent = this._poseControlledCamera;
  82950. }
  82951. if (!this._mesh.rotationQuaternion) {
  82952. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  82953. }
  82954. // 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
  82955. this._updatePoseAndMesh();
  82956. if (this._pointingPoseNode) {
  82957. var parents = [];
  82958. var obj = this._pointingPoseNode;
  82959. while (obj.parent) {
  82960. parents.push(obj.parent);
  82961. obj = obj.parent;
  82962. }
  82963. parents.reverse().forEach(function (p) { p.computeWorldMatrix(true); });
  82964. }
  82965. this._meshAttachedObservable.notifyObservers(mesh);
  82966. };
  82967. /**
  82968. * Attaches the controllers mesh to a camera
  82969. * @param camera the camera the mesh should be attached to
  82970. */
  82971. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  82972. this._poseControlledCamera = camera;
  82973. if (this._mesh) {
  82974. this._mesh.parent = this._poseControlledCamera;
  82975. }
  82976. };
  82977. /**
  82978. * Disposes of the controller
  82979. */
  82980. PoseEnabledController.prototype.dispose = function () {
  82981. if (this._mesh) {
  82982. this._mesh.dispose();
  82983. }
  82984. this._mesh = null;
  82985. _super.prototype.dispose.call(this);
  82986. };
  82987. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  82988. /**
  82989. * The mesh that is attached to the controller
  82990. */
  82991. get: function () {
  82992. return this._mesh;
  82993. },
  82994. enumerable: true,
  82995. configurable: true
  82996. });
  82997. /**
  82998. * Gets the ray of the controller in the direction the controller is pointing
  82999. * @param length the length the resulting ray should be
  83000. * @returns a ray in the direction the controller is pointing
  83001. */
  83002. PoseEnabledController.prototype.getForwardRay = function (length) {
  83003. if (length === void 0) { length = 100; }
  83004. if (!this.mesh) {
  83005. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  83006. }
  83007. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  83008. var origin = m.getTranslation();
  83009. var forward = new BABYLON.Vector3(0, 0, -1);
  83010. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  83011. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  83012. return new BABYLON.Ray(origin, direction, length);
  83013. };
  83014. /**
  83015. * Name of the child mesh that can be used to cast a ray from the controller
  83016. */
  83017. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  83018. return PoseEnabledController;
  83019. }(BABYLON.Gamepad));
  83020. BABYLON.PoseEnabledController = PoseEnabledController;
  83021. })(BABYLON || (BABYLON = {}));
  83022. //# sourceMappingURL=babylon.poseEnabledController.js.map
  83023. var BABYLON;
  83024. (function (BABYLON) {
  83025. /**
  83026. * Defines the WebVRController object that represents controllers tracked in 3D space
  83027. */
  83028. var WebVRController = /** @class */ (function (_super) {
  83029. __extends(WebVRController, _super);
  83030. /**
  83031. * Creates a new WebVRController from a gamepad
  83032. * @param vrGamepad the gamepad that the WebVRController should be created from
  83033. */
  83034. function WebVRController(vrGamepad) {
  83035. var _this = _super.call(this, vrGamepad) || this;
  83036. // Observables
  83037. /**
  83038. * Fired when the trigger state has changed
  83039. */
  83040. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  83041. /**
  83042. * Fired when the main button state has changed
  83043. */
  83044. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  83045. /**
  83046. * Fired when the secondary button state has changed
  83047. */
  83048. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  83049. /**
  83050. * Fired when the pad state has changed
  83051. */
  83052. _this.onPadStateChangedObservable = new BABYLON.Observable();
  83053. /**
  83054. * Fired when controllers stick values have changed
  83055. */
  83056. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  83057. /**
  83058. * X and Y axis corrisponding to the controllers joystick
  83059. */
  83060. _this.pad = { x: 0, y: 0 };
  83061. // avoid GC, store state in a tmp object
  83062. _this._changes = {
  83063. pressChanged: false,
  83064. touchChanged: false,
  83065. valueChanged: false,
  83066. changed: false
  83067. };
  83068. _this._buttons = new Array(vrGamepad.buttons.length);
  83069. _this.hand = vrGamepad.hand;
  83070. return _this;
  83071. }
  83072. /**
  83073. * Fired when a controller button's state has changed
  83074. * @param callback the callback containing the button that was modified
  83075. */
  83076. WebVRController.prototype.onButtonStateChange = function (callback) {
  83077. this._onButtonStateChange = callback;
  83078. };
  83079. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  83080. /**
  83081. * The default controller model for the controller
  83082. */
  83083. get: function () {
  83084. return this._defaultModel;
  83085. },
  83086. enumerable: true,
  83087. configurable: true
  83088. });
  83089. /**
  83090. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  83091. */
  83092. WebVRController.prototype.update = function () {
  83093. _super.prototype.update.call(this);
  83094. for (var index = 0; index < this._buttons.length; index++) {
  83095. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  83096. }
  83097. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  83098. this.pad.x = this.leftStick.x;
  83099. this.pad.y = this.leftStick.y;
  83100. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  83101. }
  83102. };
  83103. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  83104. if (!newState) {
  83105. newState = {
  83106. pressed: false,
  83107. touched: false,
  83108. value: 0
  83109. };
  83110. }
  83111. if (!currentState) {
  83112. this._buttons[buttonIndex] = {
  83113. pressed: newState.pressed,
  83114. touched: newState.touched,
  83115. value: newState.value
  83116. };
  83117. return;
  83118. }
  83119. this._checkChanges(newState, currentState);
  83120. if (this._changes.changed) {
  83121. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  83122. this._handleButtonChange(buttonIndex, newState, this._changes);
  83123. }
  83124. this._buttons[buttonIndex].pressed = newState.pressed;
  83125. this._buttons[buttonIndex].touched = newState.touched;
  83126. // oculus triggers are never 0, thou not touched.
  83127. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  83128. };
  83129. WebVRController.prototype._checkChanges = function (newState, currentState) {
  83130. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  83131. this._changes.touchChanged = newState.touched !== currentState.touched;
  83132. this._changes.valueChanged = newState.value !== currentState.value;
  83133. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  83134. return this._changes;
  83135. };
  83136. /**
  83137. * Disposes of th webVRCOntroller
  83138. */
  83139. WebVRController.prototype.dispose = function () {
  83140. _super.prototype.dispose.call(this);
  83141. this.onTriggerStateChangedObservable.clear();
  83142. this.onMainButtonStateChangedObservable.clear();
  83143. this.onSecondaryButtonStateChangedObservable.clear();
  83144. this.onPadStateChangedObservable.clear();
  83145. this.onPadValuesChangedObservable.clear();
  83146. };
  83147. return WebVRController;
  83148. }(BABYLON.PoseEnabledController));
  83149. BABYLON.WebVRController = WebVRController;
  83150. })(BABYLON || (BABYLON = {}));
  83151. //# sourceMappingURL=babylon.webVRController.js.map
  83152. var BABYLON;
  83153. (function (BABYLON) {
  83154. /**
  83155. * Oculus Touch Controller
  83156. */
  83157. var OculusTouchController = /** @class */ (function (_super) {
  83158. __extends(OculusTouchController, _super);
  83159. /**
  83160. * Creates a new OculusTouchController from a gamepad
  83161. * @param vrGamepad the gamepad that the controller should be created from
  83162. */
  83163. function OculusTouchController(vrGamepad) {
  83164. var _this = _super.call(this, vrGamepad) || this;
  83165. /**
  83166. * Fired when the secondary trigger on this controller is modified
  83167. */
  83168. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  83169. /**
  83170. * Fired when the thumb rest on this controller is modified
  83171. */
  83172. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  83173. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  83174. return _this;
  83175. }
  83176. /**
  83177. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  83178. * @param scene scene in which to add meshes
  83179. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  83180. */
  83181. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  83182. var _this = this;
  83183. var meshName;
  83184. // Hand
  83185. if (this.hand === 'left') {
  83186. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  83187. }
  83188. else { // Right is the default if no hand is specified
  83189. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  83190. }
  83191. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  83192. /*
  83193. Parent Mesh name: oculus_touch_left
  83194. - body
  83195. - trigger
  83196. - thumbstick
  83197. - grip
  83198. - button_y
  83199. - button_x
  83200. - button_enter
  83201. */
  83202. _this._defaultModel = newMeshes[1];
  83203. _this.attachToMesh(_this._defaultModel);
  83204. if (meshLoaded) {
  83205. meshLoaded(_this._defaultModel);
  83206. }
  83207. });
  83208. };
  83209. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  83210. /**
  83211. * Fired when the A button on this controller is modified
  83212. */
  83213. get: function () {
  83214. if (this.hand === 'right') {
  83215. return this.onMainButtonStateChangedObservable;
  83216. }
  83217. else {
  83218. throw new Error('No A button on left hand');
  83219. }
  83220. },
  83221. enumerable: true,
  83222. configurable: true
  83223. });
  83224. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  83225. /**
  83226. * Fired when the B button on this controller is modified
  83227. */
  83228. get: function () {
  83229. if (this.hand === 'right') {
  83230. return this.onSecondaryButtonStateChangedObservable;
  83231. }
  83232. else {
  83233. throw new Error('No B button on left hand');
  83234. }
  83235. },
  83236. enumerable: true,
  83237. configurable: true
  83238. });
  83239. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  83240. /**
  83241. * Fired when the X button on this controller is modified
  83242. */
  83243. get: function () {
  83244. if (this.hand === 'left') {
  83245. return this.onMainButtonStateChangedObservable;
  83246. }
  83247. else {
  83248. throw new Error('No X button on right hand');
  83249. }
  83250. },
  83251. enumerable: true,
  83252. configurable: true
  83253. });
  83254. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  83255. /**
  83256. * Fired when the Y button on this controller is modified
  83257. */
  83258. get: function () {
  83259. if (this.hand === 'left') {
  83260. return this.onSecondaryButtonStateChangedObservable;
  83261. }
  83262. else {
  83263. throw new Error('No Y button on right hand');
  83264. }
  83265. },
  83266. enumerable: true,
  83267. configurable: true
  83268. });
  83269. /**
  83270. * Called once for each button that changed state since the last frame
  83271. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  83272. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  83273. * 2) secondary trigger (same)
  83274. * 3) A (right) X (left), touch, pressed = value
  83275. * 4) B / Y
  83276. * 5) thumb rest
  83277. * @param buttonIdx Which button index changed
  83278. * @param state New state of the button
  83279. * @param changes Which properties on the state changed since last frame
  83280. */
  83281. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  83282. var notifyObject = state; //{ state: state, changes: changes };
  83283. var triggerDirection = this.hand === 'right' ? -1 : 1;
  83284. switch (buttonIdx) {
  83285. case 0:
  83286. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  83287. return;
  83288. case 1: // index trigger
  83289. if (this._defaultModel) {
  83290. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  83291. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  83292. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  83293. }
  83294. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  83295. return;
  83296. case 2: // secondary trigger
  83297. if (this._defaultModel) {
  83298. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  83299. }
  83300. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  83301. return;
  83302. case 3:
  83303. if (this._defaultModel) {
  83304. if (notifyObject.pressed) {
  83305. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  83306. }
  83307. else {
  83308. (this._defaultModel.getChildren()[1]).position.y = 0;
  83309. }
  83310. }
  83311. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  83312. return;
  83313. case 4:
  83314. if (this._defaultModel) {
  83315. if (notifyObject.pressed) {
  83316. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  83317. }
  83318. else {
  83319. (this._defaultModel.getChildren()[2]).position.y = 0;
  83320. }
  83321. }
  83322. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  83323. return;
  83324. case 5:
  83325. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  83326. return;
  83327. }
  83328. };
  83329. /**
  83330. * Base Url for the controller model.
  83331. */
  83332. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  83333. /**
  83334. * File name for the left controller model.
  83335. */
  83336. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  83337. /**
  83338. * File name for the right controller model.
  83339. */
  83340. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  83341. return OculusTouchController;
  83342. }(BABYLON.WebVRController));
  83343. BABYLON.OculusTouchController = OculusTouchController;
  83344. })(BABYLON || (BABYLON = {}));
  83345. //# sourceMappingURL=babylon.oculusTouchController.js.map
  83346. var BABYLON;
  83347. (function (BABYLON) {
  83348. /**
  83349. * Vive Controller
  83350. */
  83351. var ViveController = /** @class */ (function (_super) {
  83352. __extends(ViveController, _super);
  83353. /**
  83354. * Creates a new ViveController from a gamepad
  83355. * @param vrGamepad the gamepad that the controller should be created from
  83356. */
  83357. function ViveController(vrGamepad) {
  83358. var _this = _super.call(this, vrGamepad) || this;
  83359. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  83360. _this._invertLeftStickY = true;
  83361. return _this;
  83362. }
  83363. /**
  83364. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  83365. * @param scene scene in which to add meshes
  83366. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  83367. */
  83368. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  83369. var _this = this;
  83370. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  83371. /*
  83372. Parent Mesh name: ViveWand
  83373. - body
  83374. - r_gripper
  83375. - l_gripper
  83376. - menu_button
  83377. - system_button
  83378. - trackpad
  83379. - trigger
  83380. - LED
  83381. */
  83382. _this._defaultModel = newMeshes[1];
  83383. _this.attachToMesh(_this._defaultModel);
  83384. if (meshLoaded) {
  83385. meshLoaded(_this._defaultModel);
  83386. }
  83387. });
  83388. };
  83389. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  83390. /**
  83391. * Fired when the left button on this controller is modified
  83392. */
  83393. get: function () {
  83394. return this.onMainButtonStateChangedObservable;
  83395. },
  83396. enumerable: true,
  83397. configurable: true
  83398. });
  83399. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  83400. /**
  83401. * Fired when the right button on this controller is modified
  83402. */
  83403. get: function () {
  83404. return this.onMainButtonStateChangedObservable;
  83405. },
  83406. enumerable: true,
  83407. configurable: true
  83408. });
  83409. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  83410. /**
  83411. * Fired when the menu button on this controller is modified
  83412. */
  83413. get: function () {
  83414. return this.onSecondaryButtonStateChangedObservable;
  83415. },
  83416. enumerable: true,
  83417. configurable: true
  83418. });
  83419. /**
  83420. * Called once for each button that changed state since the last frame
  83421. * Vive mapping:
  83422. * 0: touchpad
  83423. * 1: trigger
  83424. * 2: left AND right buttons
  83425. * 3: menu button
  83426. * @param buttonIdx Which button index changed
  83427. * @param state New state of the button
  83428. * @param changes Which properties on the state changed since last frame
  83429. */
  83430. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  83431. var notifyObject = state; //{ state: state, changes: changes };
  83432. switch (buttonIdx) {
  83433. case 0:
  83434. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  83435. return;
  83436. case 1: // index trigger
  83437. if (this._defaultModel) {
  83438. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  83439. }
  83440. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  83441. return;
  83442. case 2: // left AND right button
  83443. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  83444. return;
  83445. case 3:
  83446. if (this._defaultModel) {
  83447. if (notifyObject.pressed) {
  83448. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  83449. }
  83450. else {
  83451. (this._defaultModel.getChildren()[2]).position.y = 0;
  83452. }
  83453. }
  83454. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  83455. return;
  83456. }
  83457. };
  83458. /**
  83459. * Base Url for the controller model.
  83460. */
  83461. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  83462. /**
  83463. * File name for the controller model.
  83464. */
  83465. ViveController.MODEL_FILENAME = 'wand.babylon';
  83466. return ViveController;
  83467. }(BABYLON.WebVRController));
  83468. BABYLON.ViveController = ViveController;
  83469. })(BABYLON || (BABYLON = {}));
  83470. //# sourceMappingURL=babylon.viveController.js.map
  83471. var BABYLON;
  83472. (function (BABYLON) {
  83473. /**
  83474. * Generic Controller
  83475. */
  83476. var GenericController = /** @class */ (function (_super) {
  83477. __extends(GenericController, _super);
  83478. /**
  83479. * Creates a new GenericController from a gamepad
  83480. * @param vrGamepad the gamepad that the controller should be created from
  83481. */
  83482. function GenericController(vrGamepad) {
  83483. return _super.call(this, vrGamepad) || this;
  83484. }
  83485. /**
  83486. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  83487. * @param scene scene in which to add meshes
  83488. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  83489. */
  83490. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  83491. var _this = this;
  83492. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  83493. _this._defaultModel = newMeshes[1];
  83494. _this.attachToMesh(_this._defaultModel);
  83495. if (meshLoaded) {
  83496. meshLoaded(_this._defaultModel);
  83497. }
  83498. });
  83499. };
  83500. /**
  83501. * Called once for each button that changed state since the last frame
  83502. * @param buttonIdx Which button index changed
  83503. * @param state New state of the button
  83504. * @param changes Which properties on the state changed since last frame
  83505. */
  83506. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  83507. console.log("Button id: " + buttonIdx + "state: ");
  83508. console.dir(state);
  83509. };
  83510. /**
  83511. * Base Url for the controller model.
  83512. */
  83513. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  83514. /**
  83515. * File name for the controller model.
  83516. */
  83517. GenericController.MODEL_FILENAME = 'generic.babylon';
  83518. return GenericController;
  83519. }(BABYLON.WebVRController));
  83520. BABYLON.GenericController = GenericController;
  83521. })(BABYLON || (BABYLON = {}));
  83522. //# sourceMappingURL=babylon.genericController.js.map
  83523. var BABYLON;
  83524. (function (BABYLON) {
  83525. /**
  83526. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  83527. */
  83528. var LoadedMeshInfo = /** @class */ (function () {
  83529. function LoadedMeshInfo() {
  83530. /**
  83531. * Map of the button meshes contained in the controller
  83532. */
  83533. this.buttonMeshes = {};
  83534. /**
  83535. * Map of the axis meshes contained in the controller
  83536. */
  83537. this.axisMeshes = {};
  83538. }
  83539. return LoadedMeshInfo;
  83540. }());
  83541. /**
  83542. * Defines the WindowsMotionController object that the state of the windows motion controller
  83543. */
  83544. var WindowsMotionController = /** @class */ (function (_super) {
  83545. __extends(WindowsMotionController, _super);
  83546. /**
  83547. * Creates a new WindowsMotionController from a gamepad
  83548. * @param vrGamepad the gamepad that the controller should be created from
  83549. */
  83550. function WindowsMotionController(vrGamepad) {
  83551. var _this = _super.call(this, vrGamepad) || this;
  83552. _this._mapping = {
  83553. // Semantic button names
  83554. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  83555. // A mapping of the button name to glTF model node name
  83556. // that should be transformed by button value.
  83557. buttonMeshNames: {
  83558. 'trigger': 'SELECT',
  83559. 'menu': 'MENU',
  83560. 'grip': 'GRASP',
  83561. 'thumbstick': 'THUMBSTICK_PRESS',
  83562. 'trackpad': 'TOUCHPAD_PRESS'
  83563. },
  83564. // This mapping is used to translate from the Motion Controller to Babylon semantics
  83565. buttonObservableNames: {
  83566. 'trigger': 'onTriggerStateChangedObservable',
  83567. 'menu': 'onSecondaryButtonStateChangedObservable',
  83568. 'grip': 'onMainButtonStateChangedObservable',
  83569. 'thumbstick': 'onPadStateChangedObservable',
  83570. 'trackpad': 'onTrackpadChangedObservable'
  83571. },
  83572. // A mapping of the axis name to glTF model node name
  83573. // that should be transformed by axis value.
  83574. // This array mirrors the browserGamepad.axes array, such that
  83575. // the mesh corresponding to axis 0 is in this array index 0.
  83576. axisMeshNames: [
  83577. 'THUMBSTICK_X',
  83578. 'THUMBSTICK_Y',
  83579. 'TOUCHPAD_TOUCH_X',
  83580. 'TOUCHPAD_TOUCH_Y'
  83581. ],
  83582. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  83583. };
  83584. /**
  83585. * Fired when the trackpad on this controller is clicked
  83586. */
  83587. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  83588. /**
  83589. * Fired when the trackpad on this controller is modified
  83590. */
  83591. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  83592. /**
  83593. * The current x and y values of this controller's trackpad
  83594. */
  83595. _this.trackpad = { x: 0, y: 0 };
  83596. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  83597. _this._loadedMeshInfo = null;
  83598. return _this;
  83599. }
  83600. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  83601. /**
  83602. * Fired when the trigger on this controller is modified
  83603. */
  83604. get: function () {
  83605. return this.onTriggerStateChangedObservable;
  83606. },
  83607. enumerable: true,
  83608. configurable: true
  83609. });
  83610. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  83611. /**
  83612. * Fired when the menu button on this controller is modified
  83613. */
  83614. get: function () {
  83615. return this.onSecondaryButtonStateChangedObservable;
  83616. },
  83617. enumerable: true,
  83618. configurable: true
  83619. });
  83620. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  83621. /**
  83622. * Fired when the grip button on this controller is modified
  83623. */
  83624. get: function () {
  83625. return this.onMainButtonStateChangedObservable;
  83626. },
  83627. enumerable: true,
  83628. configurable: true
  83629. });
  83630. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  83631. /**
  83632. * Fired when the thumbstick button on this controller is modified
  83633. */
  83634. get: function () {
  83635. return this.onPadStateChangedObservable;
  83636. },
  83637. enumerable: true,
  83638. configurable: true
  83639. });
  83640. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  83641. /**
  83642. * Fired when the touchpad button on this controller is modified
  83643. */
  83644. get: function () {
  83645. return this.onTrackpadChangedObservable;
  83646. },
  83647. enumerable: true,
  83648. configurable: true
  83649. });
  83650. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  83651. /**
  83652. * Fired when the touchpad values on this controller are modified
  83653. */
  83654. get: function () {
  83655. return this.onTrackpadValuesChangedObservable;
  83656. },
  83657. enumerable: true,
  83658. configurable: true
  83659. });
  83660. WindowsMotionController.prototype._updateTrackpad = function () {
  83661. if (this.browserGamepad.axes && (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y)) {
  83662. this.trackpad.x = this.browserGamepad["axes"][2];
  83663. this.trackpad.y = this.browserGamepad["axes"][3];
  83664. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  83665. }
  83666. };
  83667. /**
  83668. * Called once per frame by the engine.
  83669. */
  83670. WindowsMotionController.prototype.update = function () {
  83671. _super.prototype.update.call(this);
  83672. if (this.browserGamepad.axes) {
  83673. this._updateTrackpad();
  83674. // Only need to animate axes if there is a loaded mesh
  83675. if (this._loadedMeshInfo) {
  83676. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  83677. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  83678. }
  83679. }
  83680. }
  83681. };
  83682. /**
  83683. * Called once for each button that changed state since the last frame
  83684. * @param buttonIdx Which button index changed
  83685. * @param state New state of the button
  83686. * @param changes Which properties on the state changed since last frame
  83687. */
  83688. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  83689. var buttonName = this._mapping.buttons[buttonIdx];
  83690. if (!buttonName) {
  83691. return;
  83692. }
  83693. // Update the trackpad to ensure trackpad.x/y are accurate during button events between frames
  83694. this._updateTrackpad();
  83695. // Only emit events for buttons that we know how to map from index to name
  83696. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  83697. if (observable) {
  83698. observable.notifyObservers(state);
  83699. }
  83700. this._lerpButtonTransform(buttonName, state.value);
  83701. };
  83702. /**
  83703. * Moves the buttons on the controller mesh based on their current state
  83704. * @param buttonName the name of the button to move
  83705. * @param buttonValue the value of the button which determines the buttons new position
  83706. */
  83707. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  83708. // If there is no loaded mesh, there is nothing to transform.
  83709. if (!this._loadedMeshInfo) {
  83710. return;
  83711. }
  83712. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  83713. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  83714. return;
  83715. }
  83716. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  83717. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  83718. };
  83719. /**
  83720. * Moves the axis on the controller mesh based on its current state
  83721. * @param axis the index of the axis
  83722. * @param axisValue the value of the axis which determines the meshes new position
  83723. * @hidden
  83724. */
  83725. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  83726. if (!this._loadedMeshInfo) {
  83727. return;
  83728. }
  83729. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  83730. if (!meshInfo) {
  83731. return;
  83732. }
  83733. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  83734. return;
  83735. }
  83736. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  83737. var lerpValue = axisValue * 0.5 + 0.5;
  83738. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  83739. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  83740. };
  83741. /**
  83742. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  83743. * @param scene scene in which to add meshes
  83744. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  83745. */
  83746. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  83747. var _this = this;
  83748. if (forceDefault === void 0) { forceDefault = false; }
  83749. var path;
  83750. var filename;
  83751. // Checking if GLB loader is present
  83752. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  83753. // Determine the device specific folder based on the ID suffix
  83754. var device = 'default';
  83755. if (this.id && !forceDefault) {
  83756. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  83757. device = ((match && match[0]) || device);
  83758. }
  83759. // Hand
  83760. if (this.hand === 'left') {
  83761. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  83762. }
  83763. else { // Right is the default if no hand is specified
  83764. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  83765. }
  83766. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  83767. }
  83768. else {
  83769. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  83770. path = BABYLON.GenericController.MODEL_BASE_URL;
  83771. filename = BABYLON.GenericController.MODEL_FILENAME;
  83772. }
  83773. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  83774. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  83775. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  83776. if (!_this._loadedMeshInfo) {
  83777. return;
  83778. }
  83779. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  83780. _this.attachToMesh(_this._defaultModel);
  83781. if (meshLoaded) {
  83782. meshLoaded(_this._defaultModel);
  83783. }
  83784. }, null, function (scene, message) {
  83785. BABYLON.Tools.Log(message);
  83786. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  83787. if (!forceDefault) {
  83788. _this.initControllerMesh(scene, meshLoaded, true);
  83789. }
  83790. });
  83791. };
  83792. /**
  83793. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  83794. * can be transformed by button presses and axes values, based on this._mapping.
  83795. *
  83796. * @param scene scene in which the meshes exist
  83797. * @param meshes list of meshes that make up the controller model to process
  83798. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  83799. */
  83800. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  83801. var loadedMeshInfo = null;
  83802. // Create a new mesh to contain the glTF hierarchy
  83803. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  83804. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  83805. var childMesh = null;
  83806. for (var i = 0; i < meshes.length; i++) {
  83807. var mesh = meshes[i];
  83808. if (!mesh.parent) {
  83809. // Exclude controller meshes from picking results
  83810. mesh.isPickable = false;
  83811. // Handle root node, attach to the new parentMesh
  83812. childMesh = mesh;
  83813. break;
  83814. }
  83815. }
  83816. if (childMesh) {
  83817. childMesh.setParent(parentMesh);
  83818. // Create our mesh info. Note that this method will always return non-null.
  83819. loadedMeshInfo = this.createMeshInfo(parentMesh);
  83820. }
  83821. else {
  83822. BABYLON.Tools.Warn('Could not find root node in model file.');
  83823. }
  83824. return loadedMeshInfo;
  83825. };
  83826. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  83827. var loadedMeshInfo = new LoadedMeshInfo();
  83828. var i;
  83829. loadedMeshInfo.rootNode = rootNode;
  83830. // Reset the caches
  83831. loadedMeshInfo.buttonMeshes = {};
  83832. loadedMeshInfo.axisMeshes = {};
  83833. // Button Meshes
  83834. for (i = 0; i < this._mapping.buttons.length; i++) {
  83835. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  83836. if (!buttonMeshName) {
  83837. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  83838. continue;
  83839. }
  83840. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  83841. if (!buttonMesh) {
  83842. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  83843. continue;
  83844. }
  83845. var buttonMeshInfo = {
  83846. index: i,
  83847. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  83848. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  83849. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  83850. };
  83851. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  83852. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  83853. }
  83854. else {
  83855. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  83856. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  83857. '(VALUE: ' + !!buttonMeshInfo.value +
  83858. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  83859. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  83860. ')');
  83861. }
  83862. }
  83863. // Axis Meshes
  83864. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  83865. var axisMeshName = this._mapping.axisMeshNames[i];
  83866. if (!axisMeshName) {
  83867. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  83868. continue;
  83869. }
  83870. var axisMesh = getChildByName(rootNode, axisMeshName);
  83871. if (!axisMesh) {
  83872. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  83873. continue;
  83874. }
  83875. var axisMeshInfo = {
  83876. index: i,
  83877. value: getImmediateChildByName(axisMesh, 'VALUE'),
  83878. min: getImmediateChildByName(axisMesh, 'MIN'),
  83879. max: getImmediateChildByName(axisMesh, 'MAX')
  83880. };
  83881. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  83882. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  83883. }
  83884. else {
  83885. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  83886. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  83887. '(VALUE: ' + !!axisMeshInfo.value +
  83888. ', MIN: ' + !!axisMeshInfo.min +
  83889. ', MAX:' + !!axisMeshInfo.max +
  83890. ')');
  83891. }
  83892. }
  83893. // Pointing Ray
  83894. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  83895. if (!loadedMeshInfo.pointingPoseNode) {
  83896. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  83897. }
  83898. else {
  83899. this._pointingPoseNode = loadedMeshInfo.pointingPoseNode;
  83900. }
  83901. return loadedMeshInfo;
  83902. // Look through all children recursively. This will return null if no mesh exists with the given name.
  83903. function getChildByName(node, name) {
  83904. return node.getChildren(function (n) { return n.name === name; }, false)[0];
  83905. }
  83906. // Look through only immediate children. This will return null if no mesh exists with the given name.
  83907. function getImmediateChildByName(node, name) {
  83908. return node.getChildren(function (n) { return n.name == name; }, true)[0];
  83909. }
  83910. };
  83911. /**
  83912. * Gets the ray of the controller in the direction the controller is pointing
  83913. * @param length the length the resulting ray should be
  83914. * @returns a ray in the direction the controller is pointing
  83915. */
  83916. WindowsMotionController.prototype.getForwardRay = function (length) {
  83917. if (length === void 0) { length = 100; }
  83918. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  83919. return _super.prototype.getForwardRay.call(this, length);
  83920. }
  83921. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  83922. var origin = m.getTranslation();
  83923. var forward = new BABYLON.Vector3(0, 0, -1);
  83924. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  83925. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  83926. return new BABYLON.Ray(origin, direction, length);
  83927. };
  83928. /**
  83929. * Disposes of the controller
  83930. */
  83931. WindowsMotionController.prototype.dispose = function () {
  83932. _super.prototype.dispose.call(this);
  83933. this.onTrackpadChangedObservable.clear();
  83934. };
  83935. /**
  83936. * The base url used to load the left and right controller models
  83937. */
  83938. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  83939. /**
  83940. * The name of the left controller model file
  83941. */
  83942. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  83943. /**
  83944. * The name of the right controller model file
  83945. */
  83946. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  83947. /**
  83948. * The controller name prefix for this controller type
  83949. */
  83950. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  83951. /**
  83952. * The controller id pattern for this controller type
  83953. */
  83954. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  83955. return WindowsMotionController;
  83956. }(BABYLON.WebVRController));
  83957. BABYLON.WindowsMotionController = WindowsMotionController;
  83958. })(BABYLON || (BABYLON = {}));
  83959. //# sourceMappingURL=babylon.windowsMotionController.js.map
  83960. var BABYLON;
  83961. (function (BABYLON) {
  83962. /**
  83963. * Gear VR Controller
  83964. */
  83965. var GearVRController = /** @class */ (function (_super) {
  83966. __extends(GearVRController, _super);
  83967. /**
  83968. * Creates a new GearVRController from a gamepad
  83969. * @param vrGamepad the gamepad that the controller should be created from
  83970. */
  83971. function GearVRController(vrGamepad) {
  83972. var _this = _super.call(this, vrGamepad) || this;
  83973. _this._buttonIndexToObservableNameMap = [
  83974. 'onTrackpadChangedObservable',
  83975. 'onTriggerStateChangedObservable' // Trigger
  83976. ];
  83977. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  83978. // Initial starting position defaults to where hand would be (incase of only 3dof controller)
  83979. _this._calculatedPosition = new BABYLON.Vector3(_this.hand == "left" ? -0.15 : 0.15, -0.5, 0.25);
  83980. _this._disableTrackPosition(_this._calculatedPosition);
  83981. return _this;
  83982. }
  83983. /**
  83984. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  83985. * @param scene scene in which to add meshes
  83986. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  83987. */
  83988. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  83989. var _this = this;
  83990. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  83991. // Offset the controller so it will rotate around the users wrist
  83992. var mesh = new BABYLON.Mesh("", scene);
  83993. newMeshes[1].parent = mesh;
  83994. newMeshes[1].position.z = -0.15;
  83995. _this._defaultModel = mesh;
  83996. _this.attachToMesh(_this._defaultModel);
  83997. if (meshLoaded) {
  83998. meshLoaded(_this._defaultModel);
  83999. }
  84000. });
  84001. };
  84002. /**
  84003. * Called once for each button that changed state since the last frame
  84004. * @param buttonIdx Which button index changed
  84005. * @param state New state of the button
  84006. * @param changes Which properties on the state changed since last frame
  84007. */
  84008. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  84009. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  84010. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  84011. // Only emit events for buttons that we know how to map from index to observable
  84012. var observable = this[observableName];
  84013. if (observable) {
  84014. observable.notifyObservers(state);
  84015. }
  84016. }
  84017. };
  84018. /**
  84019. * Base Url for the controller model.
  84020. */
  84021. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  84022. /**
  84023. * File name for the controller model.
  84024. */
  84025. GearVRController.MODEL_FILENAME = 'generic.babylon';
  84026. /**
  84027. * Gamepad Id prefix used to identify this controller.
  84028. */
  84029. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  84030. return GearVRController;
  84031. }(BABYLON.WebVRController));
  84032. BABYLON.GearVRController = GearVRController;
  84033. })(BABYLON || (BABYLON = {}));
  84034. //# sourceMappingURL=babylon.gearVRController.js.map
  84035. var BABYLON;
  84036. (function (BABYLON) {
  84037. /**
  84038. * Google Daydream controller
  84039. */
  84040. var DaydreamController = /** @class */ (function (_super) {
  84041. __extends(DaydreamController, _super);
  84042. /**
  84043. * Creates a new DaydreamController from a gamepad
  84044. * @param vrGamepad the gamepad that the controller should be created from
  84045. */
  84046. function DaydreamController(vrGamepad) {
  84047. var _this = _super.call(this, vrGamepad) || this;
  84048. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  84049. return _this;
  84050. }
  84051. /**
  84052. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  84053. * @param scene scene in which to add meshes
  84054. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  84055. */
  84056. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  84057. var _this = this;
  84058. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  84059. _this._defaultModel = newMeshes[1];
  84060. _this.attachToMesh(_this._defaultModel);
  84061. if (meshLoaded) {
  84062. meshLoaded(_this._defaultModel);
  84063. }
  84064. });
  84065. };
  84066. /**
  84067. * Called once for each button that changed state since the last frame
  84068. * @param buttonIdx Which button index changed
  84069. * @param state New state of the button
  84070. * @param changes Which properties on the state changed since last frame
  84071. */
  84072. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  84073. // Daydream controller only has 1 GamepadButton (on the trackpad).
  84074. if (buttonIdx === 0) {
  84075. var observable = this.onTriggerStateChangedObservable;
  84076. if (observable) {
  84077. observable.notifyObservers(state);
  84078. }
  84079. }
  84080. else {
  84081. // If the app or home buttons are ever made available
  84082. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  84083. }
  84084. };
  84085. /**
  84086. * Base Url for the controller model.
  84087. */
  84088. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  84089. /**
  84090. * File name for the controller model.
  84091. */
  84092. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  84093. /**
  84094. * Gamepad Id prefix used to identify Daydream Controller.
  84095. */
  84096. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  84097. return DaydreamController;
  84098. }(BABYLON.WebVRController));
  84099. BABYLON.DaydreamController = DaydreamController;
  84100. })(BABYLON || (BABYLON = {}));
  84101. //# sourceMappingURL=babylon.daydreamController.js.map
  84102. var BABYLON;
  84103. (function (BABYLON) {
  84104. Object.defineProperty(BABYLON.Scene.prototype, "gamepadManager", {
  84105. get: function () {
  84106. if (!this._gamepadManager) {
  84107. this._gamepadManager = new BABYLON.GamepadManager(this);
  84108. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_GAMEPAD);
  84109. if (!component) {
  84110. component = new GamepadSystemSceneComponent(this);
  84111. this._addComponent(component);
  84112. }
  84113. }
  84114. return this._gamepadManager;
  84115. },
  84116. enumerable: true,
  84117. configurable: true
  84118. });
  84119. /**
  84120. * Adds a gamepad to the free camera inputs manager
  84121. */
  84122. BABYLON.FreeCameraInputsManager.prototype.addGamepad = function () {
  84123. this.add(new BABYLON.FreeCameraGamepadInput());
  84124. return this;
  84125. };
  84126. /**
  84127. * Adds a gamepad to the arc rotate camera inputs manager
  84128. */
  84129. BABYLON.ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  84130. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  84131. return this;
  84132. };
  84133. /**
  84134. * Defines the gamepad scene component responsible to manage gamepads in a given scene
  84135. */
  84136. var GamepadSystemSceneComponent = /** @class */ (function () {
  84137. /**
  84138. * Creates a new instance of the component for the given scene
  84139. * @param scene Defines the scene to register the component in
  84140. */
  84141. function GamepadSystemSceneComponent(scene) {
  84142. /**
  84143. * The component name helpfull to identify the component in the list of scene components.
  84144. */
  84145. this.name = BABYLON.SceneComponentConstants.NAME_GAMEPAD;
  84146. this.scene = scene;
  84147. }
  84148. /**
  84149. * Registers the component in a given scene
  84150. */
  84151. GamepadSystemSceneComponent.prototype.register = function () {
  84152. this.scene._beforeCameraUpdateStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD, this, this._beforeCameraUpdate);
  84153. };
  84154. /**
  84155. * Rebuilds the elements related to this component in case of
  84156. * context lost for instance.
  84157. */
  84158. GamepadSystemSceneComponent.prototype.rebuild = function () {
  84159. // Nothing to do for gamepads
  84160. };
  84161. /**
  84162. * Disposes the component and the associated ressources
  84163. */
  84164. GamepadSystemSceneComponent.prototype.dispose = function () {
  84165. var gamepadManager = this.scene._gamepadManager;
  84166. if (gamepadManager) {
  84167. gamepadManager.dispose();
  84168. this.scene._gamepadManager = null;
  84169. }
  84170. };
  84171. GamepadSystemSceneComponent.prototype._beforeCameraUpdate = function () {
  84172. var gamepadManager = this.scene._gamepadManager;
  84173. if (gamepadManager && gamepadManager._isMonitoring) {
  84174. gamepadManager._checkGamepadsStatus();
  84175. }
  84176. };
  84177. return GamepadSystemSceneComponent;
  84178. }());
  84179. BABYLON.GamepadSystemSceneComponent = GamepadSystemSceneComponent;
  84180. })(BABYLON || (BABYLON = {}));
  84181. //# sourceMappingURL=babylon.gamepadSceneComponent.js.map
  84182. var BABYLON;
  84183. (function (BABYLON) {
  84184. BABYLON.Node.AddNodeConstructor("FollowCamera", function (name, scene) {
  84185. return function () { return new FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  84186. });
  84187. BABYLON.Node.AddNodeConstructor("ArcFollowCamera", function (name, scene) {
  84188. return function () { return new ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  84189. });
  84190. /**
  84191. * A follow camera takes a mesh as a target and follows it as it moves. Both a free camera version followCamera and
  84192. * an arc rotate version arcFollowCamera are available.
  84193. * @see http://doc.babylonjs.com/features/cameras#follow-camera
  84194. */
  84195. var FollowCamera = /** @class */ (function (_super) {
  84196. __extends(FollowCamera, _super);
  84197. /**
  84198. * Instantiates the follow camera.
  84199. * @see http://doc.babylonjs.com/features/cameras#follow-camera
  84200. * @param name Define the name of the camera in the scene
  84201. * @param position Define the position of the camera
  84202. * @param scene Define the scene the camera belong to
  84203. * @param lockedTarget Define the target of the camera
  84204. */
  84205. function FollowCamera(name, position, scene, lockedTarget) {
  84206. if (lockedTarget === void 0) { lockedTarget = null; }
  84207. var _this = _super.call(this, name, position, scene) || this;
  84208. /**
  84209. * Distance the follow camera should follow an object at
  84210. */
  84211. _this.radius = 12;
  84212. /**
  84213. * Define a rotation offset between the camera and the object it follows
  84214. */
  84215. _this.rotationOffset = 0;
  84216. /**
  84217. * Define a height offset between the camera and the object it follows.
  84218. * It can help following an object from the top (like a car chaing a plane)
  84219. */
  84220. _this.heightOffset = 4;
  84221. /**
  84222. * Define how fast the camera can accelerate to follow it s target.
  84223. */
  84224. _this.cameraAcceleration = 0.05;
  84225. /**
  84226. * Define the speed limit of the camera following an object.
  84227. */
  84228. _this.maxCameraSpeed = 20;
  84229. _this.lockedTarget = lockedTarget;
  84230. return _this;
  84231. }
  84232. FollowCamera.prototype._follow = function (cameraTarget) {
  84233. if (!cameraTarget) {
  84234. return;
  84235. }
  84236. var yRotation;
  84237. if (cameraTarget.rotationQuaternion) {
  84238. var rotMatrix = new BABYLON.Matrix();
  84239. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  84240. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  84241. }
  84242. else {
  84243. yRotation = cameraTarget.rotation.y;
  84244. }
  84245. var radians = BABYLON.Tools.ToRadians(this.rotationOffset) + yRotation;
  84246. var targetPosition = cameraTarget.getAbsolutePosition();
  84247. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  84248. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  84249. var dx = targetX - this.position.x;
  84250. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  84251. var dz = (targetZ) - this.position.z;
  84252. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  84253. var vy = dy * this.cameraAcceleration;
  84254. var vz = dz * this.cameraAcceleration * 2;
  84255. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  84256. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  84257. }
  84258. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  84259. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  84260. }
  84261. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  84262. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  84263. }
  84264. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  84265. this.setTarget(targetPosition);
  84266. };
  84267. /** @hidden */
  84268. FollowCamera.prototype._checkInputs = function () {
  84269. _super.prototype._checkInputs.call(this);
  84270. if (this.lockedTarget) {
  84271. this._follow(this.lockedTarget);
  84272. }
  84273. };
  84274. /**
  84275. * Gets the camera class name.
  84276. * @returns the class name
  84277. */
  84278. FollowCamera.prototype.getClassName = function () {
  84279. return "FollowCamera";
  84280. };
  84281. __decorate([
  84282. BABYLON.serialize()
  84283. ], FollowCamera.prototype, "radius", void 0);
  84284. __decorate([
  84285. BABYLON.serialize()
  84286. ], FollowCamera.prototype, "rotationOffset", void 0);
  84287. __decorate([
  84288. BABYLON.serialize()
  84289. ], FollowCamera.prototype, "heightOffset", void 0);
  84290. __decorate([
  84291. BABYLON.serialize()
  84292. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  84293. __decorate([
  84294. BABYLON.serialize()
  84295. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  84296. __decorate([
  84297. BABYLON.serializeAsMeshReference("lockedTargetId")
  84298. ], FollowCamera.prototype, "lockedTarget", void 0);
  84299. return FollowCamera;
  84300. }(BABYLON.TargetCamera));
  84301. BABYLON.FollowCamera = FollowCamera;
  84302. /**
  84303. * Arc Rotate version of the follow camera.
  84304. * It still follows a Defined mesh but in an Arc Rotate Camera fashion.
  84305. * @see http://doc.babylonjs.com/features/cameras#follow-camera
  84306. */
  84307. var ArcFollowCamera = /** @class */ (function (_super) {
  84308. __extends(ArcFollowCamera, _super);
  84309. /**
  84310. * Instantiates a new ArcFollowCamera
  84311. * @see http://doc.babylonjs.com/features/cameras#follow-camera
  84312. * @param name Define the name of the camera
  84313. * @param alpha Define the rotation angle of the camera around the logitudinal axis
  84314. * @param beta Define the rotation angle of the camera around the elevation axis
  84315. * @param radius Define the radius of the camera from its target point
  84316. * @param target Define the target of the camera
  84317. * @param scene Define the scene the camera belongs to
  84318. */
  84319. function ArcFollowCamera(name,
  84320. /** The longitudinal angle of the camera */
  84321. alpha,
  84322. /** The latitudinal angle of the camera */
  84323. beta,
  84324. /** The radius of the camera from its target */
  84325. radius,
  84326. /** Define the camera target (the messh it should follow) */
  84327. target, scene) {
  84328. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  84329. _this.alpha = alpha;
  84330. _this.beta = beta;
  84331. _this.radius = radius;
  84332. _this.target = target;
  84333. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  84334. _this._follow();
  84335. return _this;
  84336. }
  84337. ArcFollowCamera.prototype._follow = function () {
  84338. if (!this.target) {
  84339. return;
  84340. }
  84341. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  84342. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  84343. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  84344. var targetPosition = this.target.getAbsolutePosition();
  84345. this.position = targetPosition.add(this._cartesianCoordinates);
  84346. this.setTarget(targetPosition);
  84347. };
  84348. /** @hidden */
  84349. ArcFollowCamera.prototype._checkInputs = function () {
  84350. _super.prototype._checkInputs.call(this);
  84351. this._follow();
  84352. };
  84353. /**
  84354. * Returns the class name of the object.
  84355. * It is mostly used internally for serialization purposes.
  84356. */
  84357. ArcFollowCamera.prototype.getClassName = function () {
  84358. return "ArcFollowCamera";
  84359. };
  84360. return ArcFollowCamera;
  84361. }(BABYLON.TargetCamera));
  84362. BABYLON.ArcFollowCamera = ArcFollowCamera;
  84363. })(BABYLON || (BABYLON = {}));
  84364. //# sourceMappingURL=babylon.followCamera.js.map
  84365. var BABYLON;
  84366. (function (BABYLON) {
  84367. /**
  84368. * 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,
  84369. * which still works and will still be found in many Playgrounds.
  84370. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  84371. */
  84372. var UniversalCamera = /** @class */ (function (_super) {
  84373. __extends(UniversalCamera, _super);
  84374. /**
  84375. * 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,
  84376. * which still works and will still be found in many Playgrounds.
  84377. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  84378. * @param name Define the name of the camera in the scene
  84379. * @param position Define the start position of the camera in the scene
  84380. * @param scene Define the scene the camera belongs to
  84381. */
  84382. function UniversalCamera(name, position, scene) {
  84383. var _this = _super.call(this, name, position, scene) || this;
  84384. _this.inputs.addGamepad();
  84385. return _this;
  84386. }
  84387. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  84388. /**
  84389. * Defines the gamepad rotation sensiblity.
  84390. * This is the threshold from when rotation starts to be accounted for to prevent jittering.
  84391. */
  84392. get: function () {
  84393. var gamepad = this.inputs.attached["gamepad"];
  84394. if (gamepad) {
  84395. return gamepad.gamepadAngularSensibility;
  84396. }
  84397. return 0;
  84398. },
  84399. set: function (value) {
  84400. var gamepad = this.inputs.attached["gamepad"];
  84401. if (gamepad) {
  84402. gamepad.gamepadAngularSensibility = value;
  84403. }
  84404. },
  84405. enumerable: true,
  84406. configurable: true
  84407. });
  84408. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  84409. /**
  84410. * Defines the gamepad move sensiblity.
  84411. * This is the threshold from when moving starts to be accounted for for to prevent jittering.
  84412. */
  84413. get: function () {
  84414. var gamepad = this.inputs.attached["gamepad"];
  84415. if (gamepad) {
  84416. return gamepad.gamepadMoveSensibility;
  84417. }
  84418. return 0;
  84419. },
  84420. set: function (value) {
  84421. var gamepad = this.inputs.attached["gamepad"];
  84422. if (gamepad) {
  84423. gamepad.gamepadMoveSensibility = value;
  84424. }
  84425. },
  84426. enumerable: true,
  84427. configurable: true
  84428. });
  84429. /**
  84430. * Gets the current object class name.
  84431. * @return the class name
  84432. */
  84433. UniversalCamera.prototype.getClassName = function () {
  84434. return "UniversalCamera";
  84435. };
  84436. return UniversalCamera;
  84437. }(BABYLON.TouchCamera));
  84438. BABYLON.UniversalCamera = UniversalCamera;
  84439. })(BABYLON || (BABYLON = {}));
  84440. //# sourceMappingURL=babylon.universalCamera.js.map
  84441. var BABYLON;
  84442. (function (BABYLON) {
  84443. BABYLON.Node.AddNodeConstructor("GamepadCamera", function (name, scene) {
  84444. return function () { return new GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  84445. });
  84446. /**
  84447. * This represents a FPS type of camera. This is only here for back compat purpose.
  84448. * Please use the UniversalCamera instead as both are identical.
  84449. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  84450. */
  84451. var GamepadCamera = /** @class */ (function (_super) {
  84452. __extends(GamepadCamera, _super);
  84453. /**
  84454. * Instantiates a new Gamepad Camera
  84455. * This represents a FPS type of camera. This is only here for back compat purpose.
  84456. * Please use the UniversalCamera instead as both are identical.
  84457. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  84458. * @param name Define the name of the camera in the scene
  84459. * @param position Define the start position of the camera in the scene
  84460. * @param scene Define the scene the camera belongs to
  84461. */
  84462. function GamepadCamera(name, position, scene) {
  84463. return _super.call(this, name, position, scene) || this;
  84464. }
  84465. /**
  84466. * Gets the current object class name.
  84467. * @return the class name
  84468. */
  84469. GamepadCamera.prototype.getClassName = function () {
  84470. return "GamepadCamera";
  84471. };
  84472. return GamepadCamera;
  84473. }(BABYLON.UniversalCamera));
  84474. BABYLON.GamepadCamera = GamepadCamera;
  84475. })(BABYLON || (BABYLON = {}));
  84476. //# sourceMappingURL=babylon.gamepadCamera.js.map
  84477. var BABYLON;
  84478. (function (BABYLON) {
  84479. /**
  84480. * PostProcessRenderPipelineManager class
  84481. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  84482. */
  84483. var PostProcessRenderPipelineManager = /** @class */ (function () {
  84484. /**
  84485. * Initializes a PostProcessRenderPipelineManager
  84486. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  84487. */
  84488. function PostProcessRenderPipelineManager() {
  84489. this._renderPipelines = {};
  84490. }
  84491. /**
  84492. * Adds a pipeline to the manager
  84493. * @param renderPipeline The pipeline to add
  84494. */
  84495. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  84496. this._renderPipelines[renderPipeline._name] = renderPipeline;
  84497. };
  84498. /**
  84499. * Attaches a camera to the pipeline
  84500. * @param renderPipelineName The name of the pipeline to attach to
  84501. * @param cameras the camera to attach
  84502. * @param unique if the camera can be attached multiple times to the pipeline
  84503. */
  84504. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  84505. if (unique === void 0) { unique = false; }
  84506. var renderPipeline = this._renderPipelines[renderPipelineName];
  84507. if (!renderPipeline) {
  84508. return;
  84509. }
  84510. renderPipeline._attachCameras(cameras, unique);
  84511. };
  84512. /**
  84513. * Detaches a camera from the pipeline
  84514. * @param renderPipelineName The name of the pipeline to detach from
  84515. * @param cameras the camera to detach
  84516. */
  84517. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  84518. var renderPipeline = this._renderPipelines[renderPipelineName];
  84519. if (!renderPipeline) {
  84520. return;
  84521. }
  84522. renderPipeline._detachCameras(cameras);
  84523. };
  84524. /**
  84525. * Enables an effect by name on a pipeline
  84526. * @param renderPipelineName the name of the pipeline to enable the effect in
  84527. * @param renderEffectName the name of the effect to enable
  84528. * @param cameras the cameras that the effect should be enabled on
  84529. */
  84530. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  84531. var renderPipeline = this._renderPipelines[renderPipelineName];
  84532. if (!renderPipeline) {
  84533. return;
  84534. }
  84535. renderPipeline._enableEffect(renderEffectName, cameras);
  84536. };
  84537. /**
  84538. * Disables an effect by name on a pipeline
  84539. * @param renderPipelineName the name of the pipeline to disable the effect in
  84540. * @param renderEffectName the name of the effect to disable
  84541. * @param cameras the cameras that the effect should be disabled on
  84542. */
  84543. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  84544. var renderPipeline = this._renderPipelines[renderPipelineName];
  84545. if (!renderPipeline) {
  84546. return;
  84547. }
  84548. renderPipeline._disableEffect(renderEffectName, cameras);
  84549. };
  84550. /**
  84551. * Updates the state of all contained render pipelines and disposes of any non supported pipelines
  84552. */
  84553. PostProcessRenderPipelineManager.prototype.update = function () {
  84554. for (var renderPipelineName in this._renderPipelines) {
  84555. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  84556. var pipeline = this._renderPipelines[renderPipelineName];
  84557. if (!pipeline.isSupported) {
  84558. pipeline.dispose();
  84559. delete this._renderPipelines[renderPipelineName];
  84560. }
  84561. else {
  84562. pipeline._update();
  84563. }
  84564. }
  84565. }
  84566. };
  84567. /** @hidden */
  84568. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  84569. for (var renderPipelineName in this._renderPipelines) {
  84570. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  84571. var pipeline = this._renderPipelines[renderPipelineName];
  84572. pipeline._rebuild();
  84573. }
  84574. }
  84575. };
  84576. /**
  84577. * Disposes of the manager and pipelines
  84578. */
  84579. PostProcessRenderPipelineManager.prototype.dispose = function () {
  84580. for (var renderPipelineName in this._renderPipelines) {
  84581. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  84582. var pipeline = this._renderPipelines[renderPipelineName];
  84583. pipeline.dispose();
  84584. }
  84585. }
  84586. };
  84587. return PostProcessRenderPipelineManager;
  84588. }());
  84589. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  84590. })(BABYLON || (BABYLON = {}));
  84591. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  84592. var BABYLON;
  84593. (function (BABYLON) {
  84594. Object.defineProperty(BABYLON.Scene.prototype, "postProcessRenderPipelineManager", {
  84595. get: function () {
  84596. if (!this._postProcessRenderPipelineManager) {
  84597. // Register the G Buffer component to the scene.
  84598. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER);
  84599. if (!component) {
  84600. component = new PostProcessRenderPipelineManagerSceneComponent(this);
  84601. this._addComponent(component);
  84602. }
  84603. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  84604. }
  84605. return this._postProcessRenderPipelineManager;
  84606. },
  84607. enumerable: true,
  84608. configurable: true
  84609. });
  84610. /**
  84611. * Defines the Render Pipeline scene component responsible to rendering pipelines
  84612. */
  84613. var PostProcessRenderPipelineManagerSceneComponent = /** @class */ (function () {
  84614. /**
  84615. * Creates a new instance of the component for the given scene
  84616. * @param scene Defines the scene to register the component in
  84617. */
  84618. function PostProcessRenderPipelineManagerSceneComponent(scene) {
  84619. /**
  84620. * The component name helpfull to identify the component in the list of scene components.
  84621. */
  84622. this.name = BABYLON.SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER;
  84623. this.scene = scene;
  84624. }
  84625. /**
  84626. * Registers the component in a given scene
  84627. */
  84628. PostProcessRenderPipelineManagerSceneComponent.prototype.register = function () {
  84629. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER, this, this._gatherRenderTargets);
  84630. };
  84631. /**
  84632. * Rebuilds the elements related to this component in case of
  84633. * context lost for instance.
  84634. */
  84635. PostProcessRenderPipelineManagerSceneComponent.prototype.rebuild = function () {
  84636. if (this.scene._postProcessRenderPipelineManager) {
  84637. this.scene._postProcessRenderPipelineManager._rebuild();
  84638. }
  84639. };
  84640. /**
  84641. * Disposes the component and the associated ressources
  84642. */
  84643. PostProcessRenderPipelineManagerSceneComponent.prototype.dispose = function () {
  84644. if (this.scene._postProcessRenderPipelineManager) {
  84645. this.scene._postProcessRenderPipelineManager.dispose();
  84646. }
  84647. };
  84648. PostProcessRenderPipelineManagerSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  84649. if (this.scene._postProcessRenderPipelineManager) {
  84650. this.scene._postProcessRenderPipelineManager.update();
  84651. }
  84652. };
  84653. return PostProcessRenderPipelineManagerSceneComponent;
  84654. }());
  84655. BABYLON.PostProcessRenderPipelineManagerSceneComponent = PostProcessRenderPipelineManagerSceneComponent;
  84656. })(BABYLON || (BABYLON = {}));
  84657. //# sourceMappingURL=babylon.postProcessRenderPipelineManagerSceneComponent.js.map
  84658. var BABYLON;
  84659. (function (BABYLON) {
  84660. /**
  84661. * This represents a set of one or more post processes in Babylon.
  84662. * A post process can be used to apply a shader to a texture after it is rendered.
  84663. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  84664. */
  84665. var PostProcessRenderEffect = /** @class */ (function () {
  84666. /**
  84667. * Instantiates a post process render effect.
  84668. * A post process can be used to apply a shader to a texture after it is rendered.
  84669. * @param engine The engine the effect is tied to
  84670. * @param name The name of the effect
  84671. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  84672. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  84673. */
  84674. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  84675. this._name = name;
  84676. this._singleInstance = singleInstance || true;
  84677. this._getPostProcesses = getPostProcesses;
  84678. this._cameras = {};
  84679. this._indicesForCamera = {};
  84680. this._postProcesses = {};
  84681. }
  84682. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  84683. /**
  84684. * Checks if all the post processes in the effect are supported.
  84685. */
  84686. get: function () {
  84687. for (var index in this._postProcesses) {
  84688. if (this._postProcesses.hasOwnProperty(index)) {
  84689. var pps = this._postProcesses[index];
  84690. for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {
  84691. if (!pps[ppIndex].isSupported) {
  84692. return false;
  84693. }
  84694. }
  84695. }
  84696. }
  84697. return true;
  84698. },
  84699. enumerable: true,
  84700. configurable: true
  84701. });
  84702. /**
  84703. * Updates the current state of the effect
  84704. * @hidden
  84705. */
  84706. PostProcessRenderEffect.prototype._update = function () {
  84707. };
  84708. /**
  84709. * Attaches the effect on cameras
  84710. * @param cameras The camera to attach to.
  84711. * @hidden
  84712. */
  84713. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  84714. var _this = this;
  84715. var cameraKey;
  84716. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  84717. if (!cams) {
  84718. return;
  84719. }
  84720. for (var i = 0; i < cams.length; i++) {
  84721. var camera = cams[i];
  84722. var cameraName = camera.name;
  84723. if (this._singleInstance) {
  84724. cameraKey = 0;
  84725. }
  84726. else {
  84727. cameraKey = cameraName;
  84728. }
  84729. if (!this._postProcesses[cameraKey]) {
  84730. var postProcess = this._getPostProcesses();
  84731. if (postProcess) {
  84732. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  84733. }
  84734. }
  84735. if (!this._indicesForCamera[cameraName]) {
  84736. this._indicesForCamera[cameraName] = [];
  84737. }
  84738. this._postProcesses[cameraKey].forEach(function (postProcess) {
  84739. var index = camera.attachPostProcess(postProcess);
  84740. _this._indicesForCamera[cameraName].push(index);
  84741. });
  84742. if (!this._cameras[cameraName]) {
  84743. this._cameras[cameraName] = camera;
  84744. }
  84745. }
  84746. };
  84747. /**
  84748. * Detatches the effect on cameras
  84749. * @param cameras The camera to detatch from.
  84750. * @hidden
  84751. */
  84752. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  84753. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  84754. if (!cams) {
  84755. return;
  84756. }
  84757. for (var i = 0; i < cams.length; i++) {
  84758. var camera = cams[i];
  84759. var cameraName = camera.name;
  84760. var postProcesses = this._postProcesses[this._singleInstance ? 0 : cameraName];
  84761. if (postProcesses) {
  84762. postProcesses.forEach(function (postProcess) {
  84763. camera.detachPostProcess(postProcess);
  84764. });
  84765. }
  84766. if (this._cameras[cameraName]) {
  84767. this._cameras[cameraName] = null;
  84768. }
  84769. }
  84770. };
  84771. /**
  84772. * Enables the effect on given cameras
  84773. * @param cameras The camera to enable.
  84774. * @hidden
  84775. */
  84776. PostProcessRenderEffect.prototype._enable = function (cameras) {
  84777. var _this = this;
  84778. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  84779. if (!cams) {
  84780. return;
  84781. }
  84782. for (var i = 0; i < cams.length; i++) {
  84783. var camera = cams[i];
  84784. var cameraName = camera.name;
  84785. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  84786. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  84787. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  84788. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  84789. });
  84790. }
  84791. }
  84792. }
  84793. };
  84794. /**
  84795. * Disables the effect on the given cameras
  84796. * @param cameras The camera to disable.
  84797. * @hidden
  84798. */
  84799. PostProcessRenderEffect.prototype._disable = function (cameras) {
  84800. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  84801. if (!cams) {
  84802. return;
  84803. }
  84804. for (var i = 0; i < cams.length; i++) {
  84805. var camera = cams[i];
  84806. var cameraName = camera.name;
  84807. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  84808. camera.detachPostProcess(postProcess);
  84809. });
  84810. }
  84811. };
  84812. /**
  84813. * Gets a list of the post processes contained in the effect.
  84814. * @param camera The camera to get the post processes on.
  84815. * @returns The list of the post processes in the effect.
  84816. */
  84817. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  84818. if (this._singleInstance) {
  84819. return this._postProcesses[0];
  84820. }
  84821. else {
  84822. if (!camera) {
  84823. return null;
  84824. }
  84825. return this._postProcesses[camera.name];
  84826. }
  84827. };
  84828. return PostProcessRenderEffect;
  84829. }());
  84830. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  84831. })(BABYLON || (BABYLON = {}));
  84832. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  84833. var BABYLON;
  84834. (function (BABYLON) {
  84835. /**
  84836. * PostProcessRenderPipeline
  84837. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  84838. */
  84839. var PostProcessRenderPipeline = /** @class */ (function () {
  84840. /**
  84841. * Initializes a PostProcessRenderPipeline
  84842. * @param engine engine to add the pipeline to
  84843. * @param name name of the pipeline
  84844. */
  84845. function PostProcessRenderPipeline(engine, name) {
  84846. this.engine = engine;
  84847. this._name = name;
  84848. this._renderEffects = {};
  84849. this._renderEffectsForIsolatedPass = new Array();
  84850. this._cameras = [];
  84851. }
  84852. /**
  84853. * "PostProcessRenderPipeline"
  84854. * @returns "PostProcessRenderPipeline"
  84855. */
  84856. PostProcessRenderPipeline.prototype.getClassName = function () {
  84857. return "PostProcessRenderPipeline";
  84858. };
  84859. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  84860. /**
  84861. * If all the render effects in the pipeline are support
  84862. */
  84863. get: function () {
  84864. for (var renderEffectName in this._renderEffects) {
  84865. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  84866. if (!this._renderEffects[renderEffectName].isSupported) {
  84867. return false;
  84868. }
  84869. }
  84870. }
  84871. return true;
  84872. },
  84873. enumerable: true,
  84874. configurable: true
  84875. });
  84876. /**
  84877. * Adds an effect to the pipeline
  84878. * @param renderEffect the effect to add
  84879. */
  84880. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  84881. this._renderEffects[renderEffect._name] = renderEffect;
  84882. };
  84883. // private
  84884. /** @hidden */
  84885. PostProcessRenderPipeline.prototype._rebuild = function () {
  84886. };
  84887. /** @hidden */
  84888. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  84889. var renderEffects = this._renderEffects[renderEffectName];
  84890. if (!renderEffects) {
  84891. return;
  84892. }
  84893. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  84894. };
  84895. /** @hidden */
  84896. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  84897. var renderEffects = this._renderEffects[renderEffectName];
  84898. if (!renderEffects) {
  84899. return;
  84900. }
  84901. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  84902. };
  84903. /** @hidden */
  84904. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  84905. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  84906. if (!cams) {
  84907. return;
  84908. }
  84909. var indicesToDelete = [];
  84910. var i;
  84911. for (i = 0; i < cams.length; i++) {
  84912. var camera = cams[i];
  84913. var cameraName = camera.name;
  84914. if (this._cameras.indexOf(camera) === -1) {
  84915. this._cameras[cameraName] = camera;
  84916. }
  84917. else if (unique) {
  84918. indicesToDelete.push(i);
  84919. }
  84920. }
  84921. for (i = 0; i < indicesToDelete.length; i++) {
  84922. cameras.splice(indicesToDelete[i], 1);
  84923. }
  84924. for (var renderEffectName in this._renderEffects) {
  84925. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  84926. this._renderEffects[renderEffectName]._attachCameras(cams);
  84927. }
  84928. }
  84929. };
  84930. /** @hidden */
  84931. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  84932. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  84933. if (!cams) {
  84934. return;
  84935. }
  84936. for (var renderEffectName in this._renderEffects) {
  84937. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  84938. this._renderEffects[renderEffectName]._detachCameras(cams);
  84939. }
  84940. }
  84941. for (var i = 0; i < cams.length; i++) {
  84942. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  84943. }
  84944. };
  84945. /** @hidden */
  84946. PostProcessRenderPipeline.prototype._update = function () {
  84947. for (var renderEffectName in this._renderEffects) {
  84948. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  84949. this._renderEffects[renderEffectName]._update();
  84950. }
  84951. }
  84952. for (var i = 0; i < this._cameras.length; i++) {
  84953. var cameraName = this._cameras[i].name;
  84954. if (this._renderEffectsForIsolatedPass[cameraName]) {
  84955. this._renderEffectsForIsolatedPass[cameraName]._update();
  84956. }
  84957. }
  84958. };
  84959. /** @hidden */
  84960. PostProcessRenderPipeline.prototype._reset = function () {
  84961. this._renderEffects = {};
  84962. this._renderEffectsForIsolatedPass = new Array();
  84963. };
  84964. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  84965. // 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)
  84966. var effectKeys = Object.keys(this._renderEffects);
  84967. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  84968. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  84969. if (postProcesses) {
  84970. postProcesses[0].samples = sampleCount;
  84971. return true;
  84972. }
  84973. }
  84974. return false;
  84975. };
  84976. /**
  84977. * Disposes of the pipeline
  84978. */
  84979. PostProcessRenderPipeline.prototype.dispose = function () {
  84980. // Must be implemented by children
  84981. };
  84982. __decorate([
  84983. BABYLON.serialize()
  84984. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  84985. return PostProcessRenderPipeline;
  84986. }());
  84987. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  84988. })(BABYLON || (BABYLON = {}));
  84989. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  84990. var BABYLON;
  84991. (function (BABYLON) {
  84992. /**
  84993. * This represents a depth renderer in Babylon.
  84994. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  84995. */
  84996. var DepthRenderer = /** @class */ (function () {
  84997. /**
  84998. * Instantiates a depth renderer
  84999. * @param scene The scene the renderer belongs to
  85000. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  85001. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  85002. */
  85003. function DepthRenderer(scene, type, camera) {
  85004. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  85005. if (camera === void 0) { camera = null; }
  85006. var _this = this;
  85007. /**
  85008. * Specifiess that the depth renderer will only be used within
  85009. * the camera it is created for.
  85010. * This can help forcing its rendering during the camera processing.
  85011. */
  85012. this.useOnlyInActiveCamera = false;
  85013. this._scene = scene;
  85014. // Register the G Buffer component to the scene.
  85015. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_DEPTHRENDERER);
  85016. if (!component) {
  85017. component = new BABYLON.DepthRendererSceneComponent(scene);
  85018. scene._addComponent(component);
  85019. }
  85020. this._camera = camera;
  85021. var engine = scene.getEngine();
  85022. // Render target
  85023. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  85024. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85025. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85026. this._depthMap.refreshRate = 1;
  85027. this._depthMap.renderParticles = false;
  85028. this._depthMap.renderList = null;
  85029. // Camera to get depth map from to support multiple concurrent cameras
  85030. this._depthMap.activeCamera = this._camera;
  85031. this._depthMap.ignoreCameraViewport = true;
  85032. this._depthMap.useCameraPostProcesses = false;
  85033. // set default depth value to 1.0 (far away)
  85034. this._depthMap.onClearObservable.add(function (engine) {
  85035. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  85036. });
  85037. // Custom render function
  85038. var renderSubMesh = function (subMesh) {
  85039. var mesh = subMesh.getRenderingMesh();
  85040. var scene = _this._scene;
  85041. var engine = scene.getEngine();
  85042. var material = subMesh.getMaterial();
  85043. if (!material) {
  85044. return;
  85045. }
  85046. // Culling and reverse (right handed system)
  85047. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  85048. // Managing instances
  85049. var batch = mesh._getInstancesRenderList(subMesh._id);
  85050. if (batch.mustReturn) {
  85051. return;
  85052. }
  85053. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  85054. var camera = _this._camera || scene.activeCamera;
  85055. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  85056. engine.enableEffect(_this._effect);
  85057. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  85058. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  85059. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  85060. // Alpha test
  85061. if (material && material.needAlphaTesting()) {
  85062. var alphaTexture = material.getAlphaTestTexture();
  85063. if (alphaTexture) {
  85064. _this._effect.setTexture("diffuseSampler", alphaTexture);
  85065. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  85066. }
  85067. }
  85068. // Bones
  85069. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  85070. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  85071. }
  85072. // Draw
  85073. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  85074. }
  85075. };
  85076. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  85077. var index;
  85078. if (depthOnlySubMeshes.length) {
  85079. engine.setColorWrite(false);
  85080. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  85081. renderSubMesh(depthOnlySubMeshes.data[index]);
  85082. }
  85083. engine.setColorWrite(true);
  85084. }
  85085. for (index = 0; index < opaqueSubMeshes.length; index++) {
  85086. renderSubMesh(opaqueSubMeshes.data[index]);
  85087. }
  85088. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  85089. renderSubMesh(alphaTestSubMeshes.data[index]);
  85090. }
  85091. };
  85092. }
  85093. /**
  85094. * Creates the depth rendering effect and checks if the effect is ready.
  85095. * @param subMesh The submesh to be used to render the depth map of
  85096. * @param useInstances If multiple world instances should be used
  85097. * @returns if the depth renderer is ready to render the depth map
  85098. */
  85099. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  85100. var material = subMesh.getMaterial();
  85101. if (material.disableDepthWrite) {
  85102. return false;
  85103. }
  85104. var defines = [];
  85105. var attribs = [BABYLON.VertexBuffer.PositionKind];
  85106. var mesh = subMesh.getMesh();
  85107. // Alpha test
  85108. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  85109. defines.push("#define ALPHATEST");
  85110. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  85111. attribs.push(BABYLON.VertexBuffer.UVKind);
  85112. defines.push("#define UV1");
  85113. }
  85114. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  85115. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  85116. defines.push("#define UV2");
  85117. }
  85118. }
  85119. // Bones
  85120. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  85121. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  85122. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  85123. if (mesh.numBoneInfluencers > 4) {
  85124. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  85125. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  85126. }
  85127. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  85128. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  85129. }
  85130. else {
  85131. defines.push("#define NUM_BONE_INFLUENCERS 0");
  85132. }
  85133. // Instances
  85134. if (useInstances) {
  85135. defines.push("#define INSTANCES");
  85136. attribs.push("world0");
  85137. attribs.push("world1");
  85138. attribs.push("world2");
  85139. attribs.push("world3");
  85140. }
  85141. // Get correct effect
  85142. var join = defines.join("\n");
  85143. if (this._cachedDefines !== join) {
  85144. this._cachedDefines = join;
  85145. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  85146. }
  85147. return this._effect.isReady();
  85148. };
  85149. /**
  85150. * Gets the texture which the depth map will be written to.
  85151. * @returns The depth map texture
  85152. */
  85153. DepthRenderer.prototype.getDepthMap = function () {
  85154. return this._depthMap;
  85155. };
  85156. /**
  85157. * Disposes of the depth renderer.
  85158. */
  85159. DepthRenderer.prototype.dispose = function () {
  85160. this._depthMap.dispose();
  85161. };
  85162. return DepthRenderer;
  85163. }());
  85164. BABYLON.DepthRenderer = DepthRenderer;
  85165. })(BABYLON || (BABYLON = {}));
  85166. //# sourceMappingURL=babylon.depthRenderer.js.map
  85167. var BABYLON;
  85168. (function (BABYLON) {
  85169. BABYLON.Scene.prototype.enableDepthRenderer = function (camera) {
  85170. camera = camera || this.activeCamera;
  85171. if (!camera) {
  85172. throw "No camera available to enable depth renderer";
  85173. }
  85174. if (!this._depthRenderer) {
  85175. this._depthRenderer = {};
  85176. }
  85177. if (!this._depthRenderer[camera.id]) {
  85178. var textureType = 0;
  85179. if (this.getEngine().getCaps().textureHalfFloatRender) {
  85180. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  85181. }
  85182. else if (this.getEngine().getCaps().textureFloatRender) {
  85183. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  85184. }
  85185. else {
  85186. throw "Depth renderer does not support int texture type";
  85187. }
  85188. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  85189. }
  85190. return this._depthRenderer[camera.id];
  85191. };
  85192. BABYLON.Scene.prototype.disableDepthRenderer = function (camera) {
  85193. camera = camera || this.activeCamera;
  85194. if (!camera || !this._depthRenderer || !this._depthRenderer[camera.id]) {
  85195. return;
  85196. }
  85197. this._depthRenderer[camera.id].dispose();
  85198. delete this._depthRenderer[camera.id];
  85199. };
  85200. /**
  85201. * Defines the Depth Renderer scene component responsible to manage a depth buffer usefull
  85202. * in several rendering techniques.
  85203. */
  85204. var DepthRendererSceneComponent = /** @class */ (function () {
  85205. /**
  85206. * Creates a new instance of the component for the given scene
  85207. * @param scene Defines the scene to register the component in
  85208. */
  85209. function DepthRendererSceneComponent(scene) {
  85210. /**
  85211. * The component name helpfull to identify the component in the list of scene components.
  85212. */
  85213. this.name = BABYLON.SceneComponentConstants.NAME_DEPTHRENDERER;
  85214. this.scene = scene;
  85215. }
  85216. /**
  85217. * Registers the component in a given scene
  85218. */
  85219. DepthRendererSceneComponent.prototype.register = function () {
  85220. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_DEPTHRENDERER, this, this._gatherRenderTargets);
  85221. this.scene._gatherActiveCameraRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER, this, this._gatherActiveCameraRenderTargets);
  85222. };
  85223. /**
  85224. * Rebuilds the elements related to this component in case of
  85225. * context lost for instance.
  85226. */
  85227. DepthRendererSceneComponent.prototype.rebuild = function () {
  85228. // Nothing to do for this component
  85229. };
  85230. /**
  85231. * Disposes the component and the associated ressources
  85232. */
  85233. DepthRendererSceneComponent.prototype.dispose = function () {
  85234. for (var key in this.scene._depthRenderer) {
  85235. this.scene._depthRenderer[key].dispose();
  85236. }
  85237. };
  85238. DepthRendererSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  85239. if (this.scene._depthRenderer) {
  85240. for (var key in this.scene._depthRenderer) {
  85241. var depthRenderer = this.scene._depthRenderer[key];
  85242. if (!depthRenderer.useOnlyInActiveCamera) {
  85243. renderTargets.push(depthRenderer.getDepthMap());
  85244. }
  85245. }
  85246. }
  85247. };
  85248. DepthRendererSceneComponent.prototype._gatherActiveCameraRenderTargets = function (renderTargets) {
  85249. if (this.scene._depthRenderer) {
  85250. for (var key in this.scene._depthRenderer) {
  85251. var depthRenderer = this.scene._depthRenderer[key];
  85252. if (depthRenderer.useOnlyInActiveCamera && this.scene.activeCamera.id === key) {
  85253. renderTargets.push(depthRenderer.getDepthMap());
  85254. }
  85255. }
  85256. }
  85257. };
  85258. return DepthRendererSceneComponent;
  85259. }());
  85260. BABYLON.DepthRendererSceneComponent = DepthRendererSceneComponent;
  85261. })(BABYLON || (BABYLON = {}));
  85262. //# sourceMappingURL=babylon.depthRendererSceneComponent.js.map
  85263. var BABYLON;
  85264. (function (BABYLON) {
  85265. /**
  85266. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  85267. */
  85268. var GeometryBufferRenderer = /** @class */ (function () {
  85269. /**
  85270. * Creates a new G Buffer for the scene
  85271. * @param scene The scene the buffer belongs to
  85272. * @param ratio How big is the buffer related to the main canvas.
  85273. */
  85274. function GeometryBufferRenderer(scene, ratio) {
  85275. if (ratio === void 0) { ratio = 1; }
  85276. /**
  85277. * Dictionary used to store the previous transformation matrices of each rendered mesh
  85278. * in order to compute objects velocities when enableVelocity is set to "true"
  85279. * @hidden
  85280. */
  85281. this._previousTransformationMatrices = {};
  85282. this._enablePosition = false;
  85283. this._enableVelocity = false;
  85284. this._positionIndex = -1;
  85285. this._velocityIndex = -1;
  85286. this._scene = scene;
  85287. this._ratio = ratio;
  85288. // Register the G Buffer component to the scene.
  85289. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER);
  85290. if (!component) {
  85291. component = new BABYLON.GeometryBufferRendererSceneComponent(scene);
  85292. scene._addComponent(component);
  85293. }
  85294. // Render target
  85295. this._createRenderTargets();
  85296. }
  85297. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  85298. /**
  85299. * Set the render list (meshes to be rendered) used in the G buffer.
  85300. */
  85301. set: function (meshes) {
  85302. this._multiRenderTarget.renderList = meshes;
  85303. },
  85304. enumerable: true,
  85305. configurable: true
  85306. });
  85307. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  85308. /**
  85309. * Gets wether or not G buffer are supported by the running hardware.
  85310. * This requires draw buffer supports
  85311. */
  85312. get: function () {
  85313. return this._multiRenderTarget.isSupported;
  85314. },
  85315. enumerable: true,
  85316. configurable: true
  85317. });
  85318. /**
  85319. * Returns the index of the given texture type in the G-Buffer textures array
  85320. * @param textureType The texture type constant. For example GeometryBufferRenderer.POSITION_TEXTURE_INDEX
  85321. * @returns the index of the given texture type in the G-Buffer textures array
  85322. */
  85323. GeometryBufferRenderer.prototype.getTextureIndex = function (textureType) {
  85324. switch (textureType) {
  85325. case GeometryBufferRenderer.POSITION_TEXTURE_TYPE: return this._positionIndex;
  85326. case GeometryBufferRenderer.VELOCITY_TEXTURE_TYPE: return this._velocityIndex;
  85327. default: return -1;
  85328. }
  85329. };
  85330. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  85331. /**
  85332. * Gets a boolean indicating if objects positions are enabled for the G buffer.
  85333. */
  85334. get: function () {
  85335. return this._enablePosition;
  85336. },
  85337. /**
  85338. * Sets whether or not objects positions are enabled for the G buffer.
  85339. */
  85340. set: function (enable) {
  85341. this._enablePosition = enable;
  85342. this.dispose();
  85343. this._createRenderTargets();
  85344. },
  85345. enumerable: true,
  85346. configurable: true
  85347. });
  85348. Object.defineProperty(GeometryBufferRenderer.prototype, "enableVelocity", {
  85349. /**
  85350. * Gets a boolean indicating if objects velocities are enabled for the G buffer.
  85351. */
  85352. get: function () {
  85353. return this._enableVelocity;
  85354. },
  85355. /**
  85356. * Sets wether or not objects velocities are enabled for the G buffer.
  85357. */
  85358. set: function (enable) {
  85359. this._enableVelocity = enable;
  85360. this.dispose();
  85361. this._createRenderTargets();
  85362. },
  85363. enumerable: true,
  85364. configurable: true
  85365. });
  85366. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  85367. /**
  85368. * Gets the scene associated with the buffer.
  85369. */
  85370. get: function () {
  85371. return this._scene;
  85372. },
  85373. enumerable: true,
  85374. configurable: true
  85375. });
  85376. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  85377. /**
  85378. * Gets the ratio used by the buffer during its creation.
  85379. * How big is the buffer related to the main canvas.
  85380. */
  85381. get: function () {
  85382. return this._ratio;
  85383. },
  85384. enumerable: true,
  85385. configurable: true
  85386. });
  85387. /**
  85388. * Checks wether everything is ready to render a submesh to the G buffer.
  85389. * @param subMesh the submesh to check readiness for
  85390. * @param useInstances is the mesh drawn using instance or not
  85391. * @returns true if ready otherwise false
  85392. */
  85393. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  85394. var material = subMesh.getMaterial();
  85395. if (material && material.disableDepthWrite) {
  85396. return false;
  85397. }
  85398. var defines = [];
  85399. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  85400. var mesh = subMesh.getMesh();
  85401. // Alpha test
  85402. if (material && material.needAlphaTesting()) {
  85403. defines.push("#define ALPHATEST");
  85404. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  85405. attribs.push(BABYLON.VertexBuffer.UVKind);
  85406. defines.push("#define UV1");
  85407. }
  85408. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  85409. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  85410. defines.push("#define UV2");
  85411. }
  85412. }
  85413. // Buffers
  85414. if (this._enablePosition) {
  85415. defines.push("#define POSITION");
  85416. defines.push("#define POSITION_INDEX " + this._positionIndex);
  85417. }
  85418. if (this._enableVelocity) {
  85419. defines.push("#define VELOCITY");
  85420. defines.push("#define VELOCITY_INDEX " + this._velocityIndex);
  85421. }
  85422. // Bones
  85423. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  85424. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  85425. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  85426. if (mesh.numBoneInfluencers > 4) {
  85427. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  85428. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  85429. }
  85430. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  85431. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  85432. }
  85433. else {
  85434. defines.push("#define NUM_BONE_INFLUENCERS 0");
  85435. }
  85436. // Instances
  85437. if (useInstances) {
  85438. defines.push("#define INSTANCES");
  85439. attribs.push("world0");
  85440. attribs.push("world1");
  85441. attribs.push("world2");
  85442. attribs.push("world3");
  85443. }
  85444. // Setup textures count
  85445. defines.push("#define RENDER_TARGET_COUNT " + this._multiRenderTarget.textures.length);
  85446. // Get correct effect
  85447. var join = defines.join("\n");
  85448. if (this._cachedDefines !== join) {
  85449. this._cachedDefines = join;
  85450. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view", "previousWorldViewProjection"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  85451. }
  85452. return this._effect.isReady();
  85453. };
  85454. /**
  85455. * Gets the current underlying G Buffer.
  85456. * @returns the buffer
  85457. */
  85458. GeometryBufferRenderer.prototype.getGBuffer = function () {
  85459. return this._multiRenderTarget;
  85460. };
  85461. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  85462. /**
  85463. * Gets the number of samples used to render the buffer (anti aliasing).
  85464. */
  85465. get: function () {
  85466. return this._multiRenderTarget.samples;
  85467. },
  85468. /**
  85469. * Sets the number of samples used to render the buffer (anti aliasing).
  85470. */
  85471. set: function (value) {
  85472. this._multiRenderTarget.samples = value;
  85473. },
  85474. enumerable: true,
  85475. configurable: true
  85476. });
  85477. /**
  85478. * Disposes the renderer and frees up associated resources.
  85479. */
  85480. GeometryBufferRenderer.prototype.dispose = function () {
  85481. this.getGBuffer().dispose();
  85482. };
  85483. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  85484. var _this = this;
  85485. var engine = this._scene.getEngine();
  85486. var count = 2;
  85487. if (this._enablePosition) {
  85488. this._positionIndex = count;
  85489. count++;
  85490. }
  85491. if (this._enableVelocity) {
  85492. this._velocityIndex = count;
  85493. count++;
  85494. }
  85495. 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 });
  85496. if (!this.isSupported) {
  85497. return;
  85498. }
  85499. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85500. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85501. this._multiRenderTarget.refreshRate = 1;
  85502. this._multiRenderTarget.renderParticles = false;
  85503. this._multiRenderTarget.renderList = null;
  85504. // set default depth value to 1.0 (far away)
  85505. this._multiRenderTarget.onClearObservable.add(function (engine) {
  85506. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  85507. });
  85508. // Custom render function
  85509. var renderSubMesh = function (subMesh) {
  85510. var mesh = subMesh.getRenderingMesh();
  85511. var scene = _this._scene;
  85512. var engine = scene.getEngine();
  85513. var material = subMesh.getMaterial();
  85514. if (!material) {
  85515. return;
  85516. }
  85517. // Velocity
  85518. if (!_this._previousTransformationMatrices[mesh.uniqueId]) {
  85519. _this._previousTransformationMatrices[mesh.uniqueId] = BABYLON.Matrix.Identity();
  85520. }
  85521. // Culling
  85522. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  85523. // Managing instances
  85524. var batch = mesh._getInstancesRenderList(subMesh._id);
  85525. if (batch.mustReturn) {
  85526. return;
  85527. }
  85528. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  85529. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  85530. engine.enableEffect(_this._effect);
  85531. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  85532. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  85533. _this._effect.setMatrix("view", scene.getViewMatrix());
  85534. // Alpha test
  85535. if (material && material.needAlphaTesting()) {
  85536. var alphaTexture = material.getAlphaTestTexture();
  85537. if (alphaTexture) {
  85538. _this._effect.setTexture("diffuseSampler", alphaTexture);
  85539. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  85540. }
  85541. }
  85542. // Bones
  85543. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  85544. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  85545. }
  85546. // Velocity
  85547. _this._effect.setMatrix("previousWorldViewProjection", _this._previousTransformationMatrices[mesh.uniqueId]);
  85548. // Draw
  85549. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  85550. }
  85551. // Velocity
  85552. _this._previousTransformationMatrices[mesh.uniqueId] = mesh.getWorldMatrix().multiply(_this._scene.getTransformMatrix());
  85553. };
  85554. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  85555. var index;
  85556. if (depthOnlySubMeshes.length) {
  85557. engine.setColorWrite(false);
  85558. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  85559. renderSubMesh(depthOnlySubMeshes.data[index]);
  85560. }
  85561. engine.setColorWrite(true);
  85562. }
  85563. for (index = 0; index < opaqueSubMeshes.length; index++) {
  85564. renderSubMesh(opaqueSubMeshes.data[index]);
  85565. }
  85566. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  85567. renderSubMesh(alphaTestSubMeshes.data[index]);
  85568. }
  85569. };
  85570. };
  85571. /**
  85572. * Constant used to retrieve the position texture index in the G-Buffer textures array
  85573. * using getIndex(GeometryBufferRenderer.POSITION_TEXTURE_INDEX)
  85574. */
  85575. GeometryBufferRenderer.POSITION_TEXTURE_TYPE = 1;
  85576. /**
  85577. * Constant used to retrieve the velocity texture index in the G-Buffer textures array
  85578. * using getIndex(GeometryBufferRenderer.VELOCITY_TEXTURE_INDEX)
  85579. */
  85580. GeometryBufferRenderer.VELOCITY_TEXTURE_TYPE = 2;
  85581. return GeometryBufferRenderer;
  85582. }());
  85583. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  85584. })(BABYLON || (BABYLON = {}));
  85585. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  85586. var BABYLON;
  85587. (function (BABYLON) {
  85588. Object.defineProperty(BABYLON.Scene.prototype, "geometryBufferRenderer", {
  85589. get: function () {
  85590. this._geometryBufferRenderer;
  85591. },
  85592. set: function (value) {
  85593. if (value && value.isSupported) {
  85594. this._geometryBufferRenderer = value;
  85595. }
  85596. },
  85597. enumerable: true,
  85598. configurable: true
  85599. });
  85600. BABYLON.Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  85601. if (ratio === void 0) { ratio = 1; }
  85602. if (this._geometryBufferRenderer) {
  85603. return this._geometryBufferRenderer;
  85604. }
  85605. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  85606. if (!this._geometryBufferRenderer.isSupported) {
  85607. this._geometryBufferRenderer = null;
  85608. }
  85609. return this._geometryBufferRenderer;
  85610. };
  85611. BABYLON.Scene.prototype.disableGeometryBufferRenderer = function () {
  85612. if (!this._geometryBufferRenderer) {
  85613. return;
  85614. }
  85615. this._geometryBufferRenderer.dispose();
  85616. this._geometryBufferRenderer = null;
  85617. };
  85618. /**
  85619. * Defines the Geometry Buffer scene component responsible to manage a G-Buffer useful
  85620. * in several rendering techniques.
  85621. */
  85622. var GeometryBufferRendererSceneComponent = /** @class */ (function () {
  85623. /**
  85624. * Creates a new instance of the component for the given scene
  85625. * @param scene Defines the scene to register the component in
  85626. */
  85627. function GeometryBufferRendererSceneComponent(scene) {
  85628. /**
  85629. * The component name helpful to identify the component in the list of scene components.
  85630. */
  85631. this.name = BABYLON.SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER;
  85632. this.scene = scene;
  85633. }
  85634. /**
  85635. * Registers the component in a given scene
  85636. */
  85637. GeometryBufferRendererSceneComponent.prototype.register = function () {
  85638. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER, this, this._gatherRenderTargets);
  85639. };
  85640. /**
  85641. * Rebuilds the elements related to this component in case of
  85642. * context lost for instance.
  85643. */
  85644. GeometryBufferRendererSceneComponent.prototype.rebuild = function () {
  85645. // Nothing to do for this component
  85646. };
  85647. /**
  85648. * Disposes the component and the associated ressources
  85649. */
  85650. GeometryBufferRendererSceneComponent.prototype.dispose = function () {
  85651. // Nothing to do for this component
  85652. };
  85653. GeometryBufferRendererSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  85654. if (this.scene._geometryBufferRenderer) {
  85655. renderTargets.push(this.scene._geometryBufferRenderer.getGBuffer());
  85656. }
  85657. };
  85658. return GeometryBufferRendererSceneComponent;
  85659. }());
  85660. BABYLON.GeometryBufferRendererSceneComponent = GeometryBufferRendererSceneComponent;
  85661. })(BABYLON || (BABYLON = {}));
  85662. //# sourceMappingURL=babylon.geometryBufferRendererSceneComponent.js.map
  85663. var BABYLON;
  85664. (function (BABYLON) {
  85665. /**
  85666. * Render pipeline to produce ssao effect
  85667. */
  85668. var SSAORenderingPipeline = /** @class */ (function (_super) {
  85669. __extends(SSAORenderingPipeline, _super);
  85670. /**
  85671. * @constructor
  85672. * @param name - The rendering pipeline name
  85673. * @param scene - The scene linked to this pipeline
  85674. * @param ratio - The size of the postprocesses. Can be a number shared between passes or an object for more precision: { ssaoRatio: 0.5, combineRatio: 1.0 }
  85675. * @param cameras - The array of cameras that the rendering pipeline will be attached to
  85676. */
  85677. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  85678. var _this = _super.call(this, scene.getEngine(), name) || this;
  85679. // Members
  85680. /**
  85681. * @ignore
  85682. * The PassPostProcess id in the pipeline that contains the original scene color
  85683. */
  85684. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  85685. /**
  85686. * @ignore
  85687. * The SSAO PostProcess id in the pipeline
  85688. */
  85689. _this.SSAORenderEffect = "SSAORenderEffect";
  85690. /**
  85691. * @ignore
  85692. * The horizontal blur PostProcess id in the pipeline
  85693. */
  85694. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  85695. /**
  85696. * @ignore
  85697. * The vertical blur PostProcess id in the pipeline
  85698. */
  85699. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  85700. /**
  85701. * @ignore
  85702. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  85703. */
  85704. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  85705. /**
  85706. * The output strength of the SSAO post-process. Default value is 1.0.
  85707. */
  85708. _this.totalStrength = 1.0;
  85709. /**
  85710. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  85711. */
  85712. _this.radius = 0.0001;
  85713. /**
  85714. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  85715. * Must not be equal to fallOff and superior to fallOff.
  85716. * Default value is 0.975
  85717. */
  85718. _this.area = 0.0075;
  85719. /**
  85720. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  85721. * Must not be equal to area and inferior to area.
  85722. * Default value is 0.0
  85723. */
  85724. _this.fallOff = 0.000001;
  85725. /**
  85726. * The base color of the SSAO post-process
  85727. * The final result is "base + ssao" between [0, 1]
  85728. */
  85729. _this.base = 0.5;
  85730. _this._firstUpdate = true;
  85731. _this._scene = scene;
  85732. // Set up assets
  85733. _this._createRandomTexture();
  85734. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  85735. var ssaoRatio = ratio.ssaoRatio || ratio;
  85736. var combineRatio = ratio.combineRatio || ratio;
  85737. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  85738. _this._createSSAOPostProcess(ssaoRatio);
  85739. _this._createBlurPostProcess(ssaoRatio);
  85740. _this._createSSAOCombinePostProcess(combineRatio);
  85741. // Set up pipeline
  85742. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  85743. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  85744. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  85745. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  85746. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  85747. // Finish
  85748. scene.postProcessRenderPipelineManager.addPipeline(_this);
  85749. if (cameras) {
  85750. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  85751. }
  85752. return _this;
  85753. }
  85754. // Public Methods
  85755. /**
  85756. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  85757. */
  85758. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  85759. if (disableDepthRender === void 0) { disableDepthRender = false; }
  85760. for (var i = 0; i < this._scene.cameras.length; i++) {
  85761. var camera = this._scene.cameras[i];
  85762. this._originalColorPostProcess.dispose(camera);
  85763. this._ssaoPostProcess.dispose(camera);
  85764. this._blurHPostProcess.dispose(camera);
  85765. this._blurVPostProcess.dispose(camera);
  85766. this._ssaoCombinePostProcess.dispose(camera);
  85767. }
  85768. this._randomTexture.dispose();
  85769. if (disableDepthRender) {
  85770. this._scene.disableDepthRenderer();
  85771. }
  85772. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  85773. _super.prototype.dispose.call(this);
  85774. };
  85775. // Private Methods
  85776. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  85777. var _this = this;
  85778. var size = 16;
  85779. 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);
  85780. 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);
  85781. this._blurHPostProcess.onActivateObservable.add(function () {
  85782. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  85783. _this._blurHPostProcess.kernel = size * dw;
  85784. });
  85785. this._blurVPostProcess.onActivateObservable.add(function () {
  85786. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  85787. _this._blurVPostProcess.kernel = size * dw;
  85788. });
  85789. };
  85790. /** @hidden */
  85791. SSAORenderingPipeline.prototype._rebuild = function () {
  85792. this._firstUpdate = true;
  85793. _super.prototype._rebuild.call(this);
  85794. };
  85795. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  85796. var _this = this;
  85797. var numSamples = 16;
  85798. var sampleSphere = [
  85799. 0.5381, 0.1856, -0.4319,
  85800. 0.1379, 0.2486, 0.4430,
  85801. 0.3371, 0.5679, -0.0057,
  85802. -0.6999, -0.0451, -0.0019,
  85803. 0.0689, -0.1598, -0.8547,
  85804. 0.0560, 0.0069, -0.1843,
  85805. -0.0146, 0.1402, 0.0762,
  85806. 0.0100, -0.1924, -0.0344,
  85807. -0.3577, -0.5301, -0.4358,
  85808. -0.3169, 0.1063, 0.0158,
  85809. 0.0103, -0.5869, 0.0046,
  85810. -0.0897, -0.4940, 0.3287,
  85811. 0.7119, -0.0154, -0.0918,
  85812. -0.0533, 0.0596, -0.5411,
  85813. 0.0352, -0.0631, 0.5460,
  85814. -0.4776, 0.2847, -0.0271
  85815. ];
  85816. var samplesFactor = 1.0 / numSamples;
  85817. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  85818. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  85819. "area", "fallOff", "base", "range", "viewport"
  85820. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  85821. this._ssaoPostProcess.onApply = function (effect) {
  85822. if (_this._firstUpdate) {
  85823. effect.setArray3("sampleSphere", sampleSphere);
  85824. effect.setFloat("samplesFactor", samplesFactor);
  85825. effect.setFloat("randTextureTiles", 4.0);
  85826. }
  85827. effect.setFloat("totalStrength", _this.totalStrength);
  85828. effect.setFloat("radius", _this.radius);
  85829. effect.setFloat("area", _this.area);
  85830. effect.setFloat("fallOff", _this.fallOff);
  85831. effect.setFloat("base", _this.base);
  85832. effect.setTexture("textureSampler", _this._depthTexture);
  85833. effect.setTexture("randomSampler", _this._randomTexture);
  85834. };
  85835. };
  85836. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  85837. var _this = this;
  85838. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  85839. this._ssaoCombinePostProcess.onApply = function (effect) {
  85840. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(0, 0, 1.0, 1.0));
  85841. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  85842. };
  85843. };
  85844. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  85845. var size = 512;
  85846. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  85847. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  85848. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  85849. var context = this._randomTexture.getContext();
  85850. var rand = function (min, max) {
  85851. return Math.random() * (max - min) + min;
  85852. };
  85853. var randVector = BABYLON.Vector3.Zero();
  85854. for (var x = 0; x < size; x++) {
  85855. for (var y = 0; y < size; y++) {
  85856. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  85857. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  85858. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  85859. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  85860. context.fillRect(x, y, 1, 1);
  85861. }
  85862. }
  85863. this._randomTexture.update(false);
  85864. };
  85865. __decorate([
  85866. BABYLON.serialize()
  85867. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  85868. __decorate([
  85869. BABYLON.serialize()
  85870. ], SSAORenderingPipeline.prototype, "radius", void 0);
  85871. __decorate([
  85872. BABYLON.serialize()
  85873. ], SSAORenderingPipeline.prototype, "area", void 0);
  85874. __decorate([
  85875. BABYLON.serialize()
  85876. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  85877. __decorate([
  85878. BABYLON.serialize()
  85879. ], SSAORenderingPipeline.prototype, "base", void 0);
  85880. return SSAORenderingPipeline;
  85881. }(BABYLON.PostProcessRenderPipeline));
  85882. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  85883. })(BABYLON || (BABYLON = {}));
  85884. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  85885. var BABYLON;
  85886. (function (BABYLON) {
  85887. /**
  85888. * Render pipeline to produce ssao effect
  85889. */
  85890. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  85891. __extends(SSAO2RenderingPipeline, _super);
  85892. /**
  85893. * @constructor
  85894. * @param name The rendering pipeline name
  85895. * @param scene The scene linked to this pipeline
  85896. * @param ratio The size of the postprocesses. Can be a number shared between passes or an object for more precision: { ssaoRatio: 0.5, blurRatio: 1.0 }
  85897. * @param cameras The array of cameras that the rendering pipeline will be attached to
  85898. */
  85899. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  85900. var _this = _super.call(this, scene.getEngine(), name) || this;
  85901. // Members
  85902. /**
  85903. * @ignore
  85904. * The PassPostProcess id in the pipeline that contains the original scene color
  85905. */
  85906. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  85907. /**
  85908. * @ignore
  85909. * The SSAO PostProcess id in the pipeline
  85910. */
  85911. _this.SSAORenderEffect = "SSAORenderEffect";
  85912. /**
  85913. * @ignore
  85914. * The horizontal blur PostProcess id in the pipeline
  85915. */
  85916. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  85917. /**
  85918. * @ignore
  85919. * The vertical blur PostProcess id in the pipeline
  85920. */
  85921. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  85922. /**
  85923. * @ignore
  85924. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  85925. */
  85926. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  85927. /**
  85928. * The output strength of the SSAO post-process. Default value is 1.0.
  85929. */
  85930. _this.totalStrength = 1.0;
  85931. /**
  85932. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  85933. */
  85934. _this.maxZ = 100.0;
  85935. /**
  85936. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  85937. */
  85938. _this.minZAspect = 0.2;
  85939. _this._samples = 8;
  85940. _this._textureSamples = 1;
  85941. _this._expensiveBlur = true;
  85942. /**
  85943. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  85944. */
  85945. _this.radius = 2.0;
  85946. /**
  85947. * The base color of the SSAO post-process
  85948. * The final result is "base + ssao" between [0, 1]
  85949. */
  85950. _this.base = 0;
  85951. _this._firstUpdate = true;
  85952. _this._bits = new Uint32Array(1);
  85953. _this._scene = scene;
  85954. _this._ratio = ratio;
  85955. if (!_this.isSupported) {
  85956. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  85957. return _this;
  85958. }
  85959. var ssaoRatio = _this._ratio.ssaoRatio || ratio;
  85960. var blurRatio = _this._ratio.blurRatio || ratio;
  85961. // Set up assets
  85962. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  85963. _this._createRandomTexture();
  85964. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  85965. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  85966. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  85967. _this._originalColorPostProcess.samples = _this.textureSamples;
  85968. _this._createSSAOPostProcess(1.0);
  85969. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  85970. _this._createSSAOCombinePostProcess(blurRatio);
  85971. // Set up pipeline
  85972. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  85973. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  85974. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  85975. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  85976. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  85977. // Finish
  85978. scene.postProcessRenderPipelineManager.addPipeline(_this);
  85979. if (cameras) {
  85980. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  85981. }
  85982. return _this;
  85983. }
  85984. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  85985. get: function () {
  85986. return this._samples;
  85987. },
  85988. /**
  85989. * Number of samples used for the SSAO calculations. Default value is 8
  85990. */
  85991. set: function (n) {
  85992. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  85993. this._samples = n;
  85994. this._sampleSphere = this._generateHemisphere();
  85995. this._firstUpdate = true;
  85996. },
  85997. enumerable: true,
  85998. configurable: true
  85999. });
  86000. Object.defineProperty(SSAO2RenderingPipeline.prototype, "textureSamples", {
  86001. get: function () {
  86002. return this._textureSamples;
  86003. },
  86004. /**
  86005. * Number of samples to use for antialiasing
  86006. */
  86007. set: function (n) {
  86008. this._textureSamples = n;
  86009. this._originalColorPostProcess.samples = n;
  86010. this._blurHPostProcess.samples = n;
  86011. this._blurVPostProcess.samples = n;
  86012. this._ssaoPostProcess.samples = n;
  86013. this._ssaoCombinePostProcess.samples = n;
  86014. },
  86015. enumerable: true,
  86016. configurable: true
  86017. });
  86018. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  86019. get: function () {
  86020. return this._expensiveBlur;
  86021. },
  86022. /**
  86023. * If bilateral blur should be used
  86024. */
  86025. set: function (b) {
  86026. 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"]);
  86027. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  86028. this._expensiveBlur = b;
  86029. this._firstUpdate = true;
  86030. },
  86031. enumerable: true,
  86032. configurable: true
  86033. });
  86034. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  86035. /**
  86036. * Support test.
  86037. */
  86038. get: function () {
  86039. var engine = BABYLON.Engine.LastCreatedEngine;
  86040. if (!engine) {
  86041. return false;
  86042. }
  86043. return engine.getCaps().drawBuffersExtension;
  86044. },
  86045. enumerable: true,
  86046. configurable: true
  86047. });
  86048. // Public Methods
  86049. /**
  86050. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  86051. */
  86052. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  86053. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  86054. for (var i = 0; i < this._scene.cameras.length; i++) {
  86055. var camera = this._scene.cameras[i];
  86056. this._originalColorPostProcess.dispose(camera);
  86057. this._ssaoPostProcess.dispose(camera);
  86058. this._blurHPostProcess.dispose(camera);
  86059. this._blurVPostProcess.dispose(camera);
  86060. this._ssaoCombinePostProcess.dispose(camera);
  86061. }
  86062. this._randomTexture.dispose();
  86063. if (disableGeometryBufferRenderer) {
  86064. this._scene.disableGeometryBufferRenderer();
  86065. }
  86066. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  86067. _super.prototype.dispose.call(this);
  86068. };
  86069. // Private Methods
  86070. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  86071. var _this = this;
  86072. this._samplerOffsets = [];
  86073. var expensive = this.expensiveBlur;
  86074. for (var i = -8; i < 8; i++) {
  86075. this._samplerOffsets.push(i * 2 + 0.5);
  86076. }
  86077. 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");
  86078. this._blurHPostProcess.onApply = function (effect) {
  86079. if (!_this._scene.activeCamera) {
  86080. return;
  86081. }
  86082. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  86083. effect.setFloat("near", _this._scene.activeCamera.minZ);
  86084. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  86085. effect.setFloat("radius", _this.radius);
  86086. effect.setTexture("depthSampler", _this._depthTexture);
  86087. if (_this._firstUpdate) {
  86088. effect.setArray("samplerOffsets", _this._samplerOffsets);
  86089. }
  86090. };
  86091. 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");
  86092. this._blurVPostProcess.onApply = function (effect) {
  86093. if (!_this._scene.activeCamera) {
  86094. return;
  86095. }
  86096. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  86097. effect.setFloat("near", _this._scene.activeCamera.minZ);
  86098. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  86099. effect.setFloat("radius", _this.radius);
  86100. effect.setTexture("depthSampler", _this._depthTexture);
  86101. if (_this._firstUpdate) {
  86102. effect.setArray("samplerOffsets", _this._samplerOffsets);
  86103. _this._firstUpdate = false;
  86104. }
  86105. };
  86106. this._blurHPostProcess.samples = this.textureSamples;
  86107. this._blurVPostProcess.samples = this.textureSamples;
  86108. };
  86109. /** @hidden */
  86110. SSAO2RenderingPipeline.prototype._rebuild = function () {
  86111. this._firstUpdate = true;
  86112. _super.prototype._rebuild.call(this);
  86113. };
  86114. //Van der Corput radical inverse
  86115. SSAO2RenderingPipeline.prototype._radicalInverse_VdC = function (i) {
  86116. this._bits[0] = i;
  86117. this._bits[0] = ((this._bits[0] << 16) | (this._bits[0] >> 16)) >>> 0;
  86118. this._bits[0] = ((this._bits[0] & 0x55555555) << 1) | ((this._bits[0] & 0xAAAAAAAA) >>> 1) >>> 0;
  86119. this._bits[0] = ((this._bits[0] & 0x33333333) << 2) | ((this._bits[0] & 0xCCCCCCCC) >>> 2) >>> 0;
  86120. this._bits[0] = ((this._bits[0] & 0x0F0F0F0F) << 4) | ((this._bits[0] & 0xF0F0F0F0) >>> 4) >>> 0;
  86121. this._bits[0] = ((this._bits[0] & 0x00FF00FF) << 8) | ((this._bits[0] & 0xFF00FF00) >>> 8) >>> 0;
  86122. return this._bits[0] * 2.3283064365386963e-10; // / 0x100000000 or / 4294967296
  86123. };
  86124. SSAO2RenderingPipeline.prototype._hammersley = function (i, n) {
  86125. return [i / n, this._radicalInverse_VdC(i)];
  86126. };
  86127. SSAO2RenderingPipeline.prototype._hemisphereSample_uniform = function (u, v) {
  86128. var phi = v * 2.0 * Math.PI;
  86129. // rejecting samples that are close to tangent plane to avoid z-fighting artifacts
  86130. var cosTheta = 1.0 - (u * 0.85 + 0.15);
  86131. var sinTheta = Math.sqrt(1.0 - cosTheta * cosTheta);
  86132. return new BABYLON.Vector3(Math.cos(phi) * sinTheta, Math.sin(phi) * sinTheta, cosTheta);
  86133. };
  86134. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  86135. var numSamples = this.samples;
  86136. var result = [];
  86137. var vector;
  86138. var i = 0;
  86139. while (i < numSamples) {
  86140. if (numSamples < 16) {
  86141. vector = this._hemisphereSample_uniform(Math.random(), Math.random());
  86142. }
  86143. else {
  86144. var rand = this._hammersley(i, numSamples);
  86145. vector = this._hemisphereSample_uniform(rand[0], rand[1]);
  86146. }
  86147. result.push(vector.x, vector.y, vector.z);
  86148. i++;
  86149. }
  86150. return result;
  86151. };
  86152. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  86153. var _this = this;
  86154. var numSamples = this.samples;
  86155. this._sampleSphere = this._generateHemisphere();
  86156. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  86157. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  86158. "base", "range", "projection", "near", "far", "texelSize",
  86159. "xViewport", "yViewport", "maxZ", "minZAspect"
  86160. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  86161. this._ssaoPostProcess.onApply = function (effect) {
  86162. if (_this._firstUpdate) {
  86163. effect.setArray3("sampleSphere", _this._sampleSphere);
  86164. effect.setFloat("randTextureTiles", 32.0);
  86165. }
  86166. if (!_this._scene.activeCamera) {
  86167. return;
  86168. }
  86169. effect.setFloat("samplesFactor", 1 / _this.samples);
  86170. effect.setFloat("totalStrength", _this.totalStrength);
  86171. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  86172. effect.setFloat("radius", _this.radius);
  86173. effect.setFloat("maxZ", _this.maxZ);
  86174. effect.setFloat("minZAspect", _this.minZAspect);
  86175. effect.setFloat("base", _this.base);
  86176. effect.setFloat("near", _this._scene.activeCamera.minZ);
  86177. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  86178. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  86179. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  86180. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  86181. effect.setTexture("textureSampler", _this._depthTexture);
  86182. effect.setTexture("normalSampler", _this._normalTexture);
  86183. effect.setTexture("randomSampler", _this._randomTexture);
  86184. };
  86185. this._ssaoPostProcess.samples = this.textureSamples;
  86186. };
  86187. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  86188. var _this = this;
  86189. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  86190. this._ssaoCombinePostProcess.onApply = function (effect) {
  86191. var viewport = _this._scene.activeCamera.viewport;
  86192. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(viewport.x, viewport.y, viewport.width, viewport.height));
  86193. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  86194. };
  86195. this._ssaoCombinePostProcess.samples = this.textureSamples;
  86196. };
  86197. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  86198. var size = 128;
  86199. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  86200. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  86201. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  86202. var context = this._randomTexture.getContext();
  86203. var rand = function (min, max) {
  86204. return Math.random() * (max - min) + min;
  86205. };
  86206. var randVector = BABYLON.Vector3.Zero();
  86207. for (var x = 0; x < size; x++) {
  86208. for (var y = 0; y < size; y++) {
  86209. randVector.x = rand(0.0, 1.0);
  86210. randVector.y = rand(0.0, 1.0);
  86211. randVector.z = 0.0;
  86212. randVector.normalize();
  86213. randVector.scaleInPlace(255);
  86214. randVector.x = Math.floor(randVector.x);
  86215. randVector.y = Math.floor(randVector.y);
  86216. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  86217. context.fillRect(x, y, 1, 1);
  86218. }
  86219. }
  86220. this._randomTexture.update(false);
  86221. };
  86222. /**
  86223. * Serialize the rendering pipeline (Used when exporting)
  86224. * @returns the serialized object
  86225. */
  86226. SSAO2RenderingPipeline.prototype.serialize = function () {
  86227. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  86228. serializationObject.customType = "SSAO2RenderingPipeline";
  86229. return serializationObject;
  86230. };
  86231. /**
  86232. * Parse the serialized pipeline
  86233. * @param source Source pipeline.
  86234. * @param scene The scene to load the pipeline to.
  86235. * @param rootUrl The URL of the serialized pipeline.
  86236. * @returns An instantiated pipeline from the serialized object.
  86237. */
  86238. SSAO2RenderingPipeline.Parse = function (source, scene, rootUrl) {
  86239. return BABYLON.SerializationHelper.Parse(function () { return new SSAO2RenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  86240. };
  86241. __decorate([
  86242. BABYLON.serialize()
  86243. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  86244. __decorate([
  86245. BABYLON.serialize()
  86246. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  86247. __decorate([
  86248. BABYLON.serialize()
  86249. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  86250. __decorate([
  86251. BABYLON.serialize("samples")
  86252. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  86253. __decorate([
  86254. BABYLON.serialize("textureSamples")
  86255. ], SSAO2RenderingPipeline.prototype, "_textureSamples", void 0);
  86256. __decorate([
  86257. BABYLON.serialize()
  86258. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  86259. __decorate([
  86260. BABYLON.serialize("expensiveBlur")
  86261. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  86262. __decorate([
  86263. BABYLON.serialize()
  86264. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  86265. __decorate([
  86266. BABYLON.serialize()
  86267. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  86268. return SSAO2RenderingPipeline;
  86269. }(BABYLON.PostProcessRenderPipeline));
  86270. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  86271. })(BABYLON || (BABYLON = {}));
  86272. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  86273. var BABYLON;
  86274. (function (BABYLON) {
  86275. /**
  86276. * BABYLON.JS Chromatic Aberration GLSL Shader
  86277. * Author: Olivier Guyot
  86278. * Separates very slightly R, G and B colors on the edges of the screen
  86279. * Inspired by Francois Tarlier & Martins Upitis
  86280. */
  86281. var LensRenderingPipeline = /** @class */ (function (_super) {
  86282. __extends(LensRenderingPipeline, _super);
  86283. /**
  86284. * @constructor
  86285. *
  86286. * Effect parameters are as follow:
  86287. * {
  86288. * chromatic_aberration: number; // from 0 to x (1 for realism)
  86289. * edge_blur: number; // from 0 to x (1 for realism)
  86290. * distortion: number; // from 0 to x (1 for realism)
  86291. * grain_amount: number; // from 0 to 1
  86292. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  86293. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  86294. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  86295. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  86296. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  86297. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  86298. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  86299. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  86300. * }
  86301. * Note: if an effect parameter is unset, effect is disabled
  86302. *
  86303. * @param name The rendering pipeline name
  86304. * @param parameters - An object containing all parameters (see above)
  86305. * @param scene The scene linked to this pipeline
  86306. * @param ratio The size of the postprocesses (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5)
  86307. * @param cameras The array of cameras that the rendering pipeline will be attached to
  86308. */
  86309. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  86310. if (ratio === void 0) { ratio = 1.0; }
  86311. var _this = _super.call(this, scene.getEngine(), name) || this;
  86312. // Lens effects can be of the following:
  86313. // - chromatic aberration (slight shift of RGB colors)
  86314. // - blur on the edge of the lens
  86315. // - lens distortion
  86316. // - depth-of-field blur & highlights enhancing
  86317. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  86318. // - grain effect (noise or custom texture)
  86319. // Two additional texture samplers are needed:
  86320. // - depth map (for depth-of-field)
  86321. // - grain texture
  86322. /**
  86323. * @ignore
  86324. * The chromatic aberration PostProcess id in the pipeline
  86325. */
  86326. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  86327. /**
  86328. * @ignore
  86329. * The highlights enhancing PostProcess id in the pipeline
  86330. */
  86331. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  86332. /**
  86333. * @ignore
  86334. * The depth-of-field PostProcess id in the pipeline
  86335. */
  86336. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  86337. _this._scene = scene;
  86338. // Fetch texture samplers
  86339. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  86340. if (parameters.grain_texture) {
  86341. _this._grainTexture = parameters.grain_texture;
  86342. }
  86343. else {
  86344. _this._createGrainTexture();
  86345. }
  86346. // save parameters
  86347. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  86348. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  86349. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  86350. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  86351. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  86352. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  86353. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  86354. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  86355. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  86356. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  86357. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  86358. // Create effects
  86359. _this._createChromaticAberrationPostProcess(ratio);
  86360. _this._createHighlightsPostProcess(ratio);
  86361. _this._createDepthOfFieldPostProcess(ratio / 4);
  86362. // Set up pipeline
  86363. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  86364. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  86365. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  86366. if (_this._highlightsGain === -1) {
  86367. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  86368. }
  86369. // Finish
  86370. scene.postProcessRenderPipelineManager.addPipeline(_this);
  86371. if (cameras) {
  86372. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  86373. }
  86374. return _this;
  86375. }
  86376. // public methods (self explanatory)
  86377. /**
  86378. * Sets the amount of blur at the edges
  86379. * @param amount blur amount
  86380. */
  86381. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  86382. /**
  86383. * Sets edge blur to 0
  86384. */
  86385. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  86386. /**
  86387. * Sets the amout of grain
  86388. * @param amount Amount of grain
  86389. */
  86390. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  86391. /**
  86392. * Set grain amount to 0
  86393. */
  86394. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  86395. /**
  86396. * Sets the chromatic aberration amount
  86397. * @param amount amount of chromatic aberration
  86398. */
  86399. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  86400. /**
  86401. * Sets chromatic aberration amount to 0
  86402. */
  86403. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  86404. /**
  86405. * Sets the EdgeDistortion amount
  86406. * @param amount amount of EdgeDistortion
  86407. */
  86408. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  86409. /**
  86410. * Sets edge distortion to 0
  86411. */
  86412. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  86413. /**
  86414. * Sets the FocusDistance amount
  86415. * @param amount amount of FocusDistance
  86416. */
  86417. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  86418. /**
  86419. * Disables depth of field
  86420. */
  86421. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  86422. /**
  86423. * Sets the Aperture amount
  86424. * @param amount amount of Aperture
  86425. */
  86426. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  86427. /**
  86428. * Sets the DarkenOutOfFocus amount
  86429. * @param amount amount of DarkenOutOfFocus
  86430. */
  86431. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  86432. /**
  86433. * Creates a pentagon bokeh effect
  86434. */
  86435. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  86436. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  86437. };
  86438. /**
  86439. * Disables the pentagon bokeh effect
  86440. */
  86441. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  86442. this._highlightsPostProcess.updateEffect();
  86443. };
  86444. /**
  86445. * Enables noise blur
  86446. */
  86447. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  86448. /**
  86449. * Disables noise blur
  86450. */
  86451. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  86452. /**
  86453. * Sets the HighlightsGain amount
  86454. * @param amount amount of HighlightsGain
  86455. */
  86456. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  86457. this._highlightsGain = amount;
  86458. };
  86459. /**
  86460. * Sets the HighlightsThreshold amount
  86461. * @param amount amount of HighlightsThreshold
  86462. */
  86463. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  86464. if (this._highlightsGain === -1) {
  86465. this._highlightsGain = 1.0;
  86466. }
  86467. this._highlightsThreshold = amount;
  86468. };
  86469. /**
  86470. * Disables highlights
  86471. */
  86472. LensRenderingPipeline.prototype.disableHighlights = function () {
  86473. this._highlightsGain = -1;
  86474. };
  86475. /**
  86476. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  86477. * @param disableDepthRender If the scens depth rendering should be disabled (default: false)
  86478. */
  86479. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  86480. if (disableDepthRender === void 0) { disableDepthRender = false; }
  86481. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  86482. this._chromaticAberrationPostProcess = null;
  86483. this._highlightsPostProcess = null;
  86484. this._depthOfFieldPostProcess = null;
  86485. this._grainTexture.dispose();
  86486. if (disableDepthRender) {
  86487. this._scene.disableDepthRenderer();
  86488. }
  86489. };
  86490. // colors shifting and distortion
  86491. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  86492. var _this = this;
  86493. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  86494. [], // samplers
  86495. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  86496. this._chromaticAberrationPostProcess.onApply = function (effect) {
  86497. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  86498. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  86499. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  86500. effect.setFloat('radialIntensity', 1);
  86501. effect.setFloat2('direction', 17, 17);
  86502. effect.setFloat2('centerPosition', 0.5, 0.5);
  86503. };
  86504. };
  86505. // highlights enhancing
  86506. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  86507. var _this = this;
  86508. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  86509. [], // samplers
  86510. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  86511. this._highlightsPostProcess.onApply = function (effect) {
  86512. effect.setFloat('gain', _this._highlightsGain);
  86513. effect.setFloat('threshold', _this._highlightsThreshold);
  86514. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  86515. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  86516. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  86517. };
  86518. };
  86519. // colors shifting and distortion
  86520. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  86521. var _this = this;
  86522. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  86523. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  86524. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  86525. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  86526. this._depthOfFieldPostProcess.onApply = function (effect) {
  86527. effect.setTexture("depthSampler", _this._depthTexture);
  86528. effect.setTexture("grainSampler", _this._grainTexture);
  86529. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  86530. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  86531. effect.setFloat('grain_amount', _this._grainAmount);
  86532. effect.setBool('blur_noise', _this._blurNoise);
  86533. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  86534. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  86535. effect.setFloat('distortion', _this._distortion);
  86536. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  86537. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  86538. effect.setFloat('aperture', _this._dofAperture);
  86539. effect.setFloat('darken', _this._dofDarken);
  86540. effect.setFloat('edge_blur', _this._edgeBlur);
  86541. effect.setBool('highlights', (_this._highlightsGain !== -1));
  86542. if (_this._scene.activeCamera) {
  86543. effect.setFloat('near', _this._scene.activeCamera.minZ);
  86544. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  86545. }
  86546. };
  86547. };
  86548. // creates a black and white random noise texture, 512x512
  86549. LensRenderingPipeline.prototype._createGrainTexture = function () {
  86550. var size = 512;
  86551. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  86552. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  86553. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  86554. var context = this._grainTexture.getContext();
  86555. var rand = function (min, max) {
  86556. return Math.random() * (max - min) + min;
  86557. };
  86558. var value;
  86559. for (var x = 0; x < size; x++) {
  86560. for (var y = 0; y < size; y++) {
  86561. value = Math.floor(rand(0.42, 0.58) * 255);
  86562. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  86563. context.fillRect(x, y, 1, 1);
  86564. }
  86565. }
  86566. this._grainTexture.update(false);
  86567. };
  86568. return LensRenderingPipeline;
  86569. }(BABYLON.PostProcessRenderPipeline));
  86570. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  86571. })(BABYLON || (BABYLON = {}));
  86572. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  86573. var BABYLON;
  86574. (function (BABYLON) {
  86575. /**
  86576. * Standard rendering pipeline
  86577. * Default pipeline should be used going forward but the standard pipeline will be kept for backwards compatibility.
  86578. * @see https://doc.babylonjs.com/how_to/using_standard_rendering_pipeline
  86579. */
  86580. var StandardRenderingPipeline = /** @class */ (function (_super) {
  86581. __extends(StandardRenderingPipeline, _super);
  86582. /**
  86583. * Default pipeline should be used going forward but the standard pipeline will be kept for backwards compatibility.
  86584. * @constructor
  86585. * @param name The rendering pipeline name
  86586. * @param scene The scene linked to this pipeline
  86587. * @param ratio The size of the postprocesses (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5)
  86588. * @param originalPostProcess the custom original color post-process. Must be "reusable". Can be null.
  86589. * @param cameras The array of cameras that the rendering pipeline will be attached to
  86590. */
  86591. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  86592. if (originalPostProcess === void 0) { originalPostProcess = null; }
  86593. var _this = _super.call(this, scene.getEngine(), name) || this;
  86594. /**
  86595. * Post-process used to down scale an image x4
  86596. */
  86597. _this.downSampleX4PostProcess = null;
  86598. /**
  86599. * Post-process used to calculate the illuminated surfaces controlled by a threshold
  86600. */
  86601. _this.brightPassPostProcess = null;
  86602. /**
  86603. * Post-process array storing all the horizontal blur post-processes used by the pipeline
  86604. */
  86605. _this.blurHPostProcesses = [];
  86606. /**
  86607. * Post-process array storing all the vertical blur post-processes used by the pipeline
  86608. */
  86609. _this.blurVPostProcesses = [];
  86610. /**
  86611. * Post-process used to add colors of 2 textures (typically brightness + real scene color)
  86612. */
  86613. _this.textureAdderPostProcess = null;
  86614. /**
  86615. * Post-process used to create volumetric lighting effect
  86616. */
  86617. _this.volumetricLightPostProcess = null;
  86618. /**
  86619. * Post-process used to smooth the previous volumetric light post-process on the X axis
  86620. */
  86621. _this.volumetricLightSmoothXPostProcess = null;
  86622. /**
  86623. * Post-process used to smooth the previous volumetric light post-process on the Y axis
  86624. */
  86625. _this.volumetricLightSmoothYPostProcess = null;
  86626. /**
  86627. * Post-process used to merge the volumetric light effect and the real scene color
  86628. */
  86629. _this.volumetricLightMergePostProces = null;
  86630. /**
  86631. * Post-process used to store the final volumetric light post-process (attach/detach for debug purpose)
  86632. */
  86633. _this.volumetricLightFinalPostProcess = null;
  86634. /**
  86635. * Base post-process used to calculate the average luminance of the final image for HDR
  86636. */
  86637. _this.luminancePostProcess = null;
  86638. /**
  86639. * Post-processes used to create down sample post-processes in order to get
  86640. * the average luminance of the final image for HDR
  86641. * Array of length "StandardRenderingPipeline.LuminanceSteps"
  86642. */
  86643. _this.luminanceDownSamplePostProcesses = [];
  86644. /**
  86645. * Post-process used to create a HDR effect (light adaptation)
  86646. */
  86647. _this.hdrPostProcess = null;
  86648. /**
  86649. * Post-process used to store the final texture adder post-process (attach/detach for debug purpose)
  86650. */
  86651. _this.textureAdderFinalPostProcess = null;
  86652. /**
  86653. * Post-process used to store the final lens flare post-process (attach/detach for debug purpose)
  86654. */
  86655. _this.lensFlareFinalPostProcess = null;
  86656. /**
  86657. * Post-process used to merge the final HDR post-process and the real scene color
  86658. */
  86659. _this.hdrFinalPostProcess = null;
  86660. /**
  86661. * Post-process used to create a lens flare effect
  86662. */
  86663. _this.lensFlarePostProcess = null;
  86664. /**
  86665. * Post-process that merges the result of the lens flare post-process and the real scene color
  86666. */
  86667. _this.lensFlareComposePostProcess = null;
  86668. /**
  86669. * Post-process used to create a motion blur effect
  86670. */
  86671. _this.motionBlurPostProcess = null;
  86672. /**
  86673. * Post-process used to create a depth of field effect
  86674. */
  86675. _this.depthOfFieldPostProcess = null;
  86676. /**
  86677. * The Fast Approximate Anti-Aliasing post process which attemps to remove aliasing from an image.
  86678. */
  86679. _this.fxaaPostProcess = null;
  86680. // Values
  86681. /**
  86682. * Represents the brightness threshold in order to configure the illuminated surfaces
  86683. */
  86684. _this.brightThreshold = 1.0;
  86685. /**
  86686. * Configures the blur intensity used for surexposed surfaces are highlighted surfaces (light halo)
  86687. */
  86688. _this.blurWidth = 512.0;
  86689. /**
  86690. * Sets if the blur for highlighted surfaces must be only horizontal
  86691. */
  86692. _this.horizontalBlur = false;
  86693. /**
  86694. * Sets the overall exposure used by the pipeline
  86695. */
  86696. _this.exposure = 1.0;
  86697. /**
  86698. * Texture used typically to simulate "dirty" on camera lens
  86699. */
  86700. _this.lensTexture = null;
  86701. /**
  86702. * Represents the offset coefficient based on Rayleigh principle. Typically in interval [-0.2, 0.2]
  86703. */
  86704. _this.volumetricLightCoefficient = 0.2;
  86705. /**
  86706. * The overall power of volumetric lights, typically in interval [0, 10] maximum
  86707. */
  86708. _this.volumetricLightPower = 4.0;
  86709. /**
  86710. * Used the set the blur intensity to smooth the volumetric lights
  86711. */
  86712. _this.volumetricLightBlurScale = 64.0;
  86713. /**
  86714. * Light (spot or directional) used to generate the volumetric lights rays
  86715. * The source light must have a shadow generate so the pipeline can get its
  86716. * depth map
  86717. */
  86718. _this.sourceLight = null;
  86719. /**
  86720. * For eye adaptation, represents the minimum luminance the eye can see
  86721. */
  86722. _this.hdrMinimumLuminance = 1.0;
  86723. /**
  86724. * For eye adaptation, represents the decrease luminance speed
  86725. */
  86726. _this.hdrDecreaseRate = 0.5;
  86727. /**
  86728. * For eye adaptation, represents the increase luminance speed
  86729. */
  86730. _this.hdrIncreaseRate = 0.5;
  86731. /**
  86732. * Lens color texture used by the lens flare effect. Mandatory if lens flare effect enabled
  86733. */
  86734. _this.lensColorTexture = null;
  86735. /**
  86736. * The overall strengh for the lens flare effect
  86737. */
  86738. _this.lensFlareStrength = 20.0;
  86739. /**
  86740. * Dispersion coefficient for lens flare ghosts
  86741. */
  86742. _this.lensFlareGhostDispersal = 1.4;
  86743. /**
  86744. * Main lens flare halo width
  86745. */
  86746. _this.lensFlareHaloWidth = 0.7;
  86747. /**
  86748. * Based on the lens distortion effect, defines how much the lens flare result
  86749. * is distorted
  86750. */
  86751. _this.lensFlareDistortionStrength = 16.0;
  86752. /**
  86753. * Lens star texture must be used to simulate rays on the flares and is available
  86754. * in the documentation
  86755. */
  86756. _this.lensStarTexture = null;
  86757. /**
  86758. * As the "lensTexture" (can be the same texture or different), it is used to apply the lens
  86759. * flare effect by taking account of the dirt texture
  86760. */
  86761. _this.lensFlareDirtTexture = null;
  86762. /**
  86763. * Represents the focal length for the depth of field effect
  86764. */
  86765. _this.depthOfFieldDistance = 10.0;
  86766. /**
  86767. * Represents the blur intensity for the blurred part of the depth of field effect
  86768. */
  86769. _this.depthOfFieldBlurWidth = 64.0;
  86770. /**
  86771. * For motion blur, defines how much the image is blurred by the movement
  86772. */
  86773. _this.motionStrength = 1.0;
  86774. /**
  86775. * List of animations for the pipeline (IAnimatable implementation)
  86776. */
  86777. _this.animations = [];
  86778. _this._currentDepthOfFieldSource = null;
  86779. _this._hdrCurrentLuminance = 1.0;
  86780. // Getters and setters
  86781. _this._bloomEnabled = false;
  86782. _this._depthOfFieldEnabled = false;
  86783. _this._vlsEnabled = false;
  86784. _this._lensFlareEnabled = false;
  86785. _this._hdrEnabled = false;
  86786. _this._motionBlurEnabled = false;
  86787. _this._fxaaEnabled = false;
  86788. _this._motionBlurSamples = 64.0;
  86789. _this._volumetricLightStepsCount = 50.0;
  86790. _this._samples = 1;
  86791. _this._cameras = cameras || [];
  86792. // Initialize
  86793. _this._scene = scene;
  86794. _this._basePostProcess = originalPostProcess;
  86795. _this._ratio = ratio;
  86796. // Misc
  86797. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  86798. // Finish
  86799. scene.postProcessRenderPipelineManager.addPipeline(_this);
  86800. _this._buildPipeline();
  86801. return _this;
  86802. }
  86803. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  86804. /**
  86805. * @ignore
  86806. * Specifies if the bloom pipeline is enabled
  86807. */
  86808. get: function () {
  86809. return this._bloomEnabled;
  86810. },
  86811. set: function (enabled) {
  86812. if (this._bloomEnabled === enabled) {
  86813. return;
  86814. }
  86815. this._bloomEnabled = enabled;
  86816. this._buildPipeline();
  86817. },
  86818. enumerable: true,
  86819. configurable: true
  86820. });
  86821. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  86822. /**
  86823. * @ignore
  86824. * Specifies if the depth of field pipeline is enabed
  86825. */
  86826. get: function () {
  86827. return this._depthOfFieldEnabled;
  86828. },
  86829. set: function (enabled) {
  86830. if (this._depthOfFieldEnabled === enabled) {
  86831. return;
  86832. }
  86833. this._depthOfFieldEnabled = enabled;
  86834. this._buildPipeline();
  86835. },
  86836. enumerable: true,
  86837. configurable: true
  86838. });
  86839. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  86840. /**
  86841. * @ignore
  86842. * Specifies if the lens flare pipeline is enabed
  86843. */
  86844. get: function () {
  86845. return this._lensFlareEnabled;
  86846. },
  86847. set: function (enabled) {
  86848. if (this._lensFlareEnabled === enabled) {
  86849. return;
  86850. }
  86851. this._lensFlareEnabled = enabled;
  86852. this._buildPipeline();
  86853. },
  86854. enumerable: true,
  86855. configurable: true
  86856. });
  86857. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  86858. /**
  86859. * @ignore
  86860. * Specifies if the HDR pipeline is enabled
  86861. */
  86862. get: function () {
  86863. return this._hdrEnabled;
  86864. },
  86865. set: function (enabled) {
  86866. if (this._hdrEnabled === enabled) {
  86867. return;
  86868. }
  86869. this._hdrEnabled = enabled;
  86870. this._buildPipeline();
  86871. },
  86872. enumerable: true,
  86873. configurable: true
  86874. });
  86875. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  86876. /**
  86877. * @ignore
  86878. * Specifies if the volumetric lights scattering effect is enabled
  86879. */
  86880. get: function () {
  86881. return this._vlsEnabled;
  86882. },
  86883. set: function (enabled) {
  86884. if (this._vlsEnabled === enabled) {
  86885. return;
  86886. }
  86887. if (enabled) {
  86888. var geometry = this._scene.enableGeometryBufferRenderer();
  86889. if (!geometry) {
  86890. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  86891. return;
  86892. }
  86893. }
  86894. this._vlsEnabled = enabled;
  86895. this._buildPipeline();
  86896. },
  86897. enumerable: true,
  86898. configurable: true
  86899. });
  86900. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  86901. /**
  86902. * @ignore
  86903. * Specifies if the motion blur effect is enabled
  86904. */
  86905. get: function () {
  86906. return this._motionBlurEnabled;
  86907. },
  86908. set: function (enabled) {
  86909. if (this._motionBlurEnabled === enabled) {
  86910. return;
  86911. }
  86912. this._motionBlurEnabled = enabled;
  86913. this._buildPipeline();
  86914. },
  86915. enumerable: true,
  86916. configurable: true
  86917. });
  86918. Object.defineProperty(StandardRenderingPipeline.prototype, "fxaaEnabled", {
  86919. /**
  86920. * Specifies if anti-aliasing is enabled
  86921. */
  86922. get: function () {
  86923. return this._fxaaEnabled;
  86924. },
  86925. set: function (enabled) {
  86926. if (this._fxaaEnabled === enabled) {
  86927. return;
  86928. }
  86929. this._fxaaEnabled = enabled;
  86930. this._buildPipeline();
  86931. },
  86932. enumerable: true,
  86933. configurable: true
  86934. });
  86935. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  86936. /**
  86937. * Specifies the number of steps used to calculate the volumetric lights
  86938. * Typically in interval [50, 200]
  86939. */
  86940. get: function () {
  86941. return this._volumetricLightStepsCount;
  86942. },
  86943. set: function (count) {
  86944. if (this.volumetricLightPostProcess) {
  86945. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  86946. }
  86947. this._volumetricLightStepsCount = count;
  86948. },
  86949. enumerable: true,
  86950. configurable: true
  86951. });
  86952. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  86953. /**
  86954. * Specifies the number of samples used for the motion blur effect
  86955. * Typically in interval [16, 64]
  86956. */
  86957. get: function () {
  86958. return this._motionBlurSamples;
  86959. },
  86960. set: function (samples) {
  86961. if (this.motionBlurPostProcess) {
  86962. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  86963. }
  86964. this._motionBlurSamples = samples;
  86965. },
  86966. enumerable: true,
  86967. configurable: true
  86968. });
  86969. Object.defineProperty(StandardRenderingPipeline.prototype, "samples", {
  86970. /**
  86971. * Specifies MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  86972. */
  86973. get: function () {
  86974. return this._samples;
  86975. },
  86976. set: function (sampleCount) {
  86977. if (this._samples === sampleCount) {
  86978. return;
  86979. }
  86980. this._samples = sampleCount;
  86981. this._buildPipeline();
  86982. },
  86983. enumerable: true,
  86984. configurable: true
  86985. });
  86986. StandardRenderingPipeline.prototype._buildPipeline = function () {
  86987. var _this = this;
  86988. var ratio = this._ratio;
  86989. var scene = this._scene;
  86990. this._disposePostProcesses();
  86991. this._reset();
  86992. // Create pass post-process
  86993. if (!this._basePostProcess) {
  86994. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  86995. this.originalPostProcess.onApply = function (effect) {
  86996. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  86997. };
  86998. }
  86999. else {
  87000. this.originalPostProcess = this._basePostProcess;
  87001. }
  87002. if (this._bloomEnabled || this._vlsEnabled || this._lensFlareEnabled || this._depthOfFieldEnabled || this._motionBlurEnabled) {
  87003. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  87004. }
  87005. this._currentDepthOfFieldSource = this.originalPostProcess;
  87006. if (this._bloomEnabled) {
  87007. // Create down sample X4 post-process
  87008. this._createDownSampleX4PostProcess(scene, ratio / 2);
  87009. // Create bright pass post-process
  87010. this._createBrightPassPostProcess(scene, ratio / 2);
  87011. // Create gaussian blur post-processes (down sampling blurs)
  87012. this._createBlurPostProcesses(scene, ratio / 4, 1);
  87013. // Create texture adder post-process
  87014. this._createTextureAdderPostProcess(scene, ratio);
  87015. // Create depth-of-field source post-process
  87016. 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);
  87017. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  87018. }
  87019. if (this._vlsEnabled) {
  87020. // Create volumetric light
  87021. this._createVolumetricLightPostProcess(scene, ratio);
  87022. // Create volumetric light final post-process
  87023. 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);
  87024. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  87025. }
  87026. if (this._lensFlareEnabled) {
  87027. // Create lens flare post-process
  87028. this._createLensFlarePostProcess(scene, ratio);
  87029. // Create depth-of-field source post-process post lens-flare and disable it now
  87030. 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);
  87031. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  87032. }
  87033. if (this._hdrEnabled) {
  87034. // Create luminance
  87035. this._createLuminancePostProcesses(scene, this._floatTextureType);
  87036. // Create HDR
  87037. this._createHdrPostProcess(scene, ratio);
  87038. // Create depth-of-field source post-process post hdr and disable it now
  87039. 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);
  87040. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  87041. }
  87042. if (this._depthOfFieldEnabled) {
  87043. // Create gaussian blur used by depth-of-field
  87044. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  87045. // Create depth-of-field post-process
  87046. this._createDepthOfFieldPostProcess(scene, ratio);
  87047. }
  87048. if (this._motionBlurEnabled) {
  87049. // Create motion blur post-process
  87050. this._createMotionBlurPostProcess(scene, ratio);
  87051. }
  87052. if (this._fxaaEnabled) {
  87053. // Create fxaa post-process
  87054. this.fxaaPostProcess = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  87055. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRFxaa", function () { return _this.fxaaPostProcess; }, true));
  87056. }
  87057. if (this._cameras !== null) {
  87058. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  87059. }
  87060. if (!this._enableMSAAOnFirstPostProcess(this._samples) && this._samples > 1) {
  87061. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  87062. }
  87063. };
  87064. // Down Sample X4 Post-Processs
  87065. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  87066. var _this = this;
  87067. var downSampleX4Offsets = new Array(32);
  87068. 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);
  87069. this.downSampleX4PostProcess.onApply = function (effect) {
  87070. var id = 0;
  87071. var width = _this.downSampleX4PostProcess.width;
  87072. var height = _this.downSampleX4PostProcess.height;
  87073. for (var i = -2; i < 2; i++) {
  87074. for (var j = -2; j < 2; j++) {
  87075. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  87076. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  87077. id += 2;
  87078. }
  87079. }
  87080. effect.setArray2("dsOffsets", downSampleX4Offsets);
  87081. };
  87082. // Add to pipeline
  87083. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  87084. };
  87085. // Brightpass Post-Process
  87086. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  87087. var _this = this;
  87088. var brightOffsets = new Array(8);
  87089. 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);
  87090. this.brightPassPostProcess.onApply = function (effect) {
  87091. var sU = (1.0 / _this.brightPassPostProcess.width);
  87092. var sV = (1.0 / _this.brightPassPostProcess.height);
  87093. brightOffsets[0] = -0.5 * sU;
  87094. brightOffsets[1] = 0.5 * sV;
  87095. brightOffsets[2] = 0.5 * sU;
  87096. brightOffsets[3] = 0.5 * sV;
  87097. brightOffsets[4] = -0.5 * sU;
  87098. brightOffsets[5] = -0.5 * sV;
  87099. brightOffsets[6] = 0.5 * sU;
  87100. brightOffsets[7] = -0.5 * sV;
  87101. effect.setArray2("dsOffsets", brightOffsets);
  87102. effect.setFloat("brightThreshold", _this.brightThreshold);
  87103. };
  87104. // Add to pipeline
  87105. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  87106. };
  87107. // Create blur H&V post-processes
  87108. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  87109. var _this = this;
  87110. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  87111. var engine = scene.getEngine();
  87112. 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);
  87113. 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);
  87114. blurX.onActivateObservable.add(function () {
  87115. var dw = blurX.width / engine.getRenderWidth();
  87116. blurX.kernel = _this[blurWidthKey] * dw;
  87117. });
  87118. blurY.onActivateObservable.add(function () {
  87119. var dw = blurY.height / engine.getRenderHeight();
  87120. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  87121. });
  87122. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  87123. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  87124. this.blurHPostProcesses.push(blurX);
  87125. this.blurVPostProcesses.push(blurY);
  87126. };
  87127. // Create texture adder post-process
  87128. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  87129. var _this = this;
  87130. 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);
  87131. this.textureAdderPostProcess.onApply = function (effect) {
  87132. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  87133. effect.setTexture("lensSampler", _this.lensTexture);
  87134. effect.setFloat("exposure", _this.exposure);
  87135. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  87136. };
  87137. // Add to pipeline
  87138. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  87139. };
  87140. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  87141. var _this = this;
  87142. var geometryRenderer = scene.enableGeometryBufferRenderer();
  87143. geometryRenderer.enablePosition = true;
  87144. var geometry = geometryRenderer.getGBuffer();
  87145. // Base post-process
  87146. 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));
  87147. var depthValues = BABYLON.Vector2.Zero();
  87148. this.volumetricLightPostProcess.onApply = function (effect) {
  87149. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  87150. var generator = _this.sourceLight.getShadowGenerator();
  87151. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  87152. effect.setTexture("positionSampler", geometry.textures[2]);
  87153. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  87154. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  87155. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  87156. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  87157. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  87158. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  87159. depthValues.x = _this.sourceLight.getDepthMinZ(_this._scene.activeCamera);
  87160. depthValues.y = _this.sourceLight.getDepthMaxZ(_this._scene.activeCamera);
  87161. effect.setVector2("depthValues", depthValues);
  87162. }
  87163. };
  87164. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  87165. // Smooth
  87166. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  87167. // Merge
  87168. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  87169. this.volumetricLightMergePostProces.onApply = function (effect) {
  87170. effect.setTextureFromPostProcess("originalSampler", _this._bloomEnabled ? _this.textureAdderFinalPostProcess : _this.originalPostProcess);
  87171. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  87172. };
  87173. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  87174. };
  87175. // Create luminance
  87176. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  87177. var _this = this;
  87178. // Create luminance
  87179. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  87180. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  87181. var offsets = [];
  87182. this.luminancePostProcess.onApply = function (effect) {
  87183. var sU = (1.0 / _this.luminancePostProcess.width);
  87184. var sV = (1.0 / _this.luminancePostProcess.height);
  87185. offsets[0] = -0.5 * sU;
  87186. offsets[1] = 0.5 * sV;
  87187. offsets[2] = 0.5 * sU;
  87188. offsets[3] = 0.5 * sV;
  87189. offsets[4] = -0.5 * sU;
  87190. offsets[5] = -0.5 * sV;
  87191. offsets[6] = 0.5 * sU;
  87192. offsets[7] = -0.5 * sV;
  87193. effect.setArray2("lumOffsets", offsets);
  87194. };
  87195. // Add to pipeline
  87196. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  87197. // Create down sample luminance
  87198. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  87199. var size = Math.pow(3, i);
  87200. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  87201. if (i === 0) {
  87202. defines += "#define FINAL_DOWN_SAMPLER";
  87203. }
  87204. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  87205. this.luminanceDownSamplePostProcesses.push(postProcess);
  87206. }
  87207. // Create callbacks and add effects
  87208. var lastLuminance = this.luminancePostProcess;
  87209. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  87210. var downSampleOffsets = new Array(18);
  87211. pp.onApply = function (effect) {
  87212. if (!lastLuminance) {
  87213. return;
  87214. }
  87215. var id = 0;
  87216. for (var x = -1; x < 2; x++) {
  87217. for (var y = -1; y < 2; y++) {
  87218. downSampleOffsets[id] = x / lastLuminance.width;
  87219. downSampleOffsets[id + 1] = y / lastLuminance.height;
  87220. id += 2;
  87221. }
  87222. }
  87223. effect.setArray2("dsOffsets", downSampleOffsets);
  87224. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  87225. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  87226. lastLuminance = _this.luminancePostProcess;
  87227. }
  87228. else {
  87229. lastLuminance = pp;
  87230. }
  87231. };
  87232. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  87233. pp.onAfterRender = function (effect) {
  87234. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  87235. 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);
  87236. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  87237. };
  87238. }
  87239. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  87240. });
  87241. };
  87242. // Create HDR post-process
  87243. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  87244. var _this = this;
  87245. 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);
  87246. var outputLiminance = 1;
  87247. var time = 0;
  87248. var lastTime = 0;
  87249. this.hdrPostProcess.onApply = function (effect) {
  87250. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  87251. time += scene.getEngine().getDeltaTime();
  87252. if (outputLiminance < 0) {
  87253. outputLiminance = _this._hdrCurrentLuminance;
  87254. }
  87255. else {
  87256. var dt = (lastTime - time) / 1000.0;
  87257. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  87258. outputLiminance += _this.hdrDecreaseRate * dt;
  87259. }
  87260. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  87261. outputLiminance -= _this.hdrIncreaseRate * dt;
  87262. }
  87263. else {
  87264. outputLiminance = _this._hdrCurrentLuminance;
  87265. }
  87266. }
  87267. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  87268. effect.setFloat("averageLuminance", outputLiminance);
  87269. lastTime = time;
  87270. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  87271. };
  87272. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  87273. };
  87274. // Create lens flare post-process
  87275. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  87276. var _this = this;
  87277. 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);
  87278. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  87279. this._createBlurPostProcesses(scene, ratio / 4, 2);
  87280. 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);
  87281. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  87282. var resolution = new BABYLON.Vector2(0, 0);
  87283. // Lens flare
  87284. this.lensFlarePostProcess.onApply = function (effect) {
  87285. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  87286. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  87287. effect.setFloat("strength", _this.lensFlareStrength);
  87288. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  87289. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  87290. // Shift
  87291. resolution.x = _this.lensFlarePostProcess.width;
  87292. resolution.y = _this.lensFlarePostProcess.height;
  87293. effect.setVector2("resolution", resolution);
  87294. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  87295. };
  87296. // Compose
  87297. 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);
  87298. 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);
  87299. this.lensFlareComposePostProcess.onApply = function (effect) {
  87300. if (!_this._scene.activeCamera) {
  87301. return;
  87302. }
  87303. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  87304. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  87305. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  87306. // Lens start rotation matrix
  87307. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  87308. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  87309. 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));
  87310. camRot *= 4.0;
  87311. 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);
  87312. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  87313. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  87314. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  87315. };
  87316. };
  87317. // Create depth-of-field post-process
  87318. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  87319. var _this = this;
  87320. 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);
  87321. this.depthOfFieldPostProcess.onApply = function (effect) {
  87322. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  87323. effect.setTexture("depthSampler", _this._getDepthTexture());
  87324. effect.setFloat("distance", _this.depthOfFieldDistance);
  87325. };
  87326. // Add to pipeline
  87327. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  87328. };
  87329. // Create motion blur post-process
  87330. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  87331. var _this = this;
  87332. 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);
  87333. var motionScale = 0;
  87334. var prevViewProjection = BABYLON.Matrix.Identity();
  87335. var invViewProjection = BABYLON.Matrix.Identity();
  87336. var viewProjection = BABYLON.Matrix.Identity();
  87337. var screenSize = BABYLON.Vector2.Zero();
  87338. this.motionBlurPostProcess.onApply = function (effect) {
  87339. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  87340. viewProjection.invertToRef(invViewProjection);
  87341. effect.setMatrix("inverseViewProjection", invViewProjection);
  87342. effect.setMatrix("prevViewProjection", prevViewProjection);
  87343. prevViewProjection = viewProjection;
  87344. screenSize.x = _this.motionBlurPostProcess.width;
  87345. screenSize.y = _this.motionBlurPostProcess.height;
  87346. effect.setVector2("screenSize", screenSize);
  87347. motionScale = scene.getEngine().getFps() / 60.0;
  87348. effect.setFloat("motionScale", motionScale);
  87349. effect.setFloat("motionStrength", _this.motionStrength);
  87350. effect.setTexture("depthSampler", _this._getDepthTexture());
  87351. };
  87352. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  87353. };
  87354. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  87355. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  87356. var renderer = this._scene.enableGeometryBufferRenderer();
  87357. return renderer.getGBuffer().textures[0];
  87358. }
  87359. return this._scene.enableDepthRenderer().getDepthMap();
  87360. };
  87361. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  87362. for (var i = 0; i < this._cameras.length; i++) {
  87363. var camera = this._cameras[i];
  87364. if (this.originalPostProcess) {
  87365. this.originalPostProcess.dispose(camera);
  87366. }
  87367. if (this.downSampleX4PostProcess) {
  87368. this.downSampleX4PostProcess.dispose(camera);
  87369. }
  87370. if (this.brightPassPostProcess) {
  87371. this.brightPassPostProcess.dispose(camera);
  87372. }
  87373. if (this.textureAdderPostProcess) {
  87374. this.textureAdderPostProcess.dispose(camera);
  87375. }
  87376. if (this.textureAdderFinalPostProcess) {
  87377. this.textureAdderFinalPostProcess.dispose(camera);
  87378. }
  87379. if (this.volumetricLightPostProcess) {
  87380. this.volumetricLightPostProcess.dispose(camera);
  87381. }
  87382. if (this.volumetricLightSmoothXPostProcess) {
  87383. this.volumetricLightSmoothXPostProcess.dispose(camera);
  87384. }
  87385. if (this.volumetricLightSmoothYPostProcess) {
  87386. this.volumetricLightSmoothYPostProcess.dispose(camera);
  87387. }
  87388. if (this.volumetricLightMergePostProces) {
  87389. this.volumetricLightMergePostProces.dispose(camera);
  87390. }
  87391. if (this.volumetricLightFinalPostProcess) {
  87392. this.volumetricLightFinalPostProcess.dispose(camera);
  87393. }
  87394. if (this.lensFlarePostProcess) {
  87395. this.lensFlarePostProcess.dispose(camera);
  87396. }
  87397. if (this.lensFlareComposePostProcess) {
  87398. this.lensFlareComposePostProcess.dispose(camera);
  87399. }
  87400. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  87401. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  87402. }
  87403. if (this.luminancePostProcess) {
  87404. this.luminancePostProcess.dispose(camera);
  87405. }
  87406. if (this.hdrPostProcess) {
  87407. this.hdrPostProcess.dispose(camera);
  87408. }
  87409. if (this.hdrFinalPostProcess) {
  87410. this.hdrFinalPostProcess.dispose(camera);
  87411. }
  87412. if (this.depthOfFieldPostProcess) {
  87413. this.depthOfFieldPostProcess.dispose(camera);
  87414. }
  87415. if (this.motionBlurPostProcess) {
  87416. this.motionBlurPostProcess.dispose(camera);
  87417. }
  87418. if (this.fxaaPostProcess) {
  87419. this.fxaaPostProcess.dispose(camera);
  87420. }
  87421. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  87422. this.blurHPostProcesses[j].dispose(camera);
  87423. }
  87424. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  87425. this.blurVPostProcesses[j].dispose(camera);
  87426. }
  87427. }
  87428. this.originalPostProcess = null;
  87429. this.downSampleX4PostProcess = null;
  87430. this.brightPassPostProcess = null;
  87431. this.textureAdderPostProcess = null;
  87432. this.textureAdderFinalPostProcess = null;
  87433. this.volumetricLightPostProcess = null;
  87434. this.volumetricLightSmoothXPostProcess = null;
  87435. this.volumetricLightSmoothYPostProcess = null;
  87436. this.volumetricLightMergePostProces = null;
  87437. this.volumetricLightFinalPostProcess = null;
  87438. this.lensFlarePostProcess = null;
  87439. this.lensFlareComposePostProcess = null;
  87440. this.luminancePostProcess = null;
  87441. this.hdrPostProcess = null;
  87442. this.hdrFinalPostProcess = null;
  87443. this.depthOfFieldPostProcess = null;
  87444. this.motionBlurPostProcess = null;
  87445. this.fxaaPostProcess = null;
  87446. this.luminanceDownSamplePostProcesses = [];
  87447. this.blurHPostProcesses = [];
  87448. this.blurVPostProcesses = [];
  87449. };
  87450. /**
  87451. * Dispose of the pipeline and stop all post processes
  87452. */
  87453. StandardRenderingPipeline.prototype.dispose = function () {
  87454. this._disposePostProcesses();
  87455. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  87456. _super.prototype.dispose.call(this);
  87457. };
  87458. /**
  87459. * Serialize the rendering pipeline (Used when exporting)
  87460. * @returns the serialized object
  87461. */
  87462. StandardRenderingPipeline.prototype.serialize = function () {
  87463. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  87464. if (this.sourceLight) {
  87465. serializationObject.sourceLightId = this.sourceLight.id;
  87466. }
  87467. serializationObject.customType = "StandardRenderingPipeline";
  87468. return serializationObject;
  87469. };
  87470. /**
  87471. * Parse the serialized pipeline
  87472. * @param source Source pipeline.
  87473. * @param scene The scene to load the pipeline to.
  87474. * @param rootUrl The URL of the serialized pipeline.
  87475. * @returns An instantiated pipeline from the serialized object.
  87476. */
  87477. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  87478. var p = BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  87479. if (source.sourceLightId) {
  87480. p.sourceLight = scene.getLightByID(source.sourceLightId);
  87481. }
  87482. return p;
  87483. };
  87484. /**
  87485. * Luminance steps
  87486. */
  87487. StandardRenderingPipeline.LuminanceSteps = 6;
  87488. __decorate([
  87489. BABYLON.serialize()
  87490. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  87491. __decorate([
  87492. BABYLON.serialize()
  87493. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  87494. __decorate([
  87495. BABYLON.serialize()
  87496. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  87497. __decorate([
  87498. BABYLON.serialize()
  87499. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  87500. __decorate([
  87501. BABYLON.serializeAsTexture("lensTexture")
  87502. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  87503. __decorate([
  87504. BABYLON.serialize()
  87505. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  87506. __decorate([
  87507. BABYLON.serialize()
  87508. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  87509. __decorate([
  87510. BABYLON.serialize()
  87511. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  87512. __decorate([
  87513. BABYLON.serialize()
  87514. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  87515. __decorate([
  87516. BABYLON.serialize()
  87517. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  87518. __decorate([
  87519. BABYLON.serialize()
  87520. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  87521. __decorate([
  87522. BABYLON.serializeAsTexture("lensColorTexture")
  87523. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  87524. __decorate([
  87525. BABYLON.serialize()
  87526. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  87527. __decorate([
  87528. BABYLON.serialize()
  87529. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  87530. __decorate([
  87531. BABYLON.serialize()
  87532. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  87533. __decorate([
  87534. BABYLON.serialize()
  87535. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  87536. __decorate([
  87537. BABYLON.serializeAsTexture("lensStarTexture")
  87538. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  87539. __decorate([
  87540. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  87541. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  87542. __decorate([
  87543. BABYLON.serialize()
  87544. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  87545. __decorate([
  87546. BABYLON.serialize()
  87547. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  87548. __decorate([
  87549. BABYLON.serialize()
  87550. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  87551. __decorate([
  87552. BABYLON.serialize()
  87553. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  87554. __decorate([
  87555. BABYLON.serialize()
  87556. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  87557. __decorate([
  87558. BABYLON.serialize()
  87559. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  87560. __decorate([
  87561. BABYLON.serialize()
  87562. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  87563. __decorate([
  87564. BABYLON.serialize()
  87565. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  87566. __decorate([
  87567. BABYLON.serialize()
  87568. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  87569. __decorate([
  87570. BABYLON.serialize()
  87571. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  87572. __decorate([
  87573. BABYLON.serialize()
  87574. ], StandardRenderingPipeline.prototype, "fxaaEnabled", null);
  87575. __decorate([
  87576. BABYLON.serialize()
  87577. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  87578. __decorate([
  87579. BABYLON.serialize()
  87580. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  87581. __decorate([
  87582. BABYLON.serialize()
  87583. ], StandardRenderingPipeline.prototype, "samples", null);
  87584. return StandardRenderingPipeline;
  87585. }(BABYLON.PostProcessRenderPipeline));
  87586. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  87587. })(BABYLON || (BABYLON = {}));
  87588. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  87589. var BABYLON;
  87590. (function (BABYLON) {
  87591. /**
  87592. * Fxaa post process
  87593. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses#fxaa
  87594. */
  87595. var FxaaPostProcess = /** @class */ (function (_super) {
  87596. __extends(FxaaPostProcess, _super);
  87597. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  87598. if (camera === void 0) { camera = null; }
  87599. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  87600. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa", undefined, true) || this;
  87601. var defines = _this._getDefines();
  87602. _this.updateEffect(defines);
  87603. _this.onApplyObservable.add(function (effect) {
  87604. var texelSize = _this.texelSize;
  87605. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  87606. });
  87607. return _this;
  87608. }
  87609. FxaaPostProcess.prototype._getDefines = function () {
  87610. var engine = this.getEngine();
  87611. if (!engine) {
  87612. return null;
  87613. }
  87614. var glInfo = engine.getGlInfo();
  87615. if (glInfo && glInfo.renderer && glInfo.renderer.toLowerCase().indexOf("mali") > -1) {
  87616. return "#define MALI 1\n";
  87617. }
  87618. return null;
  87619. };
  87620. return FxaaPostProcess;
  87621. }(BABYLON.PostProcess));
  87622. BABYLON.FxaaPostProcess = FxaaPostProcess;
  87623. })(BABYLON || (BABYLON = {}));
  87624. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  87625. var BABYLON;
  87626. (function (BABYLON) {
  87627. /**
  87628. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  87629. */
  87630. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  87631. __extends(ChromaticAberrationPostProcess, _super);
  87632. /**
  87633. * Creates a new instance ChromaticAberrationPostProcess
  87634. * @param name The name of the effect.
  87635. * @param screenWidth The width of the screen to apply the effect on.
  87636. * @param screenHeight The height of the screen to apply the effect on.
  87637. * @param options The required width/height ratio to downsize to before computing the render pass.
  87638. * @param camera The camera to apply the render pass to.
  87639. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  87640. * @param engine The engine which the post process will be applied. (default: current engine)
  87641. * @param reusable If the post process can be reused on the same frame. (default: false)
  87642. * @param textureType Type of textures used when performing the post process. (default: 0)
  87643. * @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)
  87644. */
  87645. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  87646. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  87647. if (blockCompilation === void 0) { blockCompilation = false; }
  87648. 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;
  87649. /**
  87650. * The amount of seperation of rgb channels (default: 30)
  87651. */
  87652. _this.aberrationAmount = 30;
  87653. /**
  87654. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  87655. */
  87656. _this.radialIntensity = 0;
  87657. /**
  87658. * 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))
  87659. */
  87660. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  87661. /**
  87662. * 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))
  87663. */
  87664. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  87665. _this.onApplyObservable.add(function (effect) {
  87666. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  87667. effect.setFloat('screen_width', screenWidth);
  87668. effect.setFloat('screen_height', screenHeight);
  87669. effect.setFloat('radialIntensity', _this.radialIntensity);
  87670. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  87671. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  87672. });
  87673. return _this;
  87674. }
  87675. return ChromaticAberrationPostProcess;
  87676. }(BABYLON.PostProcess));
  87677. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  87678. })(BABYLON || (BABYLON = {}));
  87679. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  87680. var BABYLON;
  87681. (function (BABYLON) {
  87682. /**
  87683. * The GrainPostProcess adds noise to the image at mid luminance levels
  87684. */
  87685. var GrainPostProcess = /** @class */ (function (_super) {
  87686. __extends(GrainPostProcess, _super);
  87687. /**
  87688. * Creates a new instance of @see GrainPostProcess
  87689. * @param name The name of the effect.
  87690. * @param options The required width/height ratio to downsize to before computing the render pass.
  87691. * @param camera The camera to apply the render pass to.
  87692. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  87693. * @param engine The engine which the post process will be applied. (default: current engine)
  87694. * @param reusable If the post process can be reused on the same frame. (default: false)
  87695. * @param textureType Type of textures used when performing the post process. (default: 0)
  87696. * @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)
  87697. */
  87698. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  87699. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  87700. if (blockCompilation === void 0) { blockCompilation = false; }
  87701. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  87702. /**
  87703. * The intensity of the grain added (default: 30)
  87704. */
  87705. _this.intensity = 30;
  87706. /**
  87707. * If the grain should be randomized on every frame
  87708. */
  87709. _this.animated = false;
  87710. _this.onApplyObservable.add(function (effect) {
  87711. effect.setFloat('intensity', _this.intensity);
  87712. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  87713. });
  87714. return _this;
  87715. }
  87716. return GrainPostProcess;
  87717. }(BABYLON.PostProcess));
  87718. BABYLON.GrainPostProcess = GrainPostProcess;
  87719. })(BABYLON || (BABYLON = {}));
  87720. //# sourceMappingURL=babylon.grainPostProcess.js.map
  87721. var BABYLON;
  87722. (function (BABYLON) {
  87723. /**
  87724. * The SharpenPostProcess applies a sharpen kernel to every pixel
  87725. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  87726. */
  87727. var SharpenPostProcess = /** @class */ (function (_super) {
  87728. __extends(SharpenPostProcess, _super);
  87729. /**
  87730. * Creates a new instance ConvolutionPostProcess
  87731. * @param name The name of the effect.
  87732. * @param options The required width/height ratio to downsize to before computing the render pass.
  87733. * @param camera The camera to apply the render pass to.
  87734. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  87735. * @param engine The engine which the post process will be applied. (default: current engine)
  87736. * @param reusable If the post process can be reused on the same frame. (default: false)
  87737. * @param textureType Type of textures used when performing the post process. (default: 0)
  87738. * @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)
  87739. */
  87740. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  87741. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  87742. if (blockCompilation === void 0) { blockCompilation = false; }
  87743. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  87744. /**
  87745. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  87746. */
  87747. _this.colorAmount = 1.0;
  87748. /**
  87749. * How much sharpness should be applied (default: 0.3)
  87750. */
  87751. _this.edgeAmount = 0.3;
  87752. _this.onApply = function (effect) {
  87753. effect.setFloat2("screenSize", _this.width, _this.height);
  87754. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  87755. };
  87756. return _this;
  87757. }
  87758. return SharpenPostProcess;
  87759. }(BABYLON.PostProcess));
  87760. BABYLON.SharpenPostProcess = SharpenPostProcess;
  87761. })(BABYLON || (BABYLON = {}));
  87762. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  87763. var BABYLON;
  87764. (function (BABYLON) {
  87765. /**
  87766. * The Blur Post Process which blurs an image based on a kernel and direction.
  87767. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  87768. */
  87769. var BlurPostProcess = /** @class */ (function (_super) {
  87770. __extends(BlurPostProcess, _super);
  87771. /**
  87772. * Creates a new instance BlurPostProcess
  87773. * @param name The name of the effect.
  87774. * @param direction The direction in which to blur the image.
  87775. * @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.
  87776. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  87777. * @param camera The camera to apply the render pass to.
  87778. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  87779. * @param engine The engine which the post process will be applied. (default: current engine)
  87780. * @param reusable If the post process can be reused on the same frame. (default: false)
  87781. * @param textureType Type of textures used when performing the post process. (default: 0)
  87782. * @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)
  87783. */
  87784. function BlurPostProcess(name,
  87785. /** The direction in which to blur the image. */
  87786. direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  87787. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  87788. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  87789. if (defines === void 0) { defines = ""; }
  87790. if (blockCompilation === void 0) { blockCompilation = false; }
  87791. 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;
  87792. _this.direction = direction;
  87793. _this.blockCompilation = blockCompilation;
  87794. _this._packedFloat = false;
  87795. _this._staticDefines = "";
  87796. _this._staticDefines = defines;
  87797. _this.onApplyObservable.add(function (effect) {
  87798. if (_this._outputTexture) {
  87799. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  87800. }
  87801. else {
  87802. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  87803. }
  87804. });
  87805. _this.kernel = kernel;
  87806. return _this;
  87807. }
  87808. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  87809. /**
  87810. * Gets the length in pixels of the blur sample region
  87811. */
  87812. get: function () {
  87813. return this._idealKernel;
  87814. },
  87815. /**
  87816. * Sets the length in pixels of the blur sample region
  87817. */
  87818. set: function (v) {
  87819. if (this._idealKernel === v) {
  87820. return;
  87821. }
  87822. v = Math.max(v, 1);
  87823. this._idealKernel = v;
  87824. this._kernel = this._nearestBestKernel(v);
  87825. if (!this.blockCompilation) {
  87826. this._updateParameters();
  87827. }
  87828. },
  87829. enumerable: true,
  87830. configurable: true
  87831. });
  87832. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  87833. /**
  87834. * Gets wether or not the blur is unpacking/repacking floats
  87835. */
  87836. get: function () {
  87837. return this._packedFloat;
  87838. },
  87839. /**
  87840. * Sets wether or not the blur needs to unpack/repack floats
  87841. */
  87842. set: function (v) {
  87843. if (this._packedFloat === v) {
  87844. return;
  87845. }
  87846. this._packedFloat = v;
  87847. if (!this.blockCompilation) {
  87848. this._updateParameters();
  87849. }
  87850. },
  87851. enumerable: true,
  87852. configurable: true
  87853. });
  87854. /**
  87855. * Updates the effect with the current post process compile time values and recompiles the shader.
  87856. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  87857. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  87858. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  87859. * @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
  87860. * @param onCompiled Called when the shader has been compiled.
  87861. * @param onError Called if there is an error when compiling a shader.
  87862. */
  87863. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  87864. if (defines === void 0) { defines = null; }
  87865. if (uniforms === void 0) { uniforms = null; }
  87866. if (samplers === void 0) { samplers = null; }
  87867. this._updateParameters(onCompiled, onError);
  87868. };
  87869. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  87870. // Generate sampling offsets and weights
  87871. var N = this._kernel;
  87872. var centerIndex = (N - 1) / 2;
  87873. // Generate Gaussian sampling weights over kernel
  87874. var offsets = [];
  87875. var weights = [];
  87876. var totalWeight = 0;
  87877. for (var i = 0; i < N; i++) {
  87878. var u = i / (N - 1);
  87879. var w = this._gaussianWeight(u * 2.0 - 1);
  87880. offsets[i] = (i - centerIndex);
  87881. weights[i] = w;
  87882. totalWeight += w;
  87883. }
  87884. // Normalize weights
  87885. for (var i = 0; i < weights.length; i++) {
  87886. weights[i] /= totalWeight;
  87887. }
  87888. // Optimize: combine samples to take advantage of hardware linear sampling
  87889. // Walk from left to center, combining pairs (symmetrically)
  87890. var linearSamplingWeights = [];
  87891. var linearSamplingOffsets = [];
  87892. var linearSamplingMap = [];
  87893. for (var i = 0; i <= centerIndex; i += 2) {
  87894. var j = Math.min(i + 1, Math.floor(centerIndex));
  87895. var singleCenterSample = i === j;
  87896. if (singleCenterSample) {
  87897. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  87898. }
  87899. else {
  87900. var sharedCell = j === centerIndex;
  87901. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  87902. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  87903. if (offsetLinear === 0) {
  87904. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  87905. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  87906. }
  87907. else {
  87908. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  87909. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  87910. }
  87911. }
  87912. }
  87913. for (var i = 0; i < linearSamplingMap.length; i++) {
  87914. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  87915. linearSamplingWeights[i] = linearSamplingMap[i].w;
  87916. }
  87917. // Replace with optimized
  87918. offsets = linearSamplingOffsets;
  87919. weights = linearSamplingWeights;
  87920. // Generate shaders
  87921. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  87922. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  87923. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  87924. var defines = "";
  87925. defines += this._staticDefines;
  87926. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  87927. if (this._staticDefines.indexOf("DOF") != -1) {
  87928. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  87929. varyingCount--;
  87930. }
  87931. for (var i = 0; i < varyingCount; i++) {
  87932. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  87933. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  87934. }
  87935. var depCount = 0;
  87936. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  87937. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  87938. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  87939. depCount++;
  87940. }
  87941. if (this.packedFloat) {
  87942. defines += "#define PACKEDFLOAT 1";
  87943. }
  87944. this.blockCompilation = false;
  87945. _super.prototype.updateEffect.call(this, defines, null, null, {
  87946. varyingCount: varyingCount,
  87947. depCount: depCount
  87948. }, onCompiled, onError);
  87949. };
  87950. /**
  87951. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  87952. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  87953. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  87954. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  87955. * The gaps between physical kernels are compensated for in the weighting of the samples
  87956. * @param idealKernel Ideal blur kernel.
  87957. * @return Nearest best kernel.
  87958. */
  87959. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  87960. var v = Math.round(idealKernel);
  87961. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  87962. var k = _a[_i];
  87963. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  87964. return Math.max(k, 3);
  87965. }
  87966. }
  87967. return Math.max(v, 3);
  87968. };
  87969. /**
  87970. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  87971. * @param x The point on the Gaussian distribution to sample.
  87972. * @return the value of the Gaussian function at x.
  87973. */
  87974. BlurPostProcess.prototype._gaussianWeight = function (x) {
  87975. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  87976. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  87977. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  87978. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  87979. // truncated at around 1.3% of peak strength.
  87980. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  87981. var sigma = (1 / 3);
  87982. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  87983. var exponent = -((x * x) / (2.0 * sigma * sigma));
  87984. var weight = (1.0 / denominator) * Math.exp(exponent);
  87985. return weight;
  87986. };
  87987. /**
  87988. * Generates a string that can be used as a floating point number in GLSL.
  87989. * @param x Value to print.
  87990. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  87991. * @return GLSL float string.
  87992. */
  87993. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  87994. if (decimalFigures === void 0) { decimalFigures = 8; }
  87995. return x.toFixed(decimalFigures).replace(/0+$/, '');
  87996. };
  87997. return BlurPostProcess;
  87998. }(BABYLON.PostProcess));
  87999. BABYLON.BlurPostProcess = BlurPostProcess;
  88000. })(BABYLON || (BABYLON = {}));
  88001. //# sourceMappingURL=babylon.blurPostProcess.js.map
  88002. var BABYLON;
  88003. (function (BABYLON) {
  88004. /**
  88005. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  88006. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  88007. * based on samples that have a large difference in distance than the center pixel.
  88008. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  88009. */
  88010. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  88011. __extends(DepthOfFieldBlurPostProcess, _super);
  88012. /**
  88013. * Creates a new instance CircleOfConfusionPostProcess
  88014. * @param name The name of the effect.
  88015. * @param scene The scene the effect belongs to.
  88016. * @param direction The direction the blur should be applied.
  88017. * @param kernel The size of the kernel used to blur.
  88018. * @param options The required width/height ratio to downsize to before computing the render pass.
  88019. * @param camera The camera to apply the render pass to.
  88020. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  88021. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  88022. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  88023. * @param engine The engine which the post process will be applied. (default: current engine)
  88024. * @param reusable If the post process can be reused on the same frame. (default: false)
  88025. * @param textureType Type of textures used when performing the post process. (default: 0)
  88026. * @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)
  88027. */
  88028. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  88029. if (imageToBlur === void 0) { imageToBlur = null; }
  88030. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  88031. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  88032. if (blockCompilation === void 0) { blockCompilation = false; }
  88033. 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;
  88034. _this.direction = direction;
  88035. _this.onApplyObservable.add(function (effect) {
  88036. if (imageToBlur != null) {
  88037. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  88038. }
  88039. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  88040. if (scene.activeCamera) {
  88041. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  88042. }
  88043. });
  88044. return _this;
  88045. }
  88046. return DepthOfFieldBlurPostProcess;
  88047. }(BABYLON.BlurPostProcess));
  88048. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  88049. })(BABYLON || (BABYLON = {}));
  88050. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  88051. var BABYLON;
  88052. (function (BABYLON) {
  88053. /**
  88054. * Options to be set when merging outputs from the default pipeline.
  88055. */
  88056. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  88057. function DepthOfFieldMergePostProcessOptions() {
  88058. }
  88059. return DepthOfFieldMergePostProcessOptions;
  88060. }());
  88061. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  88062. /**
  88063. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  88064. */
  88065. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  88066. __extends(DepthOfFieldMergePostProcess, _super);
  88067. /**
  88068. * Creates a new instance of DepthOfFieldMergePostProcess
  88069. * @param name The name of the effect.
  88070. * @param originalFromInput Post process which's input will be used for the merge.
  88071. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  88072. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  88073. * @param options The required width/height ratio to downsize to before computing the render pass.
  88074. * @param camera The camera to apply the render pass to.
  88075. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  88076. * @param engine The engine which the post process will be applied. (default: current engine)
  88077. * @param reusable If the post process can be reused on the same frame. (default: false)
  88078. * @param textureType Type of textures used when performing the post process. (default: 0)
  88079. * @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)
  88080. */
  88081. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  88082. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  88083. if (blockCompilation === void 0) { blockCompilation = false; }
  88084. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  88085. _this.blurSteps = blurSteps;
  88086. _this.onApplyObservable.add(function (effect) {
  88087. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  88088. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  88089. blurSteps.forEach(function (step, index) {
  88090. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  88091. });
  88092. });
  88093. if (!blockCompilation) {
  88094. _this.updateEffect();
  88095. }
  88096. return _this;
  88097. }
  88098. /**
  88099. * Updates the effect with the current post process compile time values and recompiles the shader.
  88100. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  88101. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  88102. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  88103. * @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
  88104. * @param onCompiled Called when the shader has been compiled.
  88105. * @param onError Called if there is an error when compiling a shader.
  88106. */
  88107. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  88108. if (defines === void 0) { defines = null; }
  88109. if (uniforms === void 0) { uniforms = null; }
  88110. if (samplers === void 0) { samplers = null; }
  88111. if (!defines) {
  88112. defines = "";
  88113. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  88114. }
  88115. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  88116. };
  88117. return DepthOfFieldMergePostProcess;
  88118. }(BABYLON.PostProcess));
  88119. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  88120. })(BABYLON || (BABYLON = {}));
  88121. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  88122. var BABYLON;
  88123. (function (BABYLON) {
  88124. /**
  88125. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  88126. */
  88127. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  88128. __extends(CircleOfConfusionPostProcess, _super);
  88129. /**
  88130. * Creates a new instance CircleOfConfusionPostProcess
  88131. * @param name The name of the effect.
  88132. * @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.
  88133. * @param options The required width/height ratio to downsize to before computing the render pass.
  88134. * @param camera The camera to apply the render pass to.
  88135. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  88136. * @param engine The engine which the post process will be applied. (default: current engine)
  88137. * @param reusable If the post process can be reused on the same frame. (default: false)
  88138. * @param textureType Type of textures used when performing the post process. (default: 0)
  88139. * @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)
  88140. */
  88141. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  88142. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  88143. if (blockCompilation === void 0) { blockCompilation = false; }
  88144. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  88145. /**
  88146. * 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.
  88147. */
  88148. _this.lensSize = 50;
  88149. /**
  88150. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  88151. */
  88152. _this.fStop = 1.4;
  88153. /**
  88154. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  88155. */
  88156. _this.focusDistance = 2000;
  88157. /**
  88158. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  88159. */
  88160. _this.focalLength = 50;
  88161. _this._depthTexture = null;
  88162. _this._depthTexture = depthTexture;
  88163. _this.onApplyObservable.add(function (effect) {
  88164. if (!_this._depthTexture) {
  88165. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  88166. return;
  88167. }
  88168. effect.setTexture("depthSampler", _this._depthTexture);
  88169. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  88170. var aperture = _this.lensSize / _this.fStop;
  88171. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  88172. effect.setFloat('focusDistance', _this.focusDistance);
  88173. effect.setFloat('cocPrecalculation', cocPrecalculation);
  88174. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  88175. });
  88176. return _this;
  88177. }
  88178. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  88179. /**
  88180. * 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.
  88181. */
  88182. set: function (value) {
  88183. this._depthTexture = value;
  88184. },
  88185. enumerable: true,
  88186. configurable: true
  88187. });
  88188. return CircleOfConfusionPostProcess;
  88189. }(BABYLON.PostProcess));
  88190. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  88191. })(BABYLON || (BABYLON = {}));
  88192. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  88193. var BABYLON;
  88194. (function (BABYLON) {
  88195. /**
  88196. * Specifies the level of max blur that should be applied when using the depth of field effect
  88197. */
  88198. var DepthOfFieldEffectBlurLevel;
  88199. (function (DepthOfFieldEffectBlurLevel) {
  88200. /**
  88201. * Subtle blur
  88202. */
  88203. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  88204. /**
  88205. * Medium blur
  88206. */
  88207. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  88208. /**
  88209. * Large blur
  88210. */
  88211. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  88212. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  88213. /**
  88214. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  88215. */
  88216. var DepthOfFieldEffect = /** @class */ (function (_super) {
  88217. __extends(DepthOfFieldEffect, _super);
  88218. /**
  88219. * Creates a new instance DepthOfFieldEffect
  88220. * @param scene The scene the effect belongs to.
  88221. * @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.
  88222. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  88223. * @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)
  88224. */
  88225. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  88226. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  88227. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  88228. if (blockCompilation === void 0) { blockCompilation = false; }
  88229. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  88230. return _this._effects;
  88231. }, true) || this;
  88232. /**
  88233. * @hidden Internal post processes in depth of field effect
  88234. */
  88235. _this._effects = [];
  88236. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  88237. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  88238. // 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)
  88239. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  88240. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  88241. _this._depthOfFieldBlurY = [];
  88242. _this._depthOfFieldBlurX = [];
  88243. var blurCount = 1;
  88244. var kernelSize = 15;
  88245. switch (blurLevel) {
  88246. case DepthOfFieldEffectBlurLevel.High: {
  88247. blurCount = 3;
  88248. kernelSize = 51;
  88249. break;
  88250. }
  88251. case DepthOfFieldEffectBlurLevel.Medium: {
  88252. blurCount = 2;
  88253. kernelSize = 31;
  88254. break;
  88255. }
  88256. default: {
  88257. kernelSize = 15;
  88258. blurCount = 1;
  88259. break;
  88260. }
  88261. }
  88262. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  88263. var ratio = 1.0;
  88264. for (var i = 0; i < blurCount; i++) {
  88265. 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);
  88266. blurY.autoClear = false;
  88267. ratio = 0.75 / Math.pow(2, i);
  88268. 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);
  88269. blurX.autoClear = false;
  88270. _this._depthOfFieldBlurY.push(blurY);
  88271. _this._depthOfFieldBlurX.push(blurX);
  88272. }
  88273. // Set all post processes on the effect.
  88274. _this._effects = [_this._circleOfConfusion];
  88275. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  88276. _this._effects.push(_this._depthOfFieldBlurY[i]);
  88277. _this._effects.push(_this._depthOfFieldBlurX[i]);
  88278. }
  88279. // Merge blurred images with original image based on circleOfConfusion
  88280. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  88281. _this._dofMerge.autoClear = false;
  88282. _this._effects.push(_this._dofMerge);
  88283. return _this;
  88284. }
  88285. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  88286. get: function () {
  88287. return this._circleOfConfusion.focalLength;
  88288. },
  88289. /**
  88290. * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
  88291. */
  88292. set: function (value) {
  88293. this._circleOfConfusion.focalLength = value;
  88294. },
  88295. enumerable: true,
  88296. configurable: true
  88297. });
  88298. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  88299. get: function () {
  88300. return this._circleOfConfusion.fStop;
  88301. },
  88302. /**
  88303. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  88304. */
  88305. set: function (value) {
  88306. this._circleOfConfusion.fStop = value;
  88307. },
  88308. enumerable: true,
  88309. configurable: true
  88310. });
  88311. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  88312. get: function () {
  88313. return this._circleOfConfusion.focusDistance;
  88314. },
  88315. /**
  88316. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  88317. */
  88318. set: function (value) {
  88319. this._circleOfConfusion.focusDistance = value;
  88320. },
  88321. enumerable: true,
  88322. configurable: true
  88323. });
  88324. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  88325. get: function () {
  88326. return this._circleOfConfusion.lensSize;
  88327. },
  88328. /**
  88329. * 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.
  88330. */
  88331. set: function (value) {
  88332. this._circleOfConfusion.lensSize = value;
  88333. },
  88334. enumerable: true,
  88335. configurable: true
  88336. });
  88337. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  88338. /**
  88339. * 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.
  88340. */
  88341. set: function (value) {
  88342. this._circleOfConfusion.depthTexture = value;
  88343. },
  88344. enumerable: true,
  88345. configurable: true
  88346. });
  88347. /**
  88348. * Disposes each of the internal effects for a given camera.
  88349. * @param camera The camera to dispose the effect on.
  88350. */
  88351. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  88352. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  88353. this._effects[effectIndex].dispose(camera);
  88354. }
  88355. };
  88356. /**
  88357. * @hidden Internal
  88358. */
  88359. DepthOfFieldEffect.prototype._updateEffects = function () {
  88360. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  88361. this._effects[effectIndex].updateEffect();
  88362. }
  88363. };
  88364. /**
  88365. * Internal
  88366. * @returns if all the contained post processes are ready.
  88367. * @hidden
  88368. */
  88369. DepthOfFieldEffect.prototype._isReady = function () {
  88370. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  88371. if (!this._effects[effectIndex].isReady()) {
  88372. return false;
  88373. }
  88374. }
  88375. return true;
  88376. };
  88377. return DepthOfFieldEffect;
  88378. }(BABYLON.PostProcessRenderEffect));
  88379. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  88380. })(BABYLON || (BABYLON = {}));
  88381. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  88382. var BABYLON;
  88383. (function (BABYLON) {
  88384. /**
  88385. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  88386. */
  88387. var BloomMergePostProcess = /** @class */ (function (_super) {
  88388. __extends(BloomMergePostProcess, _super);
  88389. /**
  88390. * Creates a new instance of @see BloomMergePostProcess
  88391. * @param name The name of the effect.
  88392. * @param originalFromInput Post process which's input will be used for the merge.
  88393. * @param blurred Blurred highlights post process which's output will be used.
  88394. * @param weight Weight of the bloom to be added to the original input.
  88395. * @param options The required width/height ratio to downsize to before computing the render pass.
  88396. * @param camera The camera to apply the render pass to.
  88397. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  88398. * @param engine The engine which the post process will be applied. (default: current engine)
  88399. * @param reusable If the post process can be reused on the same frame. (default: false)
  88400. * @param textureType Type of textures used when performing the post process. (default: 0)
  88401. * @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)
  88402. */
  88403. function BloomMergePostProcess(name, originalFromInput, blurred,
  88404. /** Weight of the bloom to be added to the original input. */
  88405. weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  88406. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  88407. if (blockCompilation === void 0) { blockCompilation = false; }
  88408. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  88409. _this.weight = weight;
  88410. _this.onApplyObservable.add(function (effect) {
  88411. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  88412. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  88413. effect.setFloat("bloomWeight", _this.weight);
  88414. });
  88415. if (!blockCompilation) {
  88416. _this.updateEffect();
  88417. }
  88418. return _this;
  88419. }
  88420. return BloomMergePostProcess;
  88421. }(BABYLON.PostProcess));
  88422. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  88423. })(BABYLON || (BABYLON = {}));
  88424. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  88425. var BABYLON;
  88426. (function (BABYLON) {
  88427. /**
  88428. * 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.
  88429. */
  88430. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  88431. __extends(ExtractHighlightsPostProcess, _super);
  88432. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  88433. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  88434. if (blockCompilation === void 0) { blockCompilation = false; }
  88435. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  88436. /**
  88437. * The luminance threshold, pixels below this value will be set to black.
  88438. */
  88439. _this.threshold = 0.9;
  88440. /** @hidden */
  88441. _this._exposure = 1;
  88442. /**
  88443. * Post process which has the input texture to be used when performing highlight extraction
  88444. * @hidden
  88445. */
  88446. _this._inputPostProcess = null;
  88447. _this.onApplyObservable.add(function (effect) {
  88448. if (_this._inputPostProcess) {
  88449. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  88450. }
  88451. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  88452. effect.setFloat('exposure', _this._exposure);
  88453. });
  88454. return _this;
  88455. }
  88456. return ExtractHighlightsPostProcess;
  88457. }(BABYLON.PostProcess));
  88458. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  88459. })(BABYLON || (BABYLON = {}));
  88460. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  88461. var BABYLON;
  88462. (function (BABYLON) {
  88463. /**
  88464. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  88465. */
  88466. var BloomEffect = /** @class */ (function (_super) {
  88467. __extends(BloomEffect, _super);
  88468. /**
  88469. * Creates a new instance of @see BloomEffect
  88470. * @param scene The scene the effect belongs to.
  88471. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  88472. * @param bloomKernel The size of the kernel to be used when applying the blur.
  88473. * @param bloomWeight The the strength of bloom.
  88474. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  88475. * @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)
  88476. */
  88477. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  88478. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  88479. if (blockCompilation === void 0) { blockCompilation = false; }
  88480. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  88481. return _this._effects;
  88482. }, true) || this;
  88483. _this.bloomScale = bloomScale;
  88484. /**
  88485. * @hidden Internal
  88486. */
  88487. _this._effects = [];
  88488. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  88489. _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);
  88490. _this._blurX.alwaysForcePOT = true;
  88491. _this._blurX.autoClear = false;
  88492. _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);
  88493. _this._blurY.alwaysForcePOT = true;
  88494. _this._blurY.autoClear = false;
  88495. _this.kernel = bloomKernel;
  88496. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  88497. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  88498. _this._merge.autoClear = false;
  88499. _this._effects.push(_this._merge);
  88500. return _this;
  88501. }
  88502. Object.defineProperty(BloomEffect.prototype, "threshold", {
  88503. /**
  88504. * The luminance threshold to find bright areas of the image to bloom.
  88505. */
  88506. get: function () {
  88507. return this._downscale.threshold;
  88508. },
  88509. set: function (value) {
  88510. this._downscale.threshold = value;
  88511. },
  88512. enumerable: true,
  88513. configurable: true
  88514. });
  88515. Object.defineProperty(BloomEffect.prototype, "weight", {
  88516. /**
  88517. * The strength of the bloom.
  88518. */
  88519. get: function () {
  88520. return this._merge.weight;
  88521. },
  88522. set: function (value) {
  88523. this._merge.weight = value;
  88524. },
  88525. enumerable: true,
  88526. configurable: true
  88527. });
  88528. Object.defineProperty(BloomEffect.prototype, "kernel", {
  88529. /**
  88530. * Specifies the size of the bloom blur kernel, relative to the final output size
  88531. */
  88532. get: function () {
  88533. return this._blurX.kernel / this.bloomScale;
  88534. },
  88535. set: function (value) {
  88536. this._blurX.kernel = value * this.bloomScale;
  88537. this._blurY.kernel = value * this.bloomScale;
  88538. },
  88539. enumerable: true,
  88540. configurable: true
  88541. });
  88542. /**
  88543. * Disposes each of the internal effects for a given camera.
  88544. * @param camera The camera to dispose the effect on.
  88545. */
  88546. BloomEffect.prototype.disposeEffects = function (camera) {
  88547. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  88548. this._effects[effectIndex].dispose(camera);
  88549. }
  88550. };
  88551. /**
  88552. * @hidden Internal
  88553. */
  88554. BloomEffect.prototype._updateEffects = function () {
  88555. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  88556. this._effects[effectIndex].updateEffect();
  88557. }
  88558. };
  88559. /**
  88560. * Internal
  88561. * @returns if all the contained post processes are ready.
  88562. * @hidden
  88563. */
  88564. BloomEffect.prototype._isReady = function () {
  88565. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  88566. if (!this._effects[effectIndex].isReady()) {
  88567. return false;
  88568. }
  88569. }
  88570. return true;
  88571. };
  88572. return BloomEffect;
  88573. }(BABYLON.PostProcessRenderEffect));
  88574. BABYLON.BloomEffect = BloomEffect;
  88575. })(BABYLON || (BABYLON = {}));
  88576. //# sourceMappingURL=babylon.bloomEffect.js.map
  88577. var BABYLON;
  88578. (function (BABYLON) {
  88579. /**
  88580. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  88581. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  88582. */
  88583. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  88584. __extends(DefaultRenderingPipeline, _super);
  88585. /**
  88586. * @constructor
  88587. * @param name - The rendering pipeline name (default: "")
  88588. * @param hdr - If high dynamic range textures should be used (default: true)
  88589. * @param scene - The scene linked to this pipeline (default: the last created scene)
  88590. * @param cameras - The array of cameras that the rendering pipeline will be attached to (default: scene.cameras)
  88591. * @param automaticBuild - if false, you will have to manually call prepare() to update the pipeline (default: true)
  88592. */
  88593. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  88594. if (name === void 0) { name = ""; }
  88595. if (hdr === void 0) { hdr = true; }
  88596. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  88597. if (automaticBuild === void 0) { automaticBuild = true; }
  88598. var _this = _super.call(this, scene.getEngine(), name) || this;
  88599. _this._camerasToBeAttached = [];
  88600. /**
  88601. * ID of the sharpen post process,
  88602. */
  88603. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  88604. /**
  88605. * @ignore
  88606. * ID of the image processing post process;
  88607. */
  88608. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  88609. /**
  88610. * @ignore
  88611. * ID of the Fast Approximate Anti-Aliasing post process;
  88612. */
  88613. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  88614. /**
  88615. * ID of the chromatic aberration post process,
  88616. */
  88617. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  88618. /**
  88619. * ID of the grain post process
  88620. */
  88621. _this.GrainPostProcessId = "GrainPostProcessEffect";
  88622. /**
  88623. * Glow post process which adds a glow to emmisive areas of the image
  88624. */
  88625. _this._glowLayer = null;
  88626. /**
  88627. * Animations which can be used to tweak settings over a period of time
  88628. */
  88629. _this.animations = [];
  88630. _this._imageProcessingConfigurationObserver = null;
  88631. // Values
  88632. _this._sharpenEnabled = false;
  88633. _this._bloomEnabled = false;
  88634. _this._depthOfFieldEnabled = false;
  88635. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  88636. _this._fxaaEnabled = false;
  88637. _this._imageProcessingEnabled = true;
  88638. _this._bloomScale = 0.5;
  88639. _this._chromaticAberrationEnabled = false;
  88640. _this._grainEnabled = false;
  88641. _this._buildAllowed = true;
  88642. _this._resizeObserver = null;
  88643. _this._hardwareScaleLevel = 1.0;
  88644. _this._bloomKernel = 64;
  88645. /**
  88646. * Specifies the weight of the bloom in the final rendering
  88647. */
  88648. _this._bloomWeight = 0.15;
  88649. /**
  88650. * Specifies the luma threshold for the area that will be blurred by the bloom
  88651. */
  88652. _this._bloomThreshold = 0.9;
  88653. _this._samples = 1;
  88654. _this._hasCleared = false;
  88655. _this._prevPostProcess = null;
  88656. _this._prevPrevPostProcess = null;
  88657. _this._depthOfFieldSceneObserver = null;
  88658. _this._cameras = cameras || scene.cameras;
  88659. _this._cameras = _this._cameras.slice();
  88660. _this._camerasToBeAttached = _this._cameras.slice();
  88661. _this._buildAllowed = automaticBuild;
  88662. // Initialize
  88663. _this._scene = scene;
  88664. var caps = _this._scene.getEngine().getCaps();
  88665. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  88666. // Misc
  88667. if (_this._hdr) {
  88668. if (caps.textureHalfFloatRender) {
  88669. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  88670. }
  88671. else if (caps.textureFloatRender) {
  88672. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  88673. }
  88674. }
  88675. else {
  88676. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  88677. }
  88678. // Attach
  88679. scene.postProcessRenderPipelineManager.addPipeline(_this);
  88680. var engine = _this._scene.getEngine();
  88681. // Create post processes before hand so they can be modified before enabled.
  88682. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  88683. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  88684. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  88685. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  88686. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  88687. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  88688. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  88689. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  88690. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  88691. _this._resizeObserver = engine.onResizeObservable.add(function () {
  88692. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  88693. _this.bloomKernel = _this.bloomKernel;
  88694. });
  88695. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  88696. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  88697. });
  88698. _this._buildPipeline();
  88699. return _this;
  88700. }
  88701. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  88702. get: function () {
  88703. return this._sharpenEnabled;
  88704. },
  88705. /**
  88706. * Enable or disable the sharpen process from the pipeline
  88707. */
  88708. set: function (enabled) {
  88709. if (this._sharpenEnabled === enabled) {
  88710. return;
  88711. }
  88712. this._sharpenEnabled = enabled;
  88713. this._buildPipeline();
  88714. },
  88715. enumerable: true,
  88716. configurable: true
  88717. });
  88718. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  88719. /**
  88720. * Specifies the size of the bloom blur kernel, relative to the final output size
  88721. */
  88722. get: function () {
  88723. return this._bloomKernel;
  88724. },
  88725. set: function (value) {
  88726. this._bloomKernel = value;
  88727. this.bloom.kernel = value / this._hardwareScaleLevel;
  88728. },
  88729. enumerable: true,
  88730. configurable: true
  88731. });
  88732. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  88733. get: function () {
  88734. return this._bloomWeight;
  88735. },
  88736. /**
  88737. * The strength of the bloom.
  88738. */
  88739. set: function (value) {
  88740. if (this._bloomWeight === value) {
  88741. return;
  88742. }
  88743. this.bloom.weight = value;
  88744. this._bloomWeight = value;
  88745. },
  88746. enumerable: true,
  88747. configurable: true
  88748. });
  88749. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  88750. get: function () {
  88751. return this._bloomThreshold;
  88752. },
  88753. /**
  88754. * The strength of the bloom.
  88755. */
  88756. set: function (value) {
  88757. if (this._bloomThreshold === value) {
  88758. return;
  88759. }
  88760. this.bloom.threshold = value;
  88761. this._bloomThreshold = value;
  88762. },
  88763. enumerable: true,
  88764. configurable: true
  88765. });
  88766. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  88767. get: function () {
  88768. return this._bloomScale;
  88769. },
  88770. /**
  88771. * The scale of the bloom, lower value will provide better performance.
  88772. */
  88773. set: function (value) {
  88774. if (this._bloomScale === value) {
  88775. return;
  88776. }
  88777. this._bloomScale = value;
  88778. // recreate bloom and dispose old as this setting is not dynamic
  88779. this._rebuildBloom();
  88780. this._buildPipeline();
  88781. },
  88782. enumerable: true,
  88783. configurable: true
  88784. });
  88785. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  88786. get: function () {
  88787. return this._bloomEnabled;
  88788. },
  88789. /**
  88790. * Enable or disable the bloom from the pipeline
  88791. */
  88792. set: function (enabled) {
  88793. if (this._bloomEnabled === enabled) {
  88794. return;
  88795. }
  88796. this._bloomEnabled = enabled;
  88797. this._buildPipeline();
  88798. },
  88799. enumerable: true,
  88800. configurable: true
  88801. });
  88802. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  88803. // recreate bloom and dispose old as this setting is not dynamic
  88804. var oldBloom = this.bloom;
  88805. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  88806. this.bloom.threshold = oldBloom.threshold;
  88807. for (var i = 0; i < this._cameras.length; i++) {
  88808. oldBloom.disposeEffects(this._cameras[i]);
  88809. }
  88810. };
  88811. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  88812. /**
  88813. * If the depth of field is enabled.
  88814. */
  88815. get: function () {
  88816. return this._depthOfFieldEnabled;
  88817. },
  88818. set: function (enabled) {
  88819. if (this._depthOfFieldEnabled === enabled) {
  88820. return;
  88821. }
  88822. this._depthOfFieldEnabled = enabled;
  88823. this._buildPipeline();
  88824. },
  88825. enumerable: true,
  88826. configurable: true
  88827. });
  88828. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  88829. /**
  88830. * Blur level of the depth of field effect. (Higher blur will effect performance)
  88831. */
  88832. get: function () {
  88833. return this._depthOfFieldBlurLevel;
  88834. },
  88835. set: function (value) {
  88836. if (this._depthOfFieldBlurLevel === value) {
  88837. return;
  88838. }
  88839. this._depthOfFieldBlurLevel = value;
  88840. // recreate dof and dispose old as this setting is not dynamic
  88841. var oldDof = this.depthOfField;
  88842. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  88843. this.depthOfField.focalLength = oldDof.focalLength;
  88844. this.depthOfField.focusDistance = oldDof.focusDistance;
  88845. this.depthOfField.fStop = oldDof.fStop;
  88846. this.depthOfField.lensSize = oldDof.lensSize;
  88847. for (var i = 0; i < this._cameras.length; i++) {
  88848. oldDof.disposeEffects(this._cameras[i]);
  88849. }
  88850. this._buildPipeline();
  88851. },
  88852. enumerable: true,
  88853. configurable: true
  88854. });
  88855. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  88856. get: function () {
  88857. return this._fxaaEnabled;
  88858. },
  88859. /**
  88860. * If the anti aliasing is enabled.
  88861. */
  88862. set: function (enabled) {
  88863. if (this._fxaaEnabled === enabled) {
  88864. return;
  88865. }
  88866. this._fxaaEnabled = enabled;
  88867. this._buildPipeline();
  88868. },
  88869. enumerable: true,
  88870. configurable: true
  88871. });
  88872. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  88873. get: function () {
  88874. return this._samples;
  88875. },
  88876. /**
  88877. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  88878. */
  88879. set: function (sampleCount) {
  88880. if (this._samples === sampleCount) {
  88881. return;
  88882. }
  88883. this._samples = sampleCount;
  88884. this._buildPipeline();
  88885. },
  88886. enumerable: true,
  88887. configurable: true
  88888. });
  88889. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  88890. get: function () {
  88891. return this._imageProcessingEnabled;
  88892. },
  88893. /**
  88894. * If image processing is enabled.
  88895. */
  88896. set: function (enabled) {
  88897. if (this._imageProcessingEnabled === enabled) {
  88898. return;
  88899. }
  88900. this._imageProcessingEnabled = enabled;
  88901. this._buildPipeline();
  88902. },
  88903. enumerable: true,
  88904. configurable: true
  88905. });
  88906. Object.defineProperty(DefaultRenderingPipeline.prototype, "glowLayerEnabled", {
  88907. get: function () {
  88908. return this._glowLayer == null;
  88909. },
  88910. /**
  88911. * If glow layer is enabled. (Adds a glow effect to emmissive materials)
  88912. */
  88913. set: function (enabled) {
  88914. if (enabled && !this._glowLayer) {
  88915. this._glowLayer = new BABYLON.GlowLayer("", this._scene);
  88916. }
  88917. else if (!enabled && this._glowLayer) {
  88918. this._glowLayer.dispose();
  88919. this._glowLayer = null;
  88920. }
  88921. },
  88922. enumerable: true,
  88923. configurable: true
  88924. });
  88925. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  88926. get: function () {
  88927. return this._chromaticAberrationEnabled;
  88928. },
  88929. /**
  88930. * Enable or disable the chromaticAberration process from the pipeline
  88931. */
  88932. set: function (enabled) {
  88933. if (this._chromaticAberrationEnabled === enabled) {
  88934. return;
  88935. }
  88936. this._chromaticAberrationEnabled = enabled;
  88937. this._buildPipeline();
  88938. },
  88939. enumerable: true,
  88940. configurable: true
  88941. });
  88942. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  88943. get: function () {
  88944. return this._grainEnabled;
  88945. },
  88946. /**
  88947. * Enable or disable the grain process from the pipeline
  88948. */
  88949. set: function (enabled) {
  88950. if (this._grainEnabled === enabled) {
  88951. return;
  88952. }
  88953. this._grainEnabled = enabled;
  88954. this._buildPipeline();
  88955. },
  88956. enumerable: true,
  88957. configurable: true
  88958. });
  88959. /**
  88960. * Force the compilation of the entire pipeline.
  88961. */
  88962. DefaultRenderingPipeline.prototype.prepare = function () {
  88963. var previousState = this._buildAllowed;
  88964. this._buildAllowed = true;
  88965. this._buildPipeline();
  88966. this._buildAllowed = previousState;
  88967. };
  88968. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  88969. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  88970. if (this._hasCleared) {
  88971. postProcess.autoClear = false;
  88972. }
  88973. else {
  88974. postProcess.autoClear = true;
  88975. this._scene.autoClear = false;
  88976. this._hasCleared = true;
  88977. }
  88978. if (!skipTextureSharing) {
  88979. if (this._prevPrevPostProcess) {
  88980. postProcess.shareOutputWith(this._prevPrevPostProcess);
  88981. }
  88982. else {
  88983. postProcess.useOwnOutput();
  88984. }
  88985. if (this._prevPostProcess) {
  88986. this._prevPrevPostProcess = this._prevPostProcess;
  88987. }
  88988. this._prevPostProcess = postProcess;
  88989. }
  88990. };
  88991. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  88992. var _this = this;
  88993. if (!this._buildAllowed) {
  88994. return;
  88995. }
  88996. this._scene.autoClear = true;
  88997. var engine = this._scene.getEngine();
  88998. this._disposePostProcesses();
  88999. if (this._cameras !== null) {
  89000. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  89001. // get back cameras to be used to reattach pipeline
  89002. this._cameras = this._camerasToBeAttached.slice();
  89003. }
  89004. this._reset();
  89005. this._prevPostProcess = null;
  89006. this._prevPrevPostProcess = null;
  89007. this._hasCleared = false;
  89008. if (this.depthOfFieldEnabled) {
  89009. // Multi camera suport
  89010. if (this._cameras.length > 1) {
  89011. for (var _i = 0, _a = this._cameras; _i < _a.length; _i++) {
  89012. var camera = _a[_i];
  89013. var depthRenderer = this._scene.enableDepthRenderer(camera);
  89014. depthRenderer.useOnlyInActiveCamera = true;
  89015. }
  89016. this._depthOfFieldSceneObserver = this._scene.onAfterRenderTargetsRenderObservable.add(function (scene) {
  89017. if (_this._cameras.indexOf(scene.activeCamera) > -1) {
  89018. _this.depthOfField.depthTexture = scene.enableDepthRenderer(scene.activeCamera).getDepthMap();
  89019. }
  89020. });
  89021. }
  89022. else {
  89023. this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
  89024. var depthRenderer = this._scene.enableDepthRenderer(this._cameras[0]);
  89025. this.depthOfField.depthTexture = depthRenderer.getDepthMap();
  89026. }
  89027. if (!this.depthOfField._isReady()) {
  89028. this.depthOfField._updateEffects();
  89029. }
  89030. this.addEffect(this.depthOfField);
  89031. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  89032. }
  89033. else {
  89034. this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
  89035. }
  89036. if (this.bloomEnabled) {
  89037. if (!this.bloom._isReady()) {
  89038. this.bloom._updateEffects();
  89039. }
  89040. this.addEffect(this.bloom);
  89041. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  89042. }
  89043. if (this._imageProcessingEnabled) {
  89044. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  89045. if (this._hdr) {
  89046. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  89047. this._setAutoClearAndTextureSharing(this.imageProcessing);
  89048. }
  89049. else {
  89050. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  89051. }
  89052. }
  89053. if (this.sharpenEnabled) {
  89054. if (!this.sharpen.isReady()) {
  89055. this.sharpen.updateEffect();
  89056. }
  89057. this.addEffect(this._sharpenEffect);
  89058. this._setAutoClearAndTextureSharing(this.sharpen);
  89059. }
  89060. if (this.grainEnabled) {
  89061. if (!this.grain.isReady()) {
  89062. this.grain.updateEffect();
  89063. }
  89064. this.addEffect(this._grainEffect);
  89065. this._setAutoClearAndTextureSharing(this.grain);
  89066. }
  89067. if (this.chromaticAberrationEnabled) {
  89068. if (!this.chromaticAberration.isReady()) {
  89069. this.chromaticAberration.updateEffect();
  89070. }
  89071. this.addEffect(this._chromaticAberrationEffect);
  89072. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  89073. }
  89074. if (this.fxaaEnabled) {
  89075. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  89076. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  89077. this._setAutoClearAndTextureSharing(this.fxaa, true);
  89078. }
  89079. if (this._cameras !== null) {
  89080. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  89081. }
  89082. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  89083. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  89084. }
  89085. };
  89086. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  89087. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  89088. for (var i = 0; i < this._cameras.length; i++) {
  89089. var camera = this._cameras[i];
  89090. if (this.imageProcessing) {
  89091. this.imageProcessing.dispose(camera);
  89092. }
  89093. if (this.fxaa) {
  89094. this.fxaa.dispose(camera);
  89095. }
  89096. // These are created in the constructor and should not be disposed on every pipeline change
  89097. if (disposeNonRecreated) {
  89098. if (this.sharpen) {
  89099. this.sharpen.dispose(camera);
  89100. }
  89101. if (this.depthOfField) {
  89102. this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
  89103. this.depthOfField.disposeEffects(camera);
  89104. }
  89105. if (this.bloom) {
  89106. this.bloom.disposeEffects(camera);
  89107. }
  89108. if (this.chromaticAberration) {
  89109. this.chromaticAberration.dispose(camera);
  89110. }
  89111. if (this.grain) {
  89112. this.grain.dispose(camera);
  89113. }
  89114. if (this._glowLayer) {
  89115. this._glowLayer.dispose();
  89116. }
  89117. }
  89118. }
  89119. this.imageProcessing = null;
  89120. this.fxaa = null;
  89121. if (disposeNonRecreated) {
  89122. this.sharpen = null;
  89123. this._sharpenEffect = null;
  89124. this.depthOfField = null;
  89125. this.bloom = null;
  89126. this.chromaticAberration = null;
  89127. this._chromaticAberrationEffect = null;
  89128. this.grain = null;
  89129. this._grainEffect = null;
  89130. this._glowLayer = null;
  89131. }
  89132. };
  89133. /**
  89134. * Adds a camera to the pipeline
  89135. * @param camera the camera to be added
  89136. */
  89137. DefaultRenderingPipeline.prototype.addCamera = function (camera) {
  89138. this._camerasToBeAttached.push(camera);
  89139. this._buildPipeline();
  89140. };
  89141. /**
  89142. * Removes a camera from the pipeline
  89143. * @param camera the camera to remove
  89144. */
  89145. DefaultRenderingPipeline.prototype.removeCamera = function (camera) {
  89146. var index = this._camerasToBeAttached.indexOf(camera);
  89147. this._camerasToBeAttached.splice(index, 1);
  89148. this._buildPipeline();
  89149. };
  89150. /**
  89151. * Dispose of the pipeline and stop all post processes
  89152. */
  89153. DefaultRenderingPipeline.prototype.dispose = function () {
  89154. this._disposePostProcesses(true);
  89155. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  89156. this._scene.autoClear = true;
  89157. if (this._resizeObserver) {
  89158. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  89159. this._resizeObserver = null;
  89160. }
  89161. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  89162. _super.prototype.dispose.call(this);
  89163. };
  89164. /**
  89165. * Serialize the rendering pipeline (Used when exporting)
  89166. * @returns the serialized object
  89167. */
  89168. DefaultRenderingPipeline.prototype.serialize = function () {
  89169. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  89170. serializationObject.customType = "DefaultRenderingPipeline";
  89171. return serializationObject;
  89172. };
  89173. /**
  89174. * Parse the serialized pipeline
  89175. * @param source Source pipeline.
  89176. * @param scene The scene to load the pipeline to.
  89177. * @param rootUrl The URL of the serialized pipeline.
  89178. * @returns An instantiated pipeline from the serialized object.
  89179. */
  89180. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  89181. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  89182. };
  89183. __decorate([
  89184. BABYLON.serialize()
  89185. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  89186. __decorate([
  89187. BABYLON.serialize()
  89188. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  89189. __decorate([
  89190. BABYLON.serialize()
  89191. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  89192. __decorate([
  89193. BABYLON.serialize()
  89194. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  89195. __decorate([
  89196. BABYLON.serialize()
  89197. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  89198. __decorate([
  89199. BABYLON.serialize()
  89200. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  89201. __decorate([
  89202. BABYLON.serialize()
  89203. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  89204. __decorate([
  89205. BABYLON.serialize()
  89206. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  89207. __decorate([
  89208. BABYLON.serialize()
  89209. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  89210. __decorate([
  89211. BABYLON.serialize()
  89212. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  89213. __decorate([
  89214. BABYLON.serialize()
  89215. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  89216. __decorate([
  89217. BABYLON.serialize()
  89218. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  89219. __decorate([
  89220. BABYLON.serialize()
  89221. ], DefaultRenderingPipeline.prototype, "samples", null);
  89222. __decorate([
  89223. BABYLON.serialize()
  89224. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  89225. __decorate([
  89226. BABYLON.serialize()
  89227. ], DefaultRenderingPipeline.prototype, "glowLayerEnabled", null);
  89228. __decorate([
  89229. BABYLON.serialize()
  89230. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  89231. __decorate([
  89232. BABYLON.serialize()
  89233. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  89234. return DefaultRenderingPipeline;
  89235. }(BABYLON.PostProcessRenderPipeline));
  89236. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  89237. })(BABYLON || (BABYLON = {}));
  89238. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  89239. var BABYLON;
  89240. (function (BABYLON) {
  89241. /**
  89242. * @hidden
  89243. */
  89244. var ImageProcessingConfigurationDefines = /** @class */ (function (_super) {
  89245. __extends(ImageProcessingConfigurationDefines, _super);
  89246. function ImageProcessingConfigurationDefines() {
  89247. var _this = _super.call(this) || this;
  89248. _this.IMAGEPROCESSING = false;
  89249. _this.VIGNETTE = false;
  89250. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  89251. _this.VIGNETTEBLENDMODEOPAQUE = false;
  89252. _this.TONEMAPPING = false;
  89253. _this.TONEMAPPING_ACES = false;
  89254. _this.CONTRAST = false;
  89255. _this.COLORCURVES = false;
  89256. _this.COLORGRADING = false;
  89257. _this.COLORGRADING3D = false;
  89258. _this.SAMPLER3DGREENDEPTH = false;
  89259. _this.SAMPLER3DBGRMAP = false;
  89260. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  89261. _this.EXPOSURE = false;
  89262. _this.rebuild();
  89263. return _this;
  89264. }
  89265. return ImageProcessingConfigurationDefines;
  89266. }(BABYLON.MaterialDefines));
  89267. BABYLON.ImageProcessingConfigurationDefines = ImageProcessingConfigurationDefines;
  89268. /**
  89269. * This groups together the common properties used for image processing either in direct forward pass
  89270. * or through post processing effect depending on the use of the image processing pipeline in your scene
  89271. * or not.
  89272. */
  89273. var ImageProcessingConfiguration = /** @class */ (function () {
  89274. function ImageProcessingConfiguration() {
  89275. /**
  89276. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  89277. */
  89278. this.colorCurves = new BABYLON.ColorCurves();
  89279. this._colorCurvesEnabled = false;
  89280. this._colorGradingEnabled = false;
  89281. this._colorGradingWithGreenDepth = true;
  89282. this._colorGradingBGR = true;
  89283. /** @hidden */
  89284. this._exposure = 1.0;
  89285. this._toneMappingEnabled = false;
  89286. this._toneMappingType = ImageProcessingConfiguration.TONEMAPPING_STANDARD;
  89287. this._contrast = 1.0;
  89288. /**
  89289. * Vignette stretch size.
  89290. */
  89291. this.vignetteStretch = 0;
  89292. /**
  89293. * Vignette centre X Offset.
  89294. */
  89295. this.vignetteCentreX = 0;
  89296. /**
  89297. * Vignette centre Y Offset.
  89298. */
  89299. this.vignetteCentreY = 0;
  89300. /**
  89301. * Vignette weight or intensity of the vignette effect.
  89302. */
  89303. this.vignetteWeight = 1.5;
  89304. /**
  89305. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  89306. * if vignetteEnabled is set to true.
  89307. */
  89308. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  89309. /**
  89310. * Camera field of view used by the Vignette effect.
  89311. */
  89312. this.vignetteCameraFov = 0.5;
  89313. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  89314. this._vignetteEnabled = false;
  89315. this._applyByPostProcess = false;
  89316. this._isEnabled = true;
  89317. /**
  89318. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  89319. */
  89320. this.onUpdateParameters = new BABYLON.Observable();
  89321. }
  89322. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  89323. /**
  89324. * Gets wether the color curves effect is enabled.
  89325. */
  89326. get: function () {
  89327. return this._colorCurvesEnabled;
  89328. },
  89329. /**
  89330. * Sets wether the color curves effect is enabled.
  89331. */
  89332. set: function (value) {
  89333. if (this._colorCurvesEnabled === value) {
  89334. return;
  89335. }
  89336. this._colorCurvesEnabled = value;
  89337. this._updateParameters();
  89338. },
  89339. enumerable: true,
  89340. configurable: true
  89341. });
  89342. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingTexture", {
  89343. /**
  89344. * Color grading LUT texture used in the effect if colorGradingEnabled is set to true
  89345. */
  89346. get: function () {
  89347. return this._colorGradingTexture;
  89348. },
  89349. /**
  89350. * Color grading LUT texture used in the effect if colorGradingEnabled is set to true
  89351. */
  89352. set: function (value) {
  89353. if (this._colorGradingTexture === value) {
  89354. return;
  89355. }
  89356. this._colorGradingTexture = value;
  89357. this._updateParameters();
  89358. },
  89359. enumerable: true,
  89360. configurable: true
  89361. });
  89362. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  89363. /**
  89364. * Gets wether the color grading effect is enabled.
  89365. */
  89366. get: function () {
  89367. return this._colorGradingEnabled;
  89368. },
  89369. /**
  89370. * Sets wether the color grading effect is enabled.
  89371. */
  89372. set: function (value) {
  89373. if (this._colorGradingEnabled === value) {
  89374. return;
  89375. }
  89376. this._colorGradingEnabled = value;
  89377. this._updateParameters();
  89378. },
  89379. enumerable: true,
  89380. configurable: true
  89381. });
  89382. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  89383. /**
  89384. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  89385. */
  89386. get: function () {
  89387. return this._colorGradingWithGreenDepth;
  89388. },
  89389. /**
  89390. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  89391. */
  89392. set: function (value) {
  89393. if (this._colorGradingWithGreenDepth === value) {
  89394. return;
  89395. }
  89396. this._colorGradingWithGreenDepth = value;
  89397. this._updateParameters();
  89398. },
  89399. enumerable: true,
  89400. configurable: true
  89401. });
  89402. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  89403. /**
  89404. * Gets wether the color grading texture contains BGR values.
  89405. */
  89406. get: function () {
  89407. return this._colorGradingBGR;
  89408. },
  89409. /**
  89410. * Sets wether the color grading texture contains BGR values.
  89411. */
  89412. set: function (value) {
  89413. if (this._colorGradingBGR === value) {
  89414. return;
  89415. }
  89416. this._colorGradingBGR = value;
  89417. this._updateParameters();
  89418. },
  89419. enumerable: true,
  89420. configurable: true
  89421. });
  89422. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  89423. /**
  89424. * Gets the Exposure used in the effect.
  89425. */
  89426. get: function () {
  89427. return this._exposure;
  89428. },
  89429. /**
  89430. * Sets the Exposure used in the effect.
  89431. */
  89432. set: function (value) {
  89433. if (this._exposure === value) {
  89434. return;
  89435. }
  89436. this._exposure = value;
  89437. this._updateParameters();
  89438. },
  89439. enumerable: true,
  89440. configurable: true
  89441. });
  89442. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  89443. /**
  89444. * Gets wether the tone mapping effect is enabled.
  89445. */
  89446. get: function () {
  89447. return this._toneMappingEnabled;
  89448. },
  89449. /**
  89450. * Sets wether the tone mapping effect is enabled.
  89451. */
  89452. set: function (value) {
  89453. if (this._toneMappingEnabled === value) {
  89454. return;
  89455. }
  89456. this._toneMappingEnabled = value;
  89457. this._updateParameters();
  89458. },
  89459. enumerable: true,
  89460. configurable: true
  89461. });
  89462. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingType", {
  89463. /**
  89464. * Gets the type of tone mapping effect.
  89465. */
  89466. get: function () {
  89467. return this._toneMappingType;
  89468. },
  89469. /**
  89470. * Sets the type of tone mapping effect used in BabylonJS.
  89471. */
  89472. set: function (value) {
  89473. if (this._toneMappingType === value) {
  89474. return;
  89475. }
  89476. this._toneMappingType = value;
  89477. this._updateParameters();
  89478. },
  89479. enumerable: true,
  89480. configurable: true
  89481. });
  89482. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  89483. /**
  89484. * Gets the contrast used in the effect.
  89485. */
  89486. get: function () {
  89487. return this._contrast;
  89488. },
  89489. /**
  89490. * Sets the contrast used in the effect.
  89491. */
  89492. set: function (value) {
  89493. if (this._contrast === value) {
  89494. return;
  89495. }
  89496. this._contrast = value;
  89497. this._updateParameters();
  89498. },
  89499. enumerable: true,
  89500. configurable: true
  89501. });
  89502. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  89503. /**
  89504. * Gets the vignette blend mode allowing different kind of effect.
  89505. */
  89506. get: function () {
  89507. return this._vignetteBlendMode;
  89508. },
  89509. /**
  89510. * Sets the vignette blend mode allowing different kind of effect.
  89511. */
  89512. set: function (value) {
  89513. if (this._vignetteBlendMode === value) {
  89514. return;
  89515. }
  89516. this._vignetteBlendMode = value;
  89517. this._updateParameters();
  89518. },
  89519. enumerable: true,
  89520. configurable: true
  89521. });
  89522. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  89523. /**
  89524. * Gets wether the vignette effect is enabled.
  89525. */
  89526. get: function () {
  89527. return this._vignetteEnabled;
  89528. },
  89529. /**
  89530. * Sets wether the vignette effect is enabled.
  89531. */
  89532. set: function (value) {
  89533. if (this._vignetteEnabled === value) {
  89534. return;
  89535. }
  89536. this._vignetteEnabled = value;
  89537. this._updateParameters();
  89538. },
  89539. enumerable: true,
  89540. configurable: true
  89541. });
  89542. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  89543. /**
  89544. * Gets wether the image processing is applied through a post process or not.
  89545. */
  89546. get: function () {
  89547. return this._applyByPostProcess;
  89548. },
  89549. /**
  89550. * Sets wether the image processing is applied through a post process or not.
  89551. */
  89552. set: function (value) {
  89553. if (this._applyByPostProcess === value) {
  89554. return;
  89555. }
  89556. this._applyByPostProcess = value;
  89557. this._updateParameters();
  89558. },
  89559. enumerable: true,
  89560. configurable: true
  89561. });
  89562. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  89563. /**
  89564. * Gets wether the image processing is enabled or not.
  89565. */
  89566. get: function () {
  89567. return this._isEnabled;
  89568. },
  89569. /**
  89570. * Sets wether the image processing is enabled or not.
  89571. */
  89572. set: function (value) {
  89573. if (this._isEnabled === value) {
  89574. return;
  89575. }
  89576. this._isEnabled = value;
  89577. this._updateParameters();
  89578. },
  89579. enumerable: true,
  89580. configurable: true
  89581. });
  89582. /**
  89583. * Method called each time the image processing information changes requires to recompile the effect.
  89584. */
  89585. ImageProcessingConfiguration.prototype._updateParameters = function () {
  89586. this.onUpdateParameters.notifyObservers(this);
  89587. };
  89588. /**
  89589. * Gets the current class name.
  89590. * @return "ImageProcessingConfiguration"
  89591. */
  89592. ImageProcessingConfiguration.prototype.getClassName = function () {
  89593. return "ImageProcessingConfiguration";
  89594. };
  89595. /**
  89596. * Prepare the list of uniforms associated with the Image Processing effects.
  89597. * @param uniforms The list of uniforms used in the effect
  89598. * @param defines the list of defines currently in use
  89599. */
  89600. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  89601. if (defines.EXPOSURE) {
  89602. uniforms.push("exposureLinear");
  89603. }
  89604. if (defines.CONTRAST) {
  89605. uniforms.push("contrast");
  89606. }
  89607. if (defines.COLORGRADING) {
  89608. uniforms.push("colorTransformSettings");
  89609. }
  89610. if (defines.VIGNETTE) {
  89611. uniforms.push("vInverseScreenSize");
  89612. uniforms.push("vignetteSettings1");
  89613. uniforms.push("vignetteSettings2");
  89614. }
  89615. if (defines.COLORCURVES) {
  89616. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  89617. }
  89618. };
  89619. /**
  89620. * Prepare the list of samplers associated with the Image Processing effects.
  89621. * @param samplersList The list of uniforms used in the effect
  89622. * @param defines the list of defines currently in use
  89623. */
  89624. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  89625. if (defines.COLORGRADING) {
  89626. samplersList.push("txColorTransform");
  89627. }
  89628. };
  89629. /**
  89630. * Prepare the list of defines associated to the shader.
  89631. * @param defines the list of defines to complete
  89632. * @param forPostProcess Define if we are currently in post process mode or not
  89633. */
  89634. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  89635. if (forPostProcess === void 0) { forPostProcess = false; }
  89636. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  89637. defines.VIGNETTE = false;
  89638. defines.TONEMAPPING = false;
  89639. defines.TONEMAPPING_ACES = false;
  89640. defines.CONTRAST = false;
  89641. defines.EXPOSURE = false;
  89642. defines.COLORCURVES = false;
  89643. defines.COLORGRADING = false;
  89644. defines.COLORGRADING3D = false;
  89645. defines.IMAGEPROCESSING = false;
  89646. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  89647. return;
  89648. }
  89649. defines.VIGNETTE = this.vignetteEnabled;
  89650. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  89651. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  89652. defines.TONEMAPPING = this.toneMappingEnabled;
  89653. switch (this._toneMappingType) {
  89654. case ImageProcessingConfiguration.TONEMAPPING_ACES:
  89655. defines.TONEMAPPING_ACES = true;
  89656. break;
  89657. }
  89658. defines.CONTRAST = (this.contrast !== 1.0);
  89659. defines.EXPOSURE = (this.exposure !== 1.0);
  89660. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  89661. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  89662. if (defines.COLORGRADING) {
  89663. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  89664. }
  89665. else {
  89666. defines.COLORGRADING3D = false;
  89667. }
  89668. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  89669. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  89670. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  89671. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  89672. };
  89673. /**
  89674. * Returns true if all the image processing information are ready.
  89675. * @returns True if ready, otherwise, false
  89676. */
  89677. ImageProcessingConfiguration.prototype.isReady = function () {
  89678. // Color Grading texure can not be none blocking.
  89679. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  89680. };
  89681. /**
  89682. * Binds the image processing to the shader.
  89683. * @param effect The effect to bind to
  89684. * @param aspectRatio Define the current aspect ratio of the effect
  89685. */
  89686. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  89687. if (aspectRatio === void 0) { aspectRatio = 1; }
  89688. // Color Curves
  89689. if (this._colorCurvesEnabled && this.colorCurves) {
  89690. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  89691. }
  89692. // Vignette
  89693. if (this._vignetteEnabled) {
  89694. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  89695. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  89696. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  89697. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  89698. var vignetteScaleX = vignetteScaleY * aspectRatio;
  89699. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  89700. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  89701. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  89702. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  89703. var vignettePower = -2.0 * this.vignetteWeight;
  89704. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  89705. }
  89706. // Exposure
  89707. effect.setFloat("exposureLinear", this.exposure);
  89708. // Contrast
  89709. effect.setFloat("contrast", this.contrast);
  89710. // Color transform settings
  89711. if (this.colorGradingTexture) {
  89712. effect.setTexture("txColorTransform", this.colorGradingTexture);
  89713. var textureSize = this.colorGradingTexture.getSize().height;
  89714. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  89715. 0.5 / textureSize, // textureOffset
  89716. textureSize, // textureSize
  89717. this.colorGradingTexture.level // weight
  89718. );
  89719. }
  89720. };
  89721. /**
  89722. * Clones the current image processing instance.
  89723. * @return The cloned image processing
  89724. */
  89725. ImageProcessingConfiguration.prototype.clone = function () {
  89726. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  89727. };
  89728. /**
  89729. * Serializes the current image processing instance to a json representation.
  89730. * @return a JSON representation
  89731. */
  89732. ImageProcessingConfiguration.prototype.serialize = function () {
  89733. return BABYLON.SerializationHelper.Serialize(this);
  89734. };
  89735. /**
  89736. * Parses the image processing from a json representation.
  89737. * @param source the JSON source to parse
  89738. * @return The parsed image processing
  89739. */
  89740. ImageProcessingConfiguration.Parse = function (source) {
  89741. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  89742. };
  89743. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  89744. /**
  89745. * Used to apply the vignette as a mix with the pixel color.
  89746. */
  89747. get: function () {
  89748. return this._VIGNETTEMODE_MULTIPLY;
  89749. },
  89750. enumerable: true,
  89751. configurable: true
  89752. });
  89753. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  89754. /**
  89755. * Used to apply the vignette as a replacement of the pixel color.
  89756. */
  89757. get: function () {
  89758. return this._VIGNETTEMODE_OPAQUE;
  89759. },
  89760. enumerable: true,
  89761. configurable: true
  89762. });
  89763. /**
  89764. * Default tone mapping applied in BabylonJS.
  89765. */
  89766. ImageProcessingConfiguration.TONEMAPPING_STANDARD = 0;
  89767. /**
  89768. * ACES Tone mapping (used by default in unreal and unity). This can help getting closer
  89769. * to other engines rendering to increase portability.
  89770. */
  89771. ImageProcessingConfiguration.TONEMAPPING_ACES = 1;
  89772. // Static constants associated to the image processing.
  89773. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  89774. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  89775. __decorate([
  89776. BABYLON.serializeAsColorCurves()
  89777. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  89778. __decorate([
  89779. BABYLON.serialize()
  89780. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  89781. __decorate([
  89782. BABYLON.serializeAsTexture("colorGradingTexture")
  89783. ], ImageProcessingConfiguration.prototype, "_colorGradingTexture", void 0);
  89784. __decorate([
  89785. BABYLON.serialize()
  89786. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  89787. __decorate([
  89788. BABYLON.serialize()
  89789. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  89790. __decorate([
  89791. BABYLON.serialize()
  89792. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  89793. __decorate([
  89794. BABYLON.serialize()
  89795. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  89796. __decorate([
  89797. BABYLON.serialize()
  89798. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  89799. __decorate([
  89800. BABYLON.serialize()
  89801. ], ImageProcessingConfiguration.prototype, "_toneMappingType", void 0);
  89802. __decorate([
  89803. BABYLON.serialize()
  89804. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  89805. __decorate([
  89806. BABYLON.serialize()
  89807. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  89808. __decorate([
  89809. BABYLON.serialize()
  89810. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  89811. __decorate([
  89812. BABYLON.serialize()
  89813. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  89814. __decorate([
  89815. BABYLON.serialize()
  89816. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  89817. __decorate([
  89818. BABYLON.serializeAsColor4()
  89819. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  89820. __decorate([
  89821. BABYLON.serialize()
  89822. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  89823. __decorate([
  89824. BABYLON.serialize()
  89825. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  89826. __decorate([
  89827. BABYLON.serialize()
  89828. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  89829. __decorate([
  89830. BABYLON.serialize()
  89831. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  89832. __decorate([
  89833. BABYLON.serialize()
  89834. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  89835. return ImageProcessingConfiguration;
  89836. }());
  89837. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  89838. })(BABYLON || (BABYLON = {}));
  89839. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  89840. var BABYLON;
  89841. (function (BABYLON) {
  89842. /**
  89843. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  89844. * It can help converting any input color in a desired output one. This can then be used to create effects
  89845. * from sepia, black and white to sixties or futuristic rendering...
  89846. *
  89847. * The only supported format is currently 3dl.
  89848. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table
  89849. */
  89850. var ColorGradingTexture = /** @class */ (function (_super) {
  89851. __extends(ColorGradingTexture, _super);
  89852. /**
  89853. * Instantiates a ColorGradingTexture from the following parameters.
  89854. *
  89855. * @param url The location of the color gradind data (currently only supporting 3dl)
  89856. * @param scene The scene the texture will be used in
  89857. */
  89858. function ColorGradingTexture(url, scene) {
  89859. var _this = _super.call(this, scene) || this;
  89860. if (!url) {
  89861. return _this;
  89862. }
  89863. _this._engine = scene.getEngine();
  89864. _this._textureMatrix = BABYLON.Matrix.Identity();
  89865. _this.name = url;
  89866. _this.url = url;
  89867. _this.hasAlpha = false;
  89868. _this.isCube = false;
  89869. _this.is3D = _this._engine.webGLVersion > 1;
  89870. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  89871. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  89872. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  89873. _this.anisotropicFilteringLevel = 1;
  89874. _this._texture = _this._getFromCache(url, true);
  89875. if (!_this._texture) {
  89876. if (!scene.useDelayedTextureLoading) {
  89877. _this.loadTexture();
  89878. }
  89879. else {
  89880. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  89881. }
  89882. }
  89883. return _this;
  89884. }
  89885. /**
  89886. * Returns the texture matrix used in most of the material.
  89887. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  89888. */
  89889. ColorGradingTexture.prototype.getTextureMatrix = function () {
  89890. return this._textureMatrix;
  89891. };
  89892. /**
  89893. * Occurs when the file being loaded is a .3dl LUT file.
  89894. */
  89895. ColorGradingTexture.prototype.load3dlTexture = function () {
  89896. var engine = this._engine;
  89897. var texture;
  89898. if (engine.webGLVersion === 1) {
  89899. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  89900. }
  89901. else {
  89902. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  89903. }
  89904. this._texture = texture;
  89905. var callback = function (text) {
  89906. if (typeof text !== "string") {
  89907. return;
  89908. }
  89909. var data = null;
  89910. var tempData = null;
  89911. var line;
  89912. var lines = text.split('\n');
  89913. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  89914. var maxColor = 0;
  89915. for (var i = 0; i < lines.length; i++) {
  89916. line = lines[i];
  89917. if (!ColorGradingTexture._noneEmptyLineRegex.test(line)) {
  89918. continue;
  89919. }
  89920. if (line.indexOf('#') === 0) {
  89921. continue;
  89922. }
  89923. var words = line.split(" ");
  89924. if (size === 0) {
  89925. // Number of space + one
  89926. size = words.length;
  89927. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  89928. tempData = new Float32Array(size * size * size * 4);
  89929. continue;
  89930. }
  89931. if (size != 0) {
  89932. var r = Math.max(parseInt(words[0]), 0);
  89933. var g = Math.max(parseInt(words[1]), 0);
  89934. var b = Math.max(parseInt(words[2]), 0);
  89935. maxColor = Math.max(r, maxColor);
  89936. maxColor = Math.max(g, maxColor);
  89937. maxColor = Math.max(b, maxColor);
  89938. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  89939. if (tempData) {
  89940. tempData[pixelStorageIndex + 0] = r;
  89941. tempData[pixelStorageIndex + 1] = g;
  89942. tempData[pixelStorageIndex + 2] = b;
  89943. }
  89944. // Keep for reference in case of back compat problems.
  89945. // pixelIndexSlice++;
  89946. // if (pixelIndexSlice % size == 0) {
  89947. // pixelIndexH++;
  89948. // pixelIndexSlice = 0;
  89949. // if (pixelIndexH % size == 0) {
  89950. // pixelIndexW++;
  89951. // pixelIndexH = 0;
  89952. // }
  89953. // }
  89954. pixelIndexH++;
  89955. if (pixelIndexH % size == 0) {
  89956. pixelIndexSlice++;
  89957. pixelIndexH = 0;
  89958. if (pixelIndexSlice % size == 0) {
  89959. pixelIndexW++;
  89960. pixelIndexSlice = 0;
  89961. }
  89962. }
  89963. }
  89964. }
  89965. if (tempData && data) {
  89966. for (var i = 0; i < tempData.length; i++) {
  89967. if (i > 0 && (i + 1) % 4 === 0) {
  89968. data[i] = 255;
  89969. }
  89970. else {
  89971. var value = tempData[i];
  89972. data[i] = (value / maxColor * 255);
  89973. }
  89974. }
  89975. }
  89976. if (texture.is3D) {
  89977. texture.updateSize(size, size, size);
  89978. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  89979. }
  89980. else {
  89981. texture.updateSize(size * size, size);
  89982. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  89983. }
  89984. };
  89985. var scene = this.getScene();
  89986. if (scene) {
  89987. scene._loadFile(this.url, callback);
  89988. }
  89989. else {
  89990. this._engine._loadFile(this.url, callback);
  89991. }
  89992. return this._texture;
  89993. };
  89994. /**
  89995. * Starts the loading process of the texture.
  89996. */
  89997. ColorGradingTexture.prototype.loadTexture = function () {
  89998. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  89999. this.load3dlTexture();
  90000. }
  90001. };
  90002. /**
  90003. * Clones the color gradind texture.
  90004. */
  90005. ColorGradingTexture.prototype.clone = function () {
  90006. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  90007. // Base texture
  90008. newTexture.level = this.level;
  90009. return newTexture;
  90010. };
  90011. /**
  90012. * Called during delayed load for textures.
  90013. */
  90014. ColorGradingTexture.prototype.delayLoad = function () {
  90015. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  90016. return;
  90017. }
  90018. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  90019. this._texture = this._getFromCache(this.url, true);
  90020. if (!this._texture) {
  90021. this.loadTexture();
  90022. }
  90023. };
  90024. /**
  90025. * Parses a color grading texture serialized by Babylon.
  90026. * @param parsedTexture The texture information being parsedTexture
  90027. * @param scene The scene to load the texture in
  90028. * @param rootUrl The root url of the data assets to load
  90029. * @return A color gradind texture
  90030. */
  90031. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  90032. var texture = null;
  90033. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  90034. texture = new ColorGradingTexture(parsedTexture.name, scene);
  90035. texture.name = parsedTexture.name;
  90036. texture.level = parsedTexture.level;
  90037. }
  90038. return texture;
  90039. };
  90040. /**
  90041. * Serializes the LUT texture to json format.
  90042. */
  90043. ColorGradingTexture.prototype.serialize = function () {
  90044. if (!this.name) {
  90045. return null;
  90046. }
  90047. var serializationObject = {};
  90048. serializationObject.name = this.name;
  90049. serializationObject.level = this.level;
  90050. serializationObject.customType = "BABYLON.ColorGradingTexture";
  90051. return serializationObject;
  90052. };
  90053. /**
  90054. * Empty line regex stored for GC.
  90055. */
  90056. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  90057. return ColorGradingTexture;
  90058. }(BABYLON.BaseTexture));
  90059. BABYLON.ColorGradingTexture = ColorGradingTexture;
  90060. })(BABYLON || (BABYLON = {}));
  90061. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  90062. var BABYLON;
  90063. (function (BABYLON) {
  90064. /**
  90065. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  90066. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  90067. * 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;
  90068. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  90069. */
  90070. var ColorCurves = /** @class */ (function () {
  90071. function ColorCurves() {
  90072. this._dirty = true;
  90073. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  90074. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  90075. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  90076. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  90077. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  90078. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  90079. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  90080. this._globalHue = 30;
  90081. this._globalDensity = 0;
  90082. this._globalSaturation = 0;
  90083. this._globalExposure = 0;
  90084. this._highlightsHue = 30;
  90085. this._highlightsDensity = 0;
  90086. this._highlightsSaturation = 0;
  90087. this._highlightsExposure = 0;
  90088. this._midtonesHue = 30;
  90089. this._midtonesDensity = 0;
  90090. this._midtonesSaturation = 0;
  90091. this._midtonesExposure = 0;
  90092. this._shadowsHue = 30;
  90093. this._shadowsDensity = 0;
  90094. this._shadowsSaturation = 0;
  90095. this._shadowsExposure = 0;
  90096. }
  90097. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  90098. /**
  90099. * Gets the global Hue value.
  90100. * 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).
  90101. */
  90102. get: function () {
  90103. return this._globalHue;
  90104. },
  90105. /**
  90106. * Sets the global Hue value.
  90107. * 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).
  90108. */
  90109. set: function (value) {
  90110. this._globalHue = value;
  90111. this._dirty = true;
  90112. },
  90113. enumerable: true,
  90114. configurable: true
  90115. });
  90116. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  90117. /**
  90118. * Gets the global Density value.
  90119. * 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.
  90120. * Values less than zero provide a filter of opposite hue.
  90121. */
  90122. get: function () {
  90123. return this._globalDensity;
  90124. },
  90125. /**
  90126. * Sets the global Density value.
  90127. * 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.
  90128. * Values less than zero provide a filter of opposite hue.
  90129. */
  90130. set: function (value) {
  90131. this._globalDensity = value;
  90132. this._dirty = true;
  90133. },
  90134. enumerable: true,
  90135. configurable: true
  90136. });
  90137. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  90138. /**
  90139. * Gets the global Saturation value.
  90140. * 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.
  90141. */
  90142. get: function () {
  90143. return this._globalSaturation;
  90144. },
  90145. /**
  90146. * Sets the global Saturation value.
  90147. * 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.
  90148. */
  90149. set: function (value) {
  90150. this._globalSaturation = value;
  90151. this._dirty = true;
  90152. },
  90153. enumerable: true,
  90154. configurable: true
  90155. });
  90156. Object.defineProperty(ColorCurves.prototype, "globalExposure", {
  90157. /**
  90158. * Gets the global Exposure value.
  90159. * 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.
  90160. */
  90161. get: function () {
  90162. return this._globalExposure;
  90163. },
  90164. /**
  90165. * Sets the global Exposure value.
  90166. * 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.
  90167. */
  90168. set: function (value) {
  90169. this._globalExposure = value;
  90170. this._dirty = true;
  90171. },
  90172. enumerable: true,
  90173. configurable: true
  90174. });
  90175. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  90176. /**
  90177. * Gets the highlights Hue value.
  90178. * 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).
  90179. */
  90180. get: function () {
  90181. return this._highlightsHue;
  90182. },
  90183. /**
  90184. * Sets the highlights Hue value.
  90185. * 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).
  90186. */
  90187. set: function (value) {
  90188. this._highlightsHue = value;
  90189. this._dirty = true;
  90190. },
  90191. enumerable: true,
  90192. configurable: true
  90193. });
  90194. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  90195. /**
  90196. * Gets the highlights Density value.
  90197. * 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.
  90198. * Values less than zero provide a filter of opposite hue.
  90199. */
  90200. get: function () {
  90201. return this._highlightsDensity;
  90202. },
  90203. /**
  90204. * Sets the highlights Density value.
  90205. * 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.
  90206. * Values less than zero provide a filter of opposite hue.
  90207. */
  90208. set: function (value) {
  90209. this._highlightsDensity = value;
  90210. this._dirty = true;
  90211. },
  90212. enumerable: true,
  90213. configurable: true
  90214. });
  90215. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  90216. /**
  90217. * Gets the highlights Saturation value.
  90218. * 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.
  90219. */
  90220. get: function () {
  90221. return this._highlightsSaturation;
  90222. },
  90223. /**
  90224. * Sets the highlights Saturation value.
  90225. * 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.
  90226. */
  90227. set: function (value) {
  90228. this._highlightsSaturation = value;
  90229. this._dirty = true;
  90230. },
  90231. enumerable: true,
  90232. configurable: true
  90233. });
  90234. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  90235. /**
  90236. * Gets the highlights Exposure value.
  90237. * 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.
  90238. */
  90239. get: function () {
  90240. return this._highlightsExposure;
  90241. },
  90242. /**
  90243. * Sets the highlights Exposure value.
  90244. * 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.
  90245. */
  90246. set: function (value) {
  90247. this._highlightsExposure = value;
  90248. this._dirty = true;
  90249. },
  90250. enumerable: true,
  90251. configurable: true
  90252. });
  90253. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  90254. /**
  90255. * Gets the midtones Hue value.
  90256. * 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).
  90257. */
  90258. get: function () {
  90259. return this._midtonesHue;
  90260. },
  90261. /**
  90262. * Sets the midtones Hue value.
  90263. * 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).
  90264. */
  90265. set: function (value) {
  90266. this._midtonesHue = value;
  90267. this._dirty = true;
  90268. },
  90269. enumerable: true,
  90270. configurable: true
  90271. });
  90272. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  90273. /**
  90274. * Gets the midtones Density value.
  90275. * 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.
  90276. * Values less than zero provide a filter of opposite hue.
  90277. */
  90278. get: function () {
  90279. return this._midtonesDensity;
  90280. },
  90281. /**
  90282. * Sets the midtones Density value.
  90283. * 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.
  90284. * Values less than zero provide a filter of opposite hue.
  90285. */
  90286. set: function (value) {
  90287. this._midtonesDensity = value;
  90288. this._dirty = true;
  90289. },
  90290. enumerable: true,
  90291. configurable: true
  90292. });
  90293. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  90294. /**
  90295. * Gets the midtones Saturation value.
  90296. * 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.
  90297. */
  90298. get: function () {
  90299. return this._midtonesSaturation;
  90300. },
  90301. /**
  90302. * Sets the midtones Saturation value.
  90303. * 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.
  90304. */
  90305. set: function (value) {
  90306. this._midtonesSaturation = value;
  90307. this._dirty = true;
  90308. },
  90309. enumerable: true,
  90310. configurable: true
  90311. });
  90312. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  90313. /**
  90314. * Gets the midtones Exposure value.
  90315. * 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.
  90316. */
  90317. get: function () {
  90318. return this._midtonesExposure;
  90319. },
  90320. /**
  90321. * Sets the midtones Exposure value.
  90322. * 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.
  90323. */
  90324. set: function (value) {
  90325. this._midtonesExposure = value;
  90326. this._dirty = true;
  90327. },
  90328. enumerable: true,
  90329. configurable: true
  90330. });
  90331. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  90332. /**
  90333. * Gets the shadows Hue value.
  90334. * 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).
  90335. */
  90336. get: function () {
  90337. return this._shadowsHue;
  90338. },
  90339. /**
  90340. * Sets the shadows Hue value.
  90341. * 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).
  90342. */
  90343. set: function (value) {
  90344. this._shadowsHue = value;
  90345. this._dirty = true;
  90346. },
  90347. enumerable: true,
  90348. configurable: true
  90349. });
  90350. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  90351. /**
  90352. * Gets the shadows Density value.
  90353. * 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.
  90354. * Values less than zero provide a filter of opposite hue.
  90355. */
  90356. get: function () {
  90357. return this._shadowsDensity;
  90358. },
  90359. /**
  90360. * Sets the shadows Density value.
  90361. * 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.
  90362. * Values less than zero provide a filter of opposite hue.
  90363. */
  90364. set: function (value) {
  90365. this._shadowsDensity = value;
  90366. this._dirty = true;
  90367. },
  90368. enumerable: true,
  90369. configurable: true
  90370. });
  90371. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  90372. /**
  90373. * Gets the shadows Saturation value.
  90374. * 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.
  90375. */
  90376. get: function () {
  90377. return this._shadowsSaturation;
  90378. },
  90379. /**
  90380. * Sets the shadows Saturation value.
  90381. * 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.
  90382. */
  90383. set: function (value) {
  90384. this._shadowsSaturation = value;
  90385. this._dirty = true;
  90386. },
  90387. enumerable: true,
  90388. configurable: true
  90389. });
  90390. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  90391. /**
  90392. * Gets the shadows Exposure value.
  90393. * 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.
  90394. */
  90395. get: function () {
  90396. return this._shadowsExposure;
  90397. },
  90398. /**
  90399. * Sets the shadows Exposure value.
  90400. * 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.
  90401. */
  90402. set: function (value) {
  90403. this._shadowsExposure = value;
  90404. this._dirty = true;
  90405. },
  90406. enumerable: true,
  90407. configurable: true
  90408. });
  90409. /**
  90410. * Returns the class name
  90411. * @returns The class name
  90412. */
  90413. ColorCurves.prototype.getClassName = function () {
  90414. return "ColorCurves";
  90415. };
  90416. /**
  90417. * Binds the color curves to the shader.
  90418. * @param colorCurves The color curve to bind
  90419. * @param effect The effect to bind to
  90420. * @param positiveUniform The positive uniform shader parameter
  90421. * @param neutralUniform The neutral uniform shader parameter
  90422. * @param negativeUniform The negative uniform shader parameter
  90423. */
  90424. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  90425. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  90426. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  90427. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  90428. if (colorCurves._dirty) {
  90429. colorCurves._dirty = false;
  90430. // Fill in global info.
  90431. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  90432. // Compute highlights info.
  90433. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  90434. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  90435. // Compute midtones info.
  90436. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  90437. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  90438. // Compute shadows info.
  90439. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  90440. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  90441. // Compute deltas (neutral is midtones).
  90442. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  90443. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  90444. }
  90445. if (effect) {
  90446. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  90447. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  90448. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  90449. }
  90450. };
  90451. /**
  90452. * Prepare the list of uniforms associated with the ColorCurves effects.
  90453. * @param uniformsList The list of uniforms used in the effect
  90454. */
  90455. ColorCurves.PrepareUniforms = function (uniformsList) {
  90456. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  90457. };
  90458. /**
  90459. * Returns color grading data based on a hue, density, saturation and exposure value.
  90460. * @param filterHue The hue of the color filter.
  90461. * @param filterDensity The density of the color filter.
  90462. * @param saturation The saturation.
  90463. * @param exposure The exposure.
  90464. * @param result The result data container.
  90465. */
  90466. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  90467. if (hue == null) {
  90468. return;
  90469. }
  90470. hue = ColorCurves.clamp(hue, 0, 360);
  90471. density = ColorCurves.clamp(density, -100, 100);
  90472. saturation = ColorCurves.clamp(saturation, -100, 100);
  90473. exposure = ColorCurves.clamp(exposure, -100, 100);
  90474. // Remap the slider/config filter density with non-linear mapping and also scale by half
  90475. // so that the maximum filter density is only 50% control. This provides fine control
  90476. // for small values and reasonable range.
  90477. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  90478. density *= 0.5;
  90479. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  90480. if (density < 0) {
  90481. density *= -1;
  90482. hue = (hue + 180) % 360;
  90483. }
  90484. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  90485. result.scaleToRef(2, result);
  90486. result.a = 1 + 0.01 * saturation;
  90487. };
  90488. /**
  90489. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  90490. * @param value The input slider value in range [-100,100].
  90491. * @returns Adjusted value.
  90492. */
  90493. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  90494. value /= 100;
  90495. var x = Math.abs(value);
  90496. x = Math.pow(x, 2);
  90497. if (value < 0) {
  90498. x *= -1;
  90499. }
  90500. x *= 100;
  90501. return x;
  90502. };
  90503. /**
  90504. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  90505. * @param hue The hue (H) input.
  90506. * @param saturation The saturation (S) input.
  90507. * @param brightness The brightness (B) input.
  90508. * @result An RGBA color represented as Vector4.
  90509. */
  90510. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  90511. var h = ColorCurves.clamp(hue, 0, 360);
  90512. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  90513. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  90514. if (s === 0) {
  90515. result.r = v;
  90516. result.g = v;
  90517. result.b = v;
  90518. }
  90519. else {
  90520. // sector 0 to 5
  90521. h /= 60;
  90522. var i = Math.floor(h);
  90523. // fractional part of h
  90524. var f = h - i;
  90525. var p = v * (1 - s);
  90526. var q = v * (1 - s * f);
  90527. var t = v * (1 - s * (1 - f));
  90528. switch (i) {
  90529. case 0:
  90530. result.r = v;
  90531. result.g = t;
  90532. result.b = p;
  90533. break;
  90534. case 1:
  90535. result.r = q;
  90536. result.g = v;
  90537. result.b = p;
  90538. break;
  90539. case 2:
  90540. result.r = p;
  90541. result.g = v;
  90542. result.b = t;
  90543. break;
  90544. case 3:
  90545. result.r = p;
  90546. result.g = q;
  90547. result.b = v;
  90548. break;
  90549. case 4:
  90550. result.r = t;
  90551. result.g = p;
  90552. result.b = v;
  90553. break;
  90554. default: // case 5:
  90555. result.r = v;
  90556. result.g = p;
  90557. result.b = q;
  90558. break;
  90559. }
  90560. }
  90561. result.a = 1;
  90562. };
  90563. /**
  90564. * Returns a value clamped between min and max
  90565. * @param value The value to clamp
  90566. * @param min The minimum of value
  90567. * @param max The maximum of value
  90568. * @returns The clamped value.
  90569. */
  90570. ColorCurves.clamp = function (value, min, max) {
  90571. return Math.min(Math.max(value, min), max);
  90572. };
  90573. /**
  90574. * Clones the current color curve instance.
  90575. * @return The cloned curves
  90576. */
  90577. ColorCurves.prototype.clone = function () {
  90578. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  90579. };
  90580. /**
  90581. * Serializes the current color curve instance to a json representation.
  90582. * @return a JSON representation
  90583. */
  90584. ColorCurves.prototype.serialize = function () {
  90585. return BABYLON.SerializationHelper.Serialize(this);
  90586. };
  90587. /**
  90588. * Parses the color curve from a json representation.
  90589. * @param source the JSON source to parse
  90590. * @return The parsed curves
  90591. */
  90592. ColorCurves.Parse = function (source) {
  90593. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  90594. };
  90595. __decorate([
  90596. BABYLON.serialize()
  90597. ], ColorCurves.prototype, "_globalHue", void 0);
  90598. __decorate([
  90599. BABYLON.serialize()
  90600. ], ColorCurves.prototype, "_globalDensity", void 0);
  90601. __decorate([
  90602. BABYLON.serialize()
  90603. ], ColorCurves.prototype, "_globalSaturation", void 0);
  90604. __decorate([
  90605. BABYLON.serialize()
  90606. ], ColorCurves.prototype, "_globalExposure", void 0);
  90607. __decorate([
  90608. BABYLON.serialize()
  90609. ], ColorCurves.prototype, "_highlightsHue", void 0);
  90610. __decorate([
  90611. BABYLON.serialize()
  90612. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  90613. __decorate([
  90614. BABYLON.serialize()
  90615. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  90616. __decorate([
  90617. BABYLON.serialize()
  90618. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  90619. __decorate([
  90620. BABYLON.serialize()
  90621. ], ColorCurves.prototype, "_midtonesHue", void 0);
  90622. __decorate([
  90623. BABYLON.serialize()
  90624. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  90625. __decorate([
  90626. BABYLON.serialize()
  90627. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  90628. __decorate([
  90629. BABYLON.serialize()
  90630. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  90631. return ColorCurves;
  90632. }());
  90633. BABYLON.ColorCurves = ColorCurves;
  90634. })(BABYLON || (BABYLON = {}));
  90635. //# sourceMappingURL=babylon.colorCurves.js.map
  90636. var BABYLON;
  90637. (function (BABYLON) {
  90638. /**
  90639. * Post process which applies a refractin texture
  90640. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses#refraction
  90641. */
  90642. var RefractionPostProcess = /** @class */ (function (_super) {
  90643. __extends(RefractionPostProcess, _super);
  90644. /**
  90645. * Initializes the RefractionPostProcess
  90646. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses#refraction
  90647. * @param name The name of the effect.
  90648. * @param refractionTextureUrl Url of the refraction texture to use
  90649. * @param color the base color of the refraction (used to taint the rendering)
  90650. * @param depth simulated refraction depth
  90651. * @param colorLevel the coefficient of the base color (0 to remove base color tainting)
  90652. * @param camera The camera to apply the render pass to.
  90653. * @param options The required width/height ratio to downsize to before computing the render pass.
  90654. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  90655. * @param engine The engine which the post process will be applied. (default: current engine)
  90656. * @param reusable If the post process can be reused on the same frame. (default: false)
  90657. */
  90658. function RefractionPostProcess(name, refractionTextureUrl,
  90659. /** the base color of the refraction (used to taint the rendering) */
  90660. color,
  90661. /** simulated refraction depth */
  90662. depth,
  90663. /** the coefficient of the base color (0 to remove base color tainting) */
  90664. colorLevel, options, camera, samplingMode, engine, reusable) {
  90665. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  90666. _this.color = color;
  90667. _this.depth = depth;
  90668. _this.colorLevel = colorLevel;
  90669. _this._ownRefractionTexture = true;
  90670. _this.onActivateObservable.add(function (cam) {
  90671. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  90672. });
  90673. _this.onApplyObservable.add(function (effect) {
  90674. effect.setColor3("baseColor", _this.color);
  90675. effect.setFloat("depth", _this.depth);
  90676. effect.setFloat("colorLevel", _this.colorLevel);
  90677. effect.setTexture("refractionSampler", _this._refTexture);
  90678. });
  90679. return _this;
  90680. }
  90681. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  90682. /**
  90683. * Gets or sets the refraction texture
  90684. * Please note that you are responsible for disposing the texture if you set it manually
  90685. */
  90686. get: function () {
  90687. return this._refTexture;
  90688. },
  90689. set: function (value) {
  90690. if (this._refTexture && this._ownRefractionTexture) {
  90691. this._refTexture.dispose();
  90692. }
  90693. this._refTexture = value;
  90694. this._ownRefractionTexture = false;
  90695. },
  90696. enumerable: true,
  90697. configurable: true
  90698. });
  90699. // Methods
  90700. /**
  90701. * Disposes of the post process
  90702. * @param camera Camera to dispose post process on
  90703. */
  90704. RefractionPostProcess.prototype.dispose = function (camera) {
  90705. if (this._refTexture && this._ownRefractionTexture) {
  90706. this._refTexture.dispose();
  90707. this._refTexture = null;
  90708. }
  90709. _super.prototype.dispose.call(this, camera);
  90710. };
  90711. return RefractionPostProcess;
  90712. }(BABYLON.PostProcess));
  90713. BABYLON.RefractionPostProcess = RefractionPostProcess;
  90714. })(BABYLON || (BABYLON = {}));
  90715. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  90716. var BABYLON;
  90717. (function (BABYLON) {
  90718. /**
  90719. * Post process used to render in black and white
  90720. */
  90721. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  90722. __extends(BlackAndWhitePostProcess, _super);
  90723. /**
  90724. * Creates a black and white post process
  90725. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses#black-and-white
  90726. * @param name The name of the effect.
  90727. * @param options The required width/height ratio to downsize to before computing the render pass.
  90728. * @param camera The camera to apply the render pass to.
  90729. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  90730. * @param engine The engine which the post process will be applied. (default: current engine)
  90731. * @param reusable If the post process can be reused on the same frame. (default: false)
  90732. */
  90733. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  90734. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  90735. /**
  90736. * Linear about to convert he result to black and white (default: 1)
  90737. */
  90738. _this.degree = 1;
  90739. _this.onApplyObservable.add(function (effect) {
  90740. effect.setFloat("degree", _this.degree);
  90741. });
  90742. return _this;
  90743. }
  90744. return BlackAndWhitePostProcess;
  90745. }(BABYLON.PostProcess));
  90746. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  90747. })(BABYLON || (BABYLON = {}));
  90748. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  90749. var BABYLON;
  90750. (function (BABYLON) {
  90751. /**
  90752. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  90753. * input texture to perform effects such as edge detection or sharpening
  90754. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  90755. */
  90756. var ConvolutionPostProcess = /** @class */ (function (_super) {
  90757. __extends(ConvolutionPostProcess, _super);
  90758. /**
  90759. * Creates a new instance ConvolutionPostProcess
  90760. * @param name The name of the effect.
  90761. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  90762. * @param options The required width/height ratio to downsize to before computing the render pass.
  90763. * @param camera The camera to apply the render pass to.
  90764. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  90765. * @param engine The engine which the post process will be applied. (default: current engine)
  90766. * @param reusable If the post process can be reused on the same frame. (default: false)
  90767. * @param textureType Type of textures used when performing the post process. (default: 0)
  90768. */
  90769. function ConvolutionPostProcess(name,
  90770. /** Array of 9 values corrisponding to the 3x3 kernel to be applied */
  90771. kernel, options, camera, samplingMode, engine, reusable, textureType) {
  90772. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  90773. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  90774. _this.kernel = kernel;
  90775. _this.onApply = function (effect) {
  90776. effect.setFloat2("screenSize", _this.width, _this.height);
  90777. effect.setArray("kernel", _this.kernel);
  90778. };
  90779. return _this;
  90780. }
  90781. // Statics
  90782. /**
  90783. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  90784. */
  90785. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  90786. /**
  90787. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  90788. */
  90789. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  90790. /**
  90791. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  90792. */
  90793. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  90794. /**
  90795. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  90796. */
  90797. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  90798. /**
  90799. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  90800. */
  90801. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  90802. /**
  90803. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  90804. */
  90805. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  90806. return ConvolutionPostProcess;
  90807. }(BABYLON.PostProcess));
  90808. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  90809. })(BABYLON || (BABYLON = {}));
  90810. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  90811. var BABYLON;
  90812. (function (BABYLON) {
  90813. /**
  90814. * Applies a kernel filter to the image
  90815. */
  90816. var FilterPostProcess = /** @class */ (function (_super) {
  90817. __extends(FilterPostProcess, _super);
  90818. /**
  90819. *
  90820. * @param name The name of the effect.
  90821. * @param kernelMatrix The matrix to be applied to the image
  90822. * @param options The required width/height ratio to downsize to before computing the render pass.
  90823. * @param camera The camera to apply the render pass to.
  90824. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  90825. * @param engine The engine which the post process will be applied. (default: current engine)
  90826. * @param reusable If the post process can be reused on the same frame. (default: false)
  90827. */
  90828. function FilterPostProcess(name,
  90829. /** The matrix to be applied to the image */
  90830. kernelMatrix, options, camera, samplingMode, engine, reusable) {
  90831. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  90832. _this.kernelMatrix = kernelMatrix;
  90833. _this.onApply = function (effect) {
  90834. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  90835. };
  90836. return _this;
  90837. }
  90838. return FilterPostProcess;
  90839. }(BABYLON.PostProcess));
  90840. BABYLON.FilterPostProcess = FilterPostProcess;
  90841. })(BABYLON || (BABYLON = {}));
  90842. //# sourceMappingURL=babylon.filterPostProcess.js.map
  90843. var BABYLON;
  90844. (function (BABYLON) {
  90845. /**
  90846. * Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  90847. */
  90848. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  90849. __extends(VolumetricLightScatteringPostProcess, _super);
  90850. /**
  90851. * @constructor
  90852. * @param name The post-process name
  90853. * @param ratio The size of the post-process and/or internal pass (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5)
  90854. * @param camera The camera that the post-process will be attached to
  90855. * @param mesh The mesh used to create the light scattering
  90856. * @param samples The post-process quality, default 100
  90857. * @param samplingModeThe post-process filtering mode
  90858. * @param engine The babylon engine
  90859. * @param reusable If the post-process is reusable
  90860. * @param scene The constructor needs a scene reference to initialize internal components. If "camera" is null a "scene" must be provided
  90861. */
  90862. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  90863. if (samples === void 0) { samples = 100; }
  90864. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  90865. 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;
  90866. _this._screenCoordinates = BABYLON.Vector2.Zero();
  90867. /**
  90868. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  90869. */
  90870. _this.customMeshPosition = BABYLON.Vector3.Zero();
  90871. /**
  90872. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  90873. */
  90874. _this.useCustomMeshPosition = false;
  90875. /**
  90876. * If the post-process should inverse the light scattering direction
  90877. */
  90878. _this.invert = true;
  90879. /**
  90880. * Array containing the excluded meshes not rendered in the internal pass
  90881. */
  90882. _this.excludedMeshes = new Array();
  90883. /**
  90884. * Controls the overall intensity of the post-process
  90885. */
  90886. _this.exposure = 0.3;
  90887. /**
  90888. * Dissipates each sample's contribution in range [0, 1]
  90889. */
  90890. _this.decay = 0.96815;
  90891. /**
  90892. * Controls the overall intensity of each sample
  90893. */
  90894. _this.weight = 0.58767;
  90895. /**
  90896. * Controls the density of each sample
  90897. */
  90898. _this.density = 0.926;
  90899. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  90900. engine = scene.getEngine();
  90901. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  90902. // Configure mesh
  90903. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  90904. // Configure
  90905. _this._createPass(scene, ratio.passRatio || ratio);
  90906. _this.onActivate = function (camera) {
  90907. if (!_this.isSupported) {
  90908. _this.dispose(camera);
  90909. }
  90910. _this.onActivate = null;
  90911. };
  90912. _this.onApplyObservable.add(function (effect) {
  90913. _this._updateMeshScreenCoordinates(scene);
  90914. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  90915. effect.setFloat("exposure", _this.exposure);
  90916. effect.setFloat("decay", _this.decay);
  90917. effect.setFloat("weight", _this.weight);
  90918. effect.setFloat("density", _this.density);
  90919. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  90920. });
  90921. return _this;
  90922. }
  90923. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  90924. /**
  90925. * @hidden
  90926. * VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead
  90927. */
  90928. get: function () {
  90929. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  90930. return false;
  90931. },
  90932. set: function (useDiffuseColor) {
  90933. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  90934. },
  90935. enumerable: true,
  90936. configurable: true
  90937. });
  90938. /**
  90939. * Returns the string "VolumetricLightScatteringPostProcess"
  90940. * @returns "VolumetricLightScatteringPostProcess"
  90941. */
  90942. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  90943. return "VolumetricLightScatteringPostProcess";
  90944. };
  90945. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  90946. var mesh = subMesh.getMesh();
  90947. // Render this.mesh as default
  90948. if (mesh === this.mesh && mesh.material) {
  90949. return mesh.material.isReady(mesh);
  90950. }
  90951. var defines = [];
  90952. var attribs = [BABYLON.VertexBuffer.PositionKind];
  90953. var material = subMesh.getMaterial();
  90954. // Alpha test
  90955. if (material) {
  90956. if (material.needAlphaTesting()) {
  90957. defines.push("#define ALPHATEST");
  90958. }
  90959. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  90960. attribs.push(BABYLON.VertexBuffer.UVKind);
  90961. defines.push("#define UV1");
  90962. }
  90963. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  90964. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  90965. defines.push("#define UV2");
  90966. }
  90967. }
  90968. // Bones
  90969. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  90970. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  90971. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  90972. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  90973. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  90974. }
  90975. else {
  90976. defines.push("#define NUM_BONE_INFLUENCERS 0");
  90977. }
  90978. // Instances
  90979. if (useInstances) {
  90980. defines.push("#define INSTANCES");
  90981. attribs.push("world0");
  90982. attribs.push("world1");
  90983. attribs.push("world2");
  90984. attribs.push("world3");
  90985. }
  90986. // Get correct effect
  90987. var join = defines.join("\n");
  90988. if (this._cachedDefines !== join) {
  90989. this._cachedDefines = join;
  90990. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  90991. }
  90992. return this._volumetricLightScatteringPass.isReady();
  90993. };
  90994. /**
  90995. * Sets the new light position for light scattering effect
  90996. * @param position The new custom light position
  90997. */
  90998. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  90999. this.customMeshPosition = position;
  91000. };
  91001. /**
  91002. * Returns the light position for light scattering effect
  91003. * @return Vector3 The custom light position
  91004. */
  91005. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  91006. return this.customMeshPosition;
  91007. };
  91008. /**
  91009. * Disposes the internal assets and detaches the post-process from the camera
  91010. */
  91011. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  91012. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  91013. if (rttIndex !== -1) {
  91014. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  91015. }
  91016. this._volumetricLightScatteringRTT.dispose();
  91017. _super.prototype.dispose.call(this, camera);
  91018. };
  91019. /**
  91020. * Returns the render target texture used by the post-process
  91021. * @return the render target texture used by the post-process
  91022. */
  91023. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  91024. return this._volumetricLightScatteringRTT;
  91025. };
  91026. // Private methods
  91027. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  91028. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  91029. return true;
  91030. }
  91031. return false;
  91032. };
  91033. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  91034. var _this = this;
  91035. var engine = scene.getEngine();
  91036. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  91037. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91038. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91039. this._volumetricLightScatteringRTT.renderList = null;
  91040. this._volumetricLightScatteringRTT.renderParticles = false;
  91041. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  91042. var camera = this.getCamera();
  91043. if (camera) {
  91044. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  91045. }
  91046. else {
  91047. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  91048. }
  91049. // Custom render function for submeshes
  91050. var renderSubMesh = function (subMesh) {
  91051. var mesh = subMesh.getRenderingMesh();
  91052. if (_this._meshExcluded(mesh)) {
  91053. return;
  91054. }
  91055. var material = subMesh.getMaterial();
  91056. if (!material) {
  91057. return;
  91058. }
  91059. var scene = mesh.getScene();
  91060. var engine = scene.getEngine();
  91061. // Culling
  91062. engine.setState(material.backFaceCulling);
  91063. // Managing instances
  91064. var batch = mesh._getInstancesRenderList(subMesh._id);
  91065. if (batch.mustReturn) {
  91066. return;
  91067. }
  91068. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  91069. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  91070. var effect = _this._volumetricLightScatteringPass;
  91071. if (mesh === _this.mesh) {
  91072. if (subMesh.effect) {
  91073. effect = subMesh.effect;
  91074. }
  91075. else {
  91076. effect = material.getEffect();
  91077. }
  91078. }
  91079. engine.enableEffect(effect);
  91080. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  91081. if (mesh === _this.mesh) {
  91082. material.bind(mesh.getWorldMatrix(), mesh);
  91083. }
  91084. else {
  91085. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  91086. // Alpha test
  91087. if (material && material.needAlphaTesting()) {
  91088. var alphaTexture = material.getAlphaTestTexture();
  91089. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  91090. if (alphaTexture) {
  91091. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  91092. }
  91093. }
  91094. // Bones
  91095. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  91096. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  91097. }
  91098. }
  91099. // Draw
  91100. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  91101. }
  91102. };
  91103. // Render target texture callbacks
  91104. var savedSceneClearColor;
  91105. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  91106. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  91107. savedSceneClearColor = scene.clearColor;
  91108. scene.clearColor = sceneClearColor;
  91109. });
  91110. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  91111. scene.clearColor = savedSceneClearColor;
  91112. });
  91113. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  91114. var engine = scene.getEngine();
  91115. var index;
  91116. if (depthOnlySubMeshes.length) {
  91117. engine.setColorWrite(false);
  91118. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  91119. renderSubMesh(depthOnlySubMeshes.data[index]);
  91120. }
  91121. engine.setColorWrite(true);
  91122. }
  91123. for (index = 0; index < opaqueSubMeshes.length; index++) {
  91124. renderSubMesh(opaqueSubMeshes.data[index]);
  91125. }
  91126. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  91127. renderSubMesh(alphaTestSubMeshes.data[index]);
  91128. }
  91129. if (transparentSubMeshes.length) {
  91130. // Sort sub meshes
  91131. for (index = 0; index < transparentSubMeshes.length; index++) {
  91132. var submesh = transparentSubMeshes.data[index];
  91133. var boundingInfo = submesh.getBoundingInfo();
  91134. if (boundingInfo && scene.activeCamera) {
  91135. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  91136. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  91137. }
  91138. }
  91139. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  91140. sortedArray.sort(function (a, b) {
  91141. // Alpha index first
  91142. if (a._alphaIndex > b._alphaIndex) {
  91143. return 1;
  91144. }
  91145. if (a._alphaIndex < b._alphaIndex) {
  91146. return -1;
  91147. }
  91148. // Then distance to camera
  91149. if (a._distanceToCamera < b._distanceToCamera) {
  91150. return 1;
  91151. }
  91152. if (a._distanceToCamera > b._distanceToCamera) {
  91153. return -1;
  91154. }
  91155. return 0;
  91156. });
  91157. // Render sub meshes
  91158. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  91159. for (index = 0; index < sortedArray.length; index++) {
  91160. renderSubMesh(sortedArray[index]);
  91161. }
  91162. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  91163. }
  91164. };
  91165. };
  91166. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  91167. var transform = scene.getTransformMatrix();
  91168. var meshPosition;
  91169. if (this.useCustomMeshPosition) {
  91170. meshPosition = this.customMeshPosition;
  91171. }
  91172. else if (this.attachedNode) {
  91173. meshPosition = this.attachedNode.position;
  91174. }
  91175. else {
  91176. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  91177. }
  91178. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  91179. this._screenCoordinates.x = pos.x / this._viewPort.width;
  91180. this._screenCoordinates.y = pos.y / this._viewPort.height;
  91181. if (this.invert) {
  91182. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  91183. }
  91184. };
  91185. // Static methods
  91186. /**
  91187. * Creates a default mesh for the Volumeric Light Scattering post-process
  91188. * @param name The mesh name
  91189. * @param scene The scene where to create the mesh
  91190. * @return the default mesh
  91191. */
  91192. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  91193. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  91194. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  91195. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  91196. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  91197. mesh.material = material;
  91198. return mesh;
  91199. };
  91200. __decorate([
  91201. BABYLON.serializeAsVector3()
  91202. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  91203. __decorate([
  91204. BABYLON.serialize()
  91205. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  91206. __decorate([
  91207. BABYLON.serialize()
  91208. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  91209. __decorate([
  91210. BABYLON.serializeAsMeshReference()
  91211. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  91212. __decorate([
  91213. BABYLON.serialize()
  91214. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  91215. __decorate([
  91216. BABYLON.serialize()
  91217. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  91218. __decorate([
  91219. BABYLON.serialize()
  91220. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  91221. __decorate([
  91222. BABYLON.serialize()
  91223. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  91224. __decorate([
  91225. BABYLON.serialize()
  91226. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  91227. return VolumetricLightScatteringPostProcess;
  91228. }(BABYLON.PostProcess));
  91229. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  91230. })(BABYLON || (BABYLON = {}));
  91231. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  91232. var BABYLON;
  91233. (function (BABYLON) {
  91234. /**
  91235. *
  91236. * This post-process allows the modification of rendered colors by using
  91237. * a 'look-up table' (LUT). This effect is also called Color Grading.
  91238. *
  91239. * The object needs to be provided an url to a texture containing the color
  91240. * look-up table: the texture must be 256 pixels wide and 16 pixels high.
  91241. * Use an image editing software to tweak the LUT to match your needs.
  91242. *
  91243. * For an example of a color LUT, see here:
  91244. * @see http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  91245. * For explanations on color grading, see here:
  91246. * @see http://udn.epicgames.com/Three/ColorGrading.html
  91247. *
  91248. */
  91249. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  91250. __extends(ColorCorrectionPostProcess, _super);
  91251. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  91252. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  91253. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  91254. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  91255. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91256. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91257. _this.onApply = function (effect) {
  91258. effect.setTexture("colorTable", _this._colorTableTexture);
  91259. };
  91260. return _this;
  91261. }
  91262. return ColorCorrectionPostProcess;
  91263. }(BABYLON.PostProcess));
  91264. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  91265. })(BABYLON || (BABYLON = {}));
  91266. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  91267. var BABYLON;
  91268. (function (BABYLON) {
  91269. /** Defines operator used for tonemapping */
  91270. var TonemappingOperator;
  91271. (function (TonemappingOperator) {
  91272. /** Hable */
  91273. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  91274. /** Reinhard */
  91275. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  91276. /** HejiDawson */
  91277. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  91278. /** Photographic */
  91279. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  91280. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  91281. /**
  91282. * Defines a post process to apply tone mapping
  91283. */
  91284. var TonemapPostProcess = /** @class */ (function (_super) {
  91285. __extends(TonemapPostProcess, _super);
  91286. /**
  91287. * Creates a new TonemapPostProcess
  91288. * @param name defines the name of the postprocess
  91289. * @param _operator defines the operator to use
  91290. * @param exposureAdjustment defines the required exposure adjustement
  91291. * @param camera defines the camera to use (can be null)
  91292. * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default)
  91293. * @param engine defines the hosting engine (can be ignore if camera is set)
  91294. * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  91295. */
  91296. function TonemapPostProcess(name, _operator,
  91297. /** Defines the required exposure adjustement */
  91298. exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  91299. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  91300. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  91301. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  91302. _this._operator = _operator;
  91303. _this.exposureAdjustment = exposureAdjustment;
  91304. var defines = "#define ";
  91305. if (_this._operator === TonemappingOperator.Hable) {
  91306. defines += "HABLE_TONEMAPPING";
  91307. }
  91308. else if (_this._operator === TonemappingOperator.Reinhard) {
  91309. defines += "REINHARD_TONEMAPPING";
  91310. }
  91311. else if (_this._operator === TonemappingOperator.HejiDawson) {
  91312. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  91313. }
  91314. else if (_this._operator === TonemappingOperator.Photographic) {
  91315. defines += "PHOTOGRAPHIC_TONEMAPPING";
  91316. }
  91317. //sadly a second call to create the effect.
  91318. _this.updateEffect(defines);
  91319. _this.onApply = function (effect) {
  91320. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  91321. };
  91322. return _this;
  91323. }
  91324. return TonemapPostProcess;
  91325. }(BABYLON.PostProcess));
  91326. BABYLON.TonemapPostProcess = TonemapPostProcess;
  91327. })(BABYLON || (BABYLON = {}));
  91328. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  91329. var BABYLON;
  91330. (function (BABYLON) {
  91331. /**
  91332. * DisplayPassPostProcess which produces an output the same as it's input
  91333. */
  91334. var DisplayPassPostProcess = /** @class */ (function (_super) {
  91335. __extends(DisplayPassPostProcess, _super);
  91336. /**
  91337. * Creates the DisplayPassPostProcess
  91338. * @param name The name of the effect.
  91339. * @param options The required width/height ratio to downsize to before computing the render pass.
  91340. * @param camera The camera to apply the render pass to.
  91341. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  91342. * @param engine The engine which the post process will be applied. (default: current engine)
  91343. * @param reusable If the post process can be reused on the same frame. (default: false)
  91344. */
  91345. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  91346. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  91347. }
  91348. return DisplayPassPostProcess;
  91349. }(BABYLON.PostProcess));
  91350. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  91351. })(BABYLON || (BABYLON = {}));
  91352. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  91353. var BABYLON;
  91354. (function (BABYLON) {
  91355. /**
  91356. * Extracts highlights from the image
  91357. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  91358. */
  91359. var HighlightsPostProcess = /** @class */ (function (_super) {
  91360. __extends(HighlightsPostProcess, _super);
  91361. /**
  91362. * Extracts highlights from the image
  91363. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  91364. * @param name The name of the effect.
  91365. * @param options The required width/height ratio to downsize to before computing the render pass.
  91366. * @param camera The camera to apply the render pass to.
  91367. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  91368. * @param engine The engine which the post process will be applied. (default: current engine)
  91369. * @param reusable If the post process can be reused on the same frame. (default: false)
  91370. * @param textureType Type of texture for the post process (default: Engine.TEXTURETYPE_UNSIGNED_INT)
  91371. */
  91372. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  91373. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  91374. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  91375. }
  91376. return HighlightsPostProcess;
  91377. }(BABYLON.PostProcess));
  91378. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  91379. })(BABYLON || (BABYLON = {}));
  91380. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  91381. var BABYLON;
  91382. (function (BABYLON) {
  91383. /**
  91384. * ImageProcessingPostProcess
  91385. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses#imageprocessing
  91386. */
  91387. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  91388. __extends(ImageProcessingPostProcess, _super);
  91389. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  91390. if (camera === void 0) { camera = null; }
  91391. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  91392. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  91393. _this._fromLinearSpace = true;
  91394. /**
  91395. * Defines cache preventing GC.
  91396. */
  91397. _this._defines = {
  91398. IMAGEPROCESSING: false,
  91399. VIGNETTE: false,
  91400. VIGNETTEBLENDMODEMULTIPLY: false,
  91401. VIGNETTEBLENDMODEOPAQUE: false,
  91402. TONEMAPPING: false,
  91403. TONEMAPPING_ACES: false,
  91404. CONTRAST: false,
  91405. COLORCURVES: false,
  91406. COLORGRADING: false,
  91407. COLORGRADING3D: false,
  91408. FROMLINEARSPACE: false,
  91409. SAMPLER3DGREENDEPTH: false,
  91410. SAMPLER3DBGRMAP: false,
  91411. IMAGEPROCESSINGPOSTPROCESS: false,
  91412. EXPOSURE: false,
  91413. };
  91414. // Setup the configuration as forced by the constructor. This would then not force the
  91415. // scene materials output in linear space and let untouched the default forward pass.
  91416. if (imageProcessingConfiguration) {
  91417. imageProcessingConfiguration.applyByPostProcess = true;
  91418. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  91419. // This will cause the shader to be compiled
  91420. _this.fromLinearSpace = false;
  91421. }
  91422. // Setup the default processing configuration to the scene.
  91423. else {
  91424. _this._attachImageProcessingConfiguration(null, true);
  91425. _this.imageProcessingConfiguration.applyByPostProcess = true;
  91426. }
  91427. _this.onApply = function (effect) {
  91428. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  91429. };
  91430. return _this;
  91431. }
  91432. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  91433. /**
  91434. * Gets the image processing configuration used either in this material.
  91435. */
  91436. get: function () {
  91437. return this._imageProcessingConfiguration;
  91438. },
  91439. /**
  91440. * Sets the Default image processing configuration used either in the this material.
  91441. *
  91442. * If sets to null, the scene one is in use.
  91443. */
  91444. set: function (value) {
  91445. this._attachImageProcessingConfiguration(value);
  91446. },
  91447. enumerable: true,
  91448. configurable: true
  91449. });
  91450. /**
  91451. * Attaches a new image processing configuration to the PBR Material.
  91452. * @param configuration
  91453. */
  91454. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  91455. var _this = this;
  91456. if (doNotBuild === void 0) { doNotBuild = false; }
  91457. if (configuration === this._imageProcessingConfiguration) {
  91458. return;
  91459. }
  91460. // Detaches observer.
  91461. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  91462. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  91463. }
  91464. // Pick the scene configuration if needed.
  91465. if (!configuration) {
  91466. var scene = null;
  91467. var engine = this.getEngine();
  91468. var camera = this.getCamera();
  91469. if (camera) {
  91470. scene = camera.getScene();
  91471. }
  91472. else if (engine && engine.scenes) {
  91473. var scenes = engine.scenes;
  91474. scene = scenes[scenes.length - 1];
  91475. }
  91476. else {
  91477. scene = BABYLON.Engine.LastCreatedScene;
  91478. }
  91479. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  91480. }
  91481. else {
  91482. this._imageProcessingConfiguration = configuration;
  91483. }
  91484. // Attaches observer.
  91485. if (this._imageProcessingConfiguration) {
  91486. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  91487. _this._updateParameters();
  91488. });
  91489. }
  91490. // Ensure the effect will be rebuilt.
  91491. if (!doNotBuild) {
  91492. this._updateParameters();
  91493. }
  91494. };
  91495. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  91496. /**
  91497. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  91498. */
  91499. get: function () {
  91500. return this.imageProcessingConfiguration.colorCurves;
  91501. },
  91502. /**
  91503. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  91504. */
  91505. set: function (value) {
  91506. this.imageProcessingConfiguration.colorCurves = value;
  91507. },
  91508. enumerable: true,
  91509. configurable: true
  91510. });
  91511. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  91512. /**
  91513. * Gets wether the color curves effect is enabled.
  91514. */
  91515. get: function () {
  91516. return this.imageProcessingConfiguration.colorCurvesEnabled;
  91517. },
  91518. /**
  91519. * Sets wether the color curves effect is enabled.
  91520. */
  91521. set: function (value) {
  91522. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  91523. },
  91524. enumerable: true,
  91525. configurable: true
  91526. });
  91527. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  91528. /**
  91529. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  91530. */
  91531. get: function () {
  91532. return this.imageProcessingConfiguration.colorGradingTexture;
  91533. },
  91534. /**
  91535. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  91536. */
  91537. set: function (value) {
  91538. this.imageProcessingConfiguration.colorGradingTexture = value;
  91539. },
  91540. enumerable: true,
  91541. configurable: true
  91542. });
  91543. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  91544. /**
  91545. * Gets wether the color grading effect is enabled.
  91546. */
  91547. get: function () {
  91548. return this.imageProcessingConfiguration.colorGradingEnabled;
  91549. },
  91550. /**
  91551. * Gets wether the color grading effect is enabled.
  91552. */
  91553. set: function (value) {
  91554. this.imageProcessingConfiguration.colorGradingEnabled = value;
  91555. },
  91556. enumerable: true,
  91557. configurable: true
  91558. });
  91559. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  91560. /**
  91561. * Gets exposure used in the effect.
  91562. */
  91563. get: function () {
  91564. return this.imageProcessingConfiguration.exposure;
  91565. },
  91566. /**
  91567. * Sets exposure used in the effect.
  91568. */
  91569. set: function (value) {
  91570. this.imageProcessingConfiguration.exposure = value;
  91571. },
  91572. enumerable: true,
  91573. configurable: true
  91574. });
  91575. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  91576. /**
  91577. * Gets wether tonemapping is enabled or not.
  91578. */
  91579. get: function () {
  91580. return this._imageProcessingConfiguration.toneMappingEnabled;
  91581. },
  91582. /**
  91583. * Sets wether tonemapping is enabled or not
  91584. */
  91585. set: function (value) {
  91586. this._imageProcessingConfiguration.toneMappingEnabled = value;
  91587. },
  91588. enumerable: true,
  91589. configurable: true
  91590. });
  91591. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  91592. /**
  91593. * Gets contrast used in the effect.
  91594. */
  91595. get: function () {
  91596. return this.imageProcessingConfiguration.contrast;
  91597. },
  91598. /**
  91599. * Sets contrast used in the effect.
  91600. */
  91601. set: function (value) {
  91602. this.imageProcessingConfiguration.contrast = value;
  91603. },
  91604. enumerable: true,
  91605. configurable: true
  91606. });
  91607. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  91608. /**
  91609. * Gets Vignette stretch size.
  91610. */
  91611. get: function () {
  91612. return this.imageProcessingConfiguration.vignetteStretch;
  91613. },
  91614. /**
  91615. * Sets Vignette stretch size.
  91616. */
  91617. set: function (value) {
  91618. this.imageProcessingConfiguration.vignetteStretch = value;
  91619. },
  91620. enumerable: true,
  91621. configurable: true
  91622. });
  91623. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  91624. /**
  91625. * Gets Vignette centre X Offset.
  91626. */
  91627. get: function () {
  91628. return this.imageProcessingConfiguration.vignetteCentreX;
  91629. },
  91630. /**
  91631. * Sets Vignette centre X Offset.
  91632. */
  91633. set: function (value) {
  91634. this.imageProcessingConfiguration.vignetteCentreX = value;
  91635. },
  91636. enumerable: true,
  91637. configurable: true
  91638. });
  91639. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  91640. /**
  91641. * Gets Vignette centre Y Offset.
  91642. */
  91643. get: function () {
  91644. return this.imageProcessingConfiguration.vignetteCentreY;
  91645. },
  91646. /**
  91647. * Sets Vignette centre Y Offset.
  91648. */
  91649. set: function (value) {
  91650. this.imageProcessingConfiguration.vignetteCentreY = value;
  91651. },
  91652. enumerable: true,
  91653. configurable: true
  91654. });
  91655. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  91656. /**
  91657. * Gets Vignette weight or intensity of the vignette effect.
  91658. */
  91659. get: function () {
  91660. return this.imageProcessingConfiguration.vignetteWeight;
  91661. },
  91662. /**
  91663. * Sets Vignette weight or intensity of the vignette effect.
  91664. */
  91665. set: function (value) {
  91666. this.imageProcessingConfiguration.vignetteWeight = value;
  91667. },
  91668. enumerable: true,
  91669. configurable: true
  91670. });
  91671. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  91672. /**
  91673. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  91674. * if vignetteEnabled is set to true.
  91675. */
  91676. get: function () {
  91677. return this.imageProcessingConfiguration.vignetteColor;
  91678. },
  91679. /**
  91680. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  91681. * if vignetteEnabled is set to true.
  91682. */
  91683. set: function (value) {
  91684. this.imageProcessingConfiguration.vignetteColor = value;
  91685. },
  91686. enumerable: true,
  91687. configurable: true
  91688. });
  91689. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  91690. /**
  91691. * Gets Camera field of view used by the Vignette effect.
  91692. */
  91693. get: function () {
  91694. return this.imageProcessingConfiguration.vignetteCameraFov;
  91695. },
  91696. /**
  91697. * Sets Camera field of view used by the Vignette effect.
  91698. */
  91699. set: function (value) {
  91700. this.imageProcessingConfiguration.vignetteCameraFov = value;
  91701. },
  91702. enumerable: true,
  91703. configurable: true
  91704. });
  91705. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  91706. /**
  91707. * Gets the vignette blend mode allowing different kind of effect.
  91708. */
  91709. get: function () {
  91710. return this.imageProcessingConfiguration.vignetteBlendMode;
  91711. },
  91712. /**
  91713. * Sets the vignette blend mode allowing different kind of effect.
  91714. */
  91715. set: function (value) {
  91716. this.imageProcessingConfiguration.vignetteBlendMode = value;
  91717. },
  91718. enumerable: true,
  91719. configurable: true
  91720. });
  91721. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  91722. /**
  91723. * Gets wether the vignette effect is enabled.
  91724. */
  91725. get: function () {
  91726. return this.imageProcessingConfiguration.vignetteEnabled;
  91727. },
  91728. /**
  91729. * Sets wether the vignette effect is enabled.
  91730. */
  91731. set: function (value) {
  91732. this.imageProcessingConfiguration.vignetteEnabled = value;
  91733. },
  91734. enumerable: true,
  91735. configurable: true
  91736. });
  91737. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  91738. /**
  91739. * Gets wether the input of the processing is in Gamma or Linear Space.
  91740. */
  91741. get: function () {
  91742. return this._fromLinearSpace;
  91743. },
  91744. /**
  91745. * Sets wether the input of the processing is in Gamma or Linear Space.
  91746. */
  91747. set: function (value) {
  91748. if (this._fromLinearSpace === value) {
  91749. return;
  91750. }
  91751. this._fromLinearSpace = value;
  91752. this._updateParameters();
  91753. },
  91754. enumerable: true,
  91755. configurable: true
  91756. });
  91757. /**
  91758. * "ImageProcessingPostProcess"
  91759. * @returns "ImageProcessingPostProcess"
  91760. */
  91761. ImageProcessingPostProcess.prototype.getClassName = function () {
  91762. return "ImageProcessingPostProcess";
  91763. };
  91764. ImageProcessingPostProcess.prototype._updateParameters = function () {
  91765. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  91766. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  91767. var defines = "";
  91768. for (var define in this._defines) {
  91769. if (this._defines[define]) {
  91770. defines += "#define " + define + ";\r\n";
  91771. }
  91772. }
  91773. var samplers = ["textureSampler"];
  91774. var uniforms = ["scale"];
  91775. if (BABYLON.ImageProcessingConfiguration) {
  91776. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  91777. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  91778. }
  91779. this.updateEffect(defines, uniforms, samplers);
  91780. };
  91781. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  91782. _super.prototype.dispose.call(this, camera);
  91783. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  91784. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  91785. }
  91786. if (this._imageProcessingConfiguration) {
  91787. this.imageProcessingConfiguration.applyByPostProcess = false;
  91788. }
  91789. };
  91790. __decorate([
  91791. BABYLON.serialize()
  91792. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  91793. return ImageProcessingPostProcess;
  91794. }(BABYLON.PostProcess));
  91795. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  91796. })(BABYLON || (BABYLON = {}));
  91797. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  91798. var BABYLON;
  91799. (function (BABYLON) {
  91800. /**
  91801. * The Motion Blur Post Process which blurs an image based on the objects velocity in scene.
  91802. * Velocity can be affected by each object's rotation, position and scale depending on the transformation speed.
  91803. * As an example, all you have to do is to create the post-process:
  91804. * var mb = new BABYLON.MotionBlurPostProcess(
  91805. * 'mb', // The name of the effect.
  91806. * scene, // The scene containing the objects to blur according to their velocity.
  91807. * 1.0, // The required width/height ratio to downsize to before computing the render pass.
  91808. * camera // The camera to apply the render pass to.
  91809. * );
  91810. * Then, all objects moving, rotating and/or scaling will be blurred depending on the transformation speed.
  91811. */
  91812. var MotionBlurPostProcess = /** @class */ (function (_super) {
  91813. __extends(MotionBlurPostProcess, _super);
  91814. /**
  91815. * Creates a new instance MotionBlurPostProcess
  91816. * @param name The name of the effect.
  91817. * @param scene The scene containing the objects to blur according to their velocity.
  91818. * @param options The required width/height ratio to downsize to before computing the render pass.
  91819. * @param camera The camera to apply the render pass to.
  91820. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  91821. * @param engine The engine which the post process will be applied. (default: current engine)
  91822. * @param reusable If the post process can be reused on the same frame. (default: false)
  91823. * @param textureType Type of textures used when performing the post process. (default: 0)
  91824. * @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)
  91825. */
  91826. function MotionBlurPostProcess(name, scene, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  91827. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  91828. if (blockCompilation === void 0) { blockCompilation = false; }
  91829. var _this = _super.call(this, name, "motionBlur", ["motionStrength", "motionScale", "screenSize"], ["velocitySampler"], options, camera, samplingMode, engine, reusable, "#define GEOMETRY_SUPPORTED\n#define SAMPLES 64.0", textureType, undefined, null, blockCompilation) || this;
  91830. /**
  91831. * Defines how much the image is blurred by the movement. Default value is equal to 1
  91832. */
  91833. _this.motionStrength = 1;
  91834. _this._motionBlurSamples = 32;
  91835. _this._geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  91836. if (!_this._geometryBufferRenderer) {
  91837. // Geometry buffer renderer is not supported. So, work as a passthrough.
  91838. BABYLON.Tools.Warn("Multiple Render Target support needed to compute object based motion blur");
  91839. _this.updateEffect();
  91840. }
  91841. else {
  91842. // Geometry buffer renderer is supported.
  91843. _this._geometryBufferRenderer.enableVelocity = true;
  91844. _this.onApply = function (effect) {
  91845. effect.setVector2("screenSize", new BABYLON.Vector2(_this.width, _this.height));
  91846. effect.setFloat("motionScale", scene.getAnimationRatio());
  91847. effect.setFloat("motionStrength", _this.motionStrength);
  91848. if (_this._geometryBufferRenderer) {
  91849. var velocityIndex = _this._geometryBufferRenderer.getTextureIndex(BABYLON.GeometryBufferRenderer.VELOCITY_TEXTURE_TYPE);
  91850. effect.setTexture("velocitySampler", _this._geometryBufferRenderer.getGBuffer().textures[velocityIndex]);
  91851. }
  91852. };
  91853. }
  91854. return _this;
  91855. }
  91856. Object.defineProperty(MotionBlurPostProcess.prototype, "motionBlurSamples", {
  91857. /**
  91858. * Gets the number of iterations are used for motion blur quality. Default value is equal to 32
  91859. */
  91860. get: function () {
  91861. return this._motionBlurSamples;
  91862. },
  91863. /**
  91864. * Sets the number of iterations to be used for motion blur quality
  91865. */
  91866. set: function (samples) {
  91867. this._motionBlurSamples = samples;
  91868. if (this._geometryBufferRenderer) {
  91869. this.updateEffect("#define GEOMETRY_SUPPORTED\n#define SAMPLES " + samples.toFixed(1));
  91870. }
  91871. },
  91872. enumerable: true,
  91873. configurable: true
  91874. });
  91875. /**
  91876. * Disposes the post process.
  91877. * @param camera The camera to dispose the post process on.
  91878. */
  91879. MotionBlurPostProcess.prototype.dispose = function (camera) {
  91880. if (this._geometryBufferRenderer) {
  91881. // Clear previous transformation matrices dictionary used to compute objects velocities
  91882. this._geometryBufferRenderer._previousTransformationMatrices = {};
  91883. }
  91884. _super.prototype.dispose.call(this, camera);
  91885. };
  91886. return MotionBlurPostProcess;
  91887. }(BABYLON.PostProcess));
  91888. BABYLON.MotionBlurPostProcess = MotionBlurPostProcess;
  91889. })(BABYLON || (BABYLON = {}));
  91890. //# sourceMappingURL=babylon.motionBlurPostProcess.js.map
  91891. var BABYLON;
  91892. (function (BABYLON) {
  91893. /**
  91894. * Class used to store bone information
  91895. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  91896. */
  91897. var Bone = /** @class */ (function (_super) {
  91898. __extends(Bone, _super);
  91899. /**
  91900. * Create a new bone
  91901. * @param name defines the bone name
  91902. * @param skeleton defines the parent skeleton
  91903. * @param parentBone defines the parent (can be null if the bone is the root)
  91904. * @param localMatrix defines the local matrix
  91905. * @param restPose defines the rest pose matrix
  91906. * @param baseMatrix defines the base matrix
  91907. * @param index defines index of the bone in the hiearchy
  91908. */
  91909. function Bone(
  91910. /**
  91911. * defines the bone name
  91912. */
  91913. name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  91914. if (parentBone === void 0) { parentBone = null; }
  91915. if (localMatrix === void 0) { localMatrix = null; }
  91916. if (restPose === void 0) { restPose = null; }
  91917. if (baseMatrix === void 0) { baseMatrix = null; }
  91918. if (index === void 0) { index = null; }
  91919. var _this = _super.call(this, name, skeleton.getScene(), false) || this;
  91920. _this.name = name;
  91921. /**
  91922. * Gets the list of child bones
  91923. */
  91924. _this.children = new Array();
  91925. /** Gets the animations associated with this bone */
  91926. _this.animations = new Array();
  91927. /**
  91928. * @hidden Internal only
  91929. * Set this value to map this bone to a different index in the transform matrices
  91930. * Set this value to -1 to exclude the bone from the transform matrices
  91931. */
  91932. _this._index = null;
  91933. _this._absoluteTransform = new BABYLON.Matrix();
  91934. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  91935. _this._scalingDeterminant = 1;
  91936. _this._worldTransform = new BABYLON.Matrix();
  91937. _this._needToDecompose = true;
  91938. _this._needToCompose = false;
  91939. _this._skeleton = skeleton;
  91940. _this._localMatrix = localMatrix ? localMatrix.clone() : BABYLON.Matrix.Identity();
  91941. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  91942. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  91943. _this._index = index;
  91944. skeleton.bones.push(_this);
  91945. _this.setParent(parentBone, false);
  91946. if (baseMatrix || localMatrix) {
  91947. _this._updateDifferenceMatrix();
  91948. }
  91949. return _this;
  91950. }
  91951. Object.defineProperty(Bone.prototype, "_matrix", {
  91952. /** @hidden */
  91953. get: function () {
  91954. this._compose();
  91955. return this._localMatrix;
  91956. },
  91957. /** @hidden */
  91958. set: function (value) {
  91959. this._localMatrix.copyFrom(value);
  91960. this._needToDecompose = true;
  91961. },
  91962. enumerable: true,
  91963. configurable: true
  91964. });
  91965. // Members
  91966. /**
  91967. * Gets the parent skeleton
  91968. * @returns a skeleton
  91969. */
  91970. Bone.prototype.getSkeleton = function () {
  91971. return this._skeleton;
  91972. };
  91973. /**
  91974. * Gets parent bone
  91975. * @returns a bone or null if the bone is the root of the bone hierarchy
  91976. */
  91977. Bone.prototype.getParent = function () {
  91978. return this._parent;
  91979. };
  91980. /**
  91981. * Sets the parent bone
  91982. * @param parent defines the parent (can be null if the bone is the root)
  91983. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  91984. */
  91985. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  91986. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  91987. if (this._parent === parent) {
  91988. return;
  91989. }
  91990. if (this._parent) {
  91991. var index = this._parent.children.indexOf(this);
  91992. if (index !== -1) {
  91993. this._parent.children.splice(index, 1);
  91994. }
  91995. }
  91996. this._parent = parent;
  91997. if (this._parent) {
  91998. this._parent.children.push(this);
  91999. }
  92000. if (updateDifferenceMatrix) {
  92001. this._updateDifferenceMatrix();
  92002. }
  92003. this.markAsDirty();
  92004. };
  92005. /**
  92006. * Gets the local matrix
  92007. * @returns a matrix
  92008. */
  92009. Bone.prototype.getLocalMatrix = function () {
  92010. this._compose();
  92011. return this._localMatrix;
  92012. };
  92013. /**
  92014. * Gets the base matrix (initial matrix which remains unchanged)
  92015. * @returns a matrix
  92016. */
  92017. Bone.prototype.getBaseMatrix = function () {
  92018. return this._baseMatrix;
  92019. };
  92020. /**
  92021. * Gets the rest pose matrix
  92022. * @returns a matrix
  92023. */
  92024. Bone.prototype.getRestPose = function () {
  92025. return this._restPose;
  92026. };
  92027. /**
  92028. * Gets a matrix used to store world matrix (ie. the matrix sent to shaders)
  92029. */
  92030. Bone.prototype.getWorldMatrix = function () {
  92031. return this._worldTransform;
  92032. };
  92033. /**
  92034. * Sets the local matrix to rest pose matrix
  92035. */
  92036. Bone.prototype.returnToRest = function () {
  92037. this.updateMatrix(this._restPose.clone());
  92038. };
  92039. /**
  92040. * Gets the inverse of the absolute transform matrix.
  92041. * This matrix will be multiplied by local matrix to get the difference matrix (ie. the difference between original state and current state)
  92042. * @returns a matrix
  92043. */
  92044. Bone.prototype.getInvertedAbsoluteTransform = function () {
  92045. return this._invertedAbsoluteTransform;
  92046. };
  92047. /**
  92048. * Gets the absolute transform matrix (ie base matrix * parent world matrix)
  92049. * @returns a matrix
  92050. */
  92051. Bone.prototype.getAbsoluteTransform = function () {
  92052. return this._absoluteTransform;
  92053. };
  92054. Object.defineProperty(Bone.prototype, "position", {
  92055. // Properties (matches AbstractMesh properties)
  92056. /** Gets or sets current position (in local space) */
  92057. get: function () {
  92058. this._decompose();
  92059. return this._localPosition;
  92060. },
  92061. set: function (newPosition) {
  92062. this._decompose();
  92063. this._localPosition.copyFrom(newPosition);
  92064. this._markAsDirtyAndCompose();
  92065. },
  92066. enumerable: true,
  92067. configurable: true
  92068. });
  92069. Object.defineProperty(Bone.prototype, "rotation", {
  92070. /** Gets or sets current rotation (in local space) */
  92071. get: function () {
  92072. return this.getRotation();
  92073. },
  92074. set: function (newRotation) {
  92075. this.setRotation(newRotation);
  92076. },
  92077. enumerable: true,
  92078. configurable: true
  92079. });
  92080. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  92081. /** Gets or sets current rotation quaternion (in local space) */
  92082. get: function () {
  92083. this._decompose();
  92084. return this._localRotation;
  92085. },
  92086. set: function (newRotation) {
  92087. this.setRotationQuaternion(newRotation);
  92088. },
  92089. enumerable: true,
  92090. configurable: true
  92091. });
  92092. Object.defineProperty(Bone.prototype, "scaling", {
  92093. /** Gets or sets current scaling (in local space) */
  92094. get: function () {
  92095. return this.getScale();
  92096. },
  92097. set: function (newScaling) {
  92098. this.setScale(newScaling);
  92099. },
  92100. enumerable: true,
  92101. configurable: true
  92102. });
  92103. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  92104. /**
  92105. * Gets the animation properties override
  92106. */
  92107. get: function () {
  92108. return this._skeleton.animationPropertiesOverride;
  92109. },
  92110. enumerable: true,
  92111. configurable: true
  92112. });
  92113. // Methods
  92114. Bone.prototype._decompose = function () {
  92115. if (!this._needToDecompose) {
  92116. return;
  92117. }
  92118. this._needToDecompose = false;
  92119. if (!this._localScaling) {
  92120. this._localScaling = BABYLON.Vector3.Zero();
  92121. this._localRotation = BABYLON.Quaternion.Zero();
  92122. this._localPosition = BABYLON.Vector3.Zero();
  92123. }
  92124. this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);
  92125. };
  92126. Bone.prototype._compose = function () {
  92127. if (!this._needToCompose) {
  92128. return;
  92129. }
  92130. this._needToCompose = false;
  92131. BABYLON.Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);
  92132. };
  92133. /**
  92134. * Update the base and local matrices
  92135. * @param matrix defines the new base or local matrix
  92136. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  92137. * @param updateLocalMatrix defines if the local matrix should be updated
  92138. */
  92139. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix, updateLocalMatrix) {
  92140. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  92141. if (updateLocalMatrix === void 0) { updateLocalMatrix = true; }
  92142. this._baseMatrix.copyFrom(matrix);
  92143. if (updateDifferenceMatrix) {
  92144. this._updateDifferenceMatrix();
  92145. }
  92146. if (updateLocalMatrix) {
  92147. this._localMatrix.copyFrom(matrix);
  92148. this._markAsDirtyAndDecompose();
  92149. }
  92150. else {
  92151. this.markAsDirty();
  92152. }
  92153. };
  92154. /** @hidden */
  92155. Bone.prototype._updateDifferenceMatrix = function (rootMatrix, updateChildren) {
  92156. if (updateChildren === void 0) { updateChildren = true; }
  92157. if (!rootMatrix) {
  92158. rootMatrix = this._baseMatrix;
  92159. }
  92160. if (this._parent) {
  92161. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  92162. }
  92163. else {
  92164. this._absoluteTransform.copyFrom(rootMatrix);
  92165. }
  92166. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  92167. if (updateChildren) {
  92168. for (var index = 0; index < this.children.length; index++) {
  92169. this.children[index]._updateDifferenceMatrix();
  92170. }
  92171. }
  92172. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  92173. };
  92174. /**
  92175. * Flag the bone as dirty (Forcing it to update everything)
  92176. */
  92177. Bone.prototype.markAsDirty = function () {
  92178. this._currentRenderId++;
  92179. this._childRenderId++;
  92180. this._skeleton._markAsDirty();
  92181. };
  92182. Bone.prototype._markAsDirtyAndCompose = function () {
  92183. this.markAsDirty();
  92184. this._needToCompose = true;
  92185. };
  92186. Bone.prototype._markAsDirtyAndDecompose = function () {
  92187. this.markAsDirty();
  92188. this._needToDecompose = true;
  92189. };
  92190. /**
  92191. * Copy an animation range from another bone
  92192. * @param source defines the source bone
  92193. * @param rangeName defines the range name to copy
  92194. * @param frameOffset defines the frame offset
  92195. * @param rescaleAsRequired defines if rescaling must be applied if required
  92196. * @param skelDimensionsRatio defines the scaling ratio
  92197. * @returns true if operation was successful
  92198. */
  92199. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  92200. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  92201. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  92202. // all animation may be coming from a library skeleton, so may need to create animation
  92203. if (this.animations.length === 0) {
  92204. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  92205. this.animations[0].setKeys([]);
  92206. }
  92207. // get animation info / verify there is such a range from the source bone
  92208. var sourceRange = source.animations[0].getRange(rangeName);
  92209. if (!sourceRange) {
  92210. return false;
  92211. }
  92212. var from = sourceRange.from;
  92213. var to = sourceRange.to;
  92214. var sourceKeys = source.animations[0].getKeys();
  92215. // rescaling prep
  92216. var sourceBoneLength = source.length;
  92217. var sourceParent = source.getParent();
  92218. var parent = this.getParent();
  92219. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  92220. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  92221. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  92222. var destKeys = this.animations[0].getKeys();
  92223. // loop vars declaration
  92224. var orig;
  92225. var origTranslation;
  92226. var mat;
  92227. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  92228. orig = sourceKeys[key];
  92229. if (orig.frame >= from && orig.frame <= to) {
  92230. if (rescaleAsRequired) {
  92231. mat = orig.value.clone();
  92232. // scale based on parent ratio, when bone has parent
  92233. if (parentScalingReqd) {
  92234. origTranslation = mat.getTranslation();
  92235. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  92236. // scale based on skeleton dimension ratio when root bone, and value is passed
  92237. }
  92238. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  92239. origTranslation = mat.getTranslation();
  92240. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  92241. // use original when root bone, and no data for skelDimensionsRatio
  92242. }
  92243. else {
  92244. mat = orig.value;
  92245. }
  92246. }
  92247. else {
  92248. mat = orig.value;
  92249. }
  92250. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  92251. }
  92252. }
  92253. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  92254. return true;
  92255. };
  92256. /**
  92257. * Translate the bone in local or world space
  92258. * @param vec The amount to translate the bone
  92259. * @param space The space that the translation is in
  92260. * @param mesh The mesh that this bone is attached to. This is only used in world space
  92261. */
  92262. Bone.prototype.translate = function (vec, space, mesh) {
  92263. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  92264. var lm = this.getLocalMatrix();
  92265. if (space == BABYLON.Space.LOCAL) {
  92266. lm.addAtIndex(12, vec.x);
  92267. lm.addAtIndex(13, vec.y);
  92268. lm.addAtIndex(14, vec.z);
  92269. }
  92270. else {
  92271. var wm = null;
  92272. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  92273. if (mesh) {
  92274. wm = mesh.getWorldMatrix();
  92275. }
  92276. this._skeleton.computeAbsoluteTransforms();
  92277. var tmat = Bone._tmpMats[0];
  92278. var tvec = Bone._tmpVecs[0];
  92279. if (this._parent) {
  92280. if (mesh && wm) {
  92281. tmat.copyFrom(this._parent.getAbsoluteTransform());
  92282. tmat.multiplyToRef(wm, tmat);
  92283. }
  92284. else {
  92285. tmat.copyFrom(this._parent.getAbsoluteTransform());
  92286. }
  92287. }
  92288. tmat.setTranslationFromFloats(0, 0, 0);
  92289. tmat.invert();
  92290. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  92291. lm.addAtIndex(12, tvec.x);
  92292. lm.addAtIndex(13, tvec.y);
  92293. lm.addAtIndex(14, tvec.z);
  92294. }
  92295. this._markAsDirtyAndDecompose();
  92296. };
  92297. /**
  92298. * Set the postion of the bone in local or world space
  92299. * @param position The position to set the bone
  92300. * @param space The space that the position is in
  92301. * @param mesh The mesh that this bone is attached to. This is only used in world space
  92302. */
  92303. Bone.prototype.setPosition = function (position, space, mesh) {
  92304. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  92305. var lm = this.getLocalMatrix();
  92306. if (space == BABYLON.Space.LOCAL) {
  92307. lm.setTranslationFromFloats(position.x, position.y, position.z);
  92308. }
  92309. else {
  92310. var wm = null;
  92311. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  92312. if (mesh) {
  92313. wm = mesh.getWorldMatrix();
  92314. }
  92315. this._skeleton.computeAbsoluteTransforms();
  92316. var tmat = Bone._tmpMats[0];
  92317. var vec = Bone._tmpVecs[0];
  92318. if (this._parent) {
  92319. if (mesh && wm) {
  92320. tmat.copyFrom(this._parent.getAbsoluteTransform());
  92321. tmat.multiplyToRef(wm, tmat);
  92322. }
  92323. else {
  92324. tmat.copyFrom(this._parent.getAbsoluteTransform());
  92325. }
  92326. }
  92327. tmat.invert();
  92328. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  92329. lm.setTranslationFromFloats(vec.x, vec.y, vec.z);
  92330. }
  92331. this._markAsDirtyAndDecompose();
  92332. };
  92333. /**
  92334. * Set the absolute position of the bone (world space)
  92335. * @param position The position to set the bone
  92336. * @param mesh The mesh that this bone is attached to
  92337. */
  92338. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  92339. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  92340. };
  92341. /**
  92342. * Scale the bone on the x, y and z axes (in local space)
  92343. * @param x The amount to scale the bone on the x axis
  92344. * @param y The amount to scale the bone on the y axis
  92345. * @param z The amount to scale the bone on the z axis
  92346. * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default)
  92347. */
  92348. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  92349. if (scaleChildren === void 0) { scaleChildren = false; }
  92350. var locMat = this.getLocalMatrix();
  92351. // Apply new scaling on top of current local matrix
  92352. var scaleMat = Bone._tmpMats[0];
  92353. BABYLON.Matrix.ScalingToRef(x, y, z, scaleMat);
  92354. scaleMat.multiplyToRef(locMat, locMat);
  92355. // Invert scaling matrix and apply the inverse to all children
  92356. scaleMat.invert();
  92357. for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
  92358. var child = _a[_i];
  92359. var cm = child.getLocalMatrix();
  92360. cm.multiplyToRef(scaleMat, cm);
  92361. cm.multiplyAtIndex(12, x);
  92362. cm.multiplyAtIndex(13, y);
  92363. cm.multiplyAtIndex(14, z);
  92364. child._markAsDirtyAndDecompose();
  92365. }
  92366. this._markAsDirtyAndDecompose();
  92367. if (scaleChildren) {
  92368. for (var _b = 0, _c = this.children; _b < _c.length; _b++) {
  92369. var child = _c[_b];
  92370. child.scale(x, y, z, scaleChildren);
  92371. }
  92372. }
  92373. };
  92374. /**
  92375. * Set the bone scaling in local space
  92376. * @param scale defines the scaling vector
  92377. */
  92378. Bone.prototype.setScale = function (scale) {
  92379. this._decompose();
  92380. this._localScaling.copyFrom(scale);
  92381. this._markAsDirtyAndCompose();
  92382. };
  92383. /**
  92384. * Gets the current scaling in local space
  92385. * @returns the current scaling vector
  92386. */
  92387. Bone.prototype.getScale = function () {
  92388. this._decompose();
  92389. return this._localScaling;
  92390. };
  92391. /**
  92392. * Gets the current scaling in local space and stores it in a target vector
  92393. * @param result defines the target vector
  92394. */
  92395. Bone.prototype.getScaleToRef = function (result) {
  92396. this._decompose();
  92397. result.copyFrom(this._localScaling);
  92398. };
  92399. /**
  92400. * Set the yaw, pitch, and roll of the bone in local or world space
  92401. * @param yaw The rotation of the bone on the y axis
  92402. * @param pitch The rotation of the bone on the x axis
  92403. * @param roll The rotation of the bone on the z axis
  92404. * @param space The space that the axes of rotation are in
  92405. * @param mesh The mesh that this bone is attached to. This is only used in world space
  92406. */
  92407. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  92408. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  92409. if (space === BABYLON.Space.LOCAL) {
  92410. var quat = Bone._tmpQuat;
  92411. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);
  92412. this.setRotationQuaternion(quat, space, mesh);
  92413. return;
  92414. }
  92415. var rotMatInv = Bone._tmpMats[0];
  92416. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  92417. return;
  92418. }
  92419. var rotMat = Bone._tmpMats[1];
  92420. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  92421. rotMatInv.multiplyToRef(rotMat, rotMat);
  92422. this._rotateWithMatrix(rotMat, space, mesh);
  92423. };
  92424. /**
  92425. * Add a rotation to the bone on an axis in local or world space
  92426. * @param axis The axis to rotate the bone on
  92427. * @param amount The amount to rotate the bone
  92428. * @param space The space that the axis is in
  92429. * @param mesh The mesh that this bone is attached to. This is only used in world space
  92430. */
  92431. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  92432. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  92433. var rmat = Bone._tmpMats[0];
  92434. rmat.setTranslationFromFloats(0, 0, 0);
  92435. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  92436. this._rotateWithMatrix(rmat, space, mesh);
  92437. };
  92438. /**
  92439. * Set the rotation of the bone to a particular axis angle in local or world space
  92440. * @param axis The axis to rotate the bone on
  92441. * @param angle The angle that the bone should be rotated to
  92442. * @param space The space that the axis is in
  92443. * @param mesh The mesh that this bone is attached to. This is only used in world space
  92444. */
  92445. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  92446. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  92447. if (space === BABYLON.Space.LOCAL) {
  92448. var quat = Bone._tmpQuat;
  92449. BABYLON.Quaternion.RotationAxisToRef(axis, angle, quat);
  92450. this.setRotationQuaternion(quat, space, mesh);
  92451. return;
  92452. }
  92453. var rotMatInv = Bone._tmpMats[0];
  92454. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  92455. return;
  92456. }
  92457. var rotMat = Bone._tmpMats[1];
  92458. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  92459. rotMatInv.multiplyToRef(rotMat, rotMat);
  92460. this._rotateWithMatrix(rotMat, space, mesh);
  92461. };
  92462. /**
  92463. * Set the euler rotation of the bone in local of world space
  92464. * @param rotation The euler rotation that the bone should be set to
  92465. * @param space The space that the rotation is in
  92466. * @param mesh The mesh that this bone is attached to. This is only used in world space
  92467. */
  92468. Bone.prototype.setRotation = function (rotation, space, mesh) {
  92469. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  92470. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  92471. };
  92472. /**
  92473. * Set the quaternion rotation of the bone in local of world space
  92474. * @param quat The quaternion rotation that the bone should be set to
  92475. * @param space The space that the rotation is in
  92476. * @param mesh The mesh that this bone is attached to. This is only used in world space
  92477. */
  92478. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  92479. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  92480. if (space === BABYLON.Space.LOCAL) {
  92481. this._decompose();
  92482. this._localRotation.copyFrom(quat);
  92483. this._markAsDirtyAndCompose();
  92484. return;
  92485. }
  92486. var rotMatInv = Bone._tmpMats[0];
  92487. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  92488. return;
  92489. }
  92490. var rotMat = Bone._tmpMats[1];
  92491. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  92492. rotMatInv.multiplyToRef(rotMat, rotMat);
  92493. this._rotateWithMatrix(rotMat, space, mesh);
  92494. };
  92495. /**
  92496. * Set the rotation matrix of the bone in local of world space
  92497. * @param rotMat The rotation matrix that the bone should be set to
  92498. * @param space The space that the rotation is in
  92499. * @param mesh The mesh that this bone is attached to. This is only used in world space
  92500. */
  92501. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  92502. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  92503. if (space === BABYLON.Space.LOCAL) {
  92504. var quat = Bone._tmpQuat;
  92505. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, quat);
  92506. this.setRotationQuaternion(quat, space, mesh);
  92507. return;
  92508. }
  92509. var rotMatInv = Bone._tmpMats[0];
  92510. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  92511. return;
  92512. }
  92513. var rotMat2 = Bone._tmpMats[1];
  92514. rotMat2.copyFrom(rotMat);
  92515. rotMatInv.multiplyToRef(rotMat, rotMat2);
  92516. this._rotateWithMatrix(rotMat2, space, mesh);
  92517. };
  92518. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  92519. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  92520. var lmat = this.getLocalMatrix();
  92521. var lx = lmat.m[12];
  92522. var ly = lmat.m[13];
  92523. var lz = lmat.m[14];
  92524. var parent = this.getParent();
  92525. var parentScale = Bone._tmpMats[3];
  92526. var parentScaleInv = Bone._tmpMats[4];
  92527. if (parent && space == BABYLON.Space.WORLD) {
  92528. if (mesh) {
  92529. parentScale.copyFrom(mesh.getWorldMatrix());
  92530. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  92531. }
  92532. else {
  92533. parentScale.copyFrom(parent.getAbsoluteTransform());
  92534. }
  92535. parentScaleInv.copyFrom(parentScale);
  92536. parentScaleInv.invert();
  92537. lmat.multiplyToRef(parentScale, lmat);
  92538. lmat.multiplyToRef(rmat, lmat);
  92539. lmat.multiplyToRef(parentScaleInv, lmat);
  92540. }
  92541. else {
  92542. if (space == BABYLON.Space.WORLD && mesh) {
  92543. parentScale.copyFrom(mesh.getWorldMatrix());
  92544. parentScaleInv.copyFrom(parentScale);
  92545. parentScaleInv.invert();
  92546. lmat.multiplyToRef(parentScale, lmat);
  92547. lmat.multiplyToRef(rmat, lmat);
  92548. lmat.multiplyToRef(parentScaleInv, lmat);
  92549. }
  92550. else {
  92551. lmat.multiplyToRef(rmat, lmat);
  92552. }
  92553. }
  92554. lmat.setTranslationFromFloats(lx, ly, lz);
  92555. this.computeAbsoluteTransforms();
  92556. this._markAsDirtyAndDecompose();
  92557. };
  92558. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, mesh) {
  92559. var scaleMatrix = Bone._tmpMats[2];
  92560. rotMatInv.copyFrom(this.getAbsoluteTransform());
  92561. if (mesh) {
  92562. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  92563. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, scaleMatrix);
  92564. }
  92565. rotMatInv.invert();
  92566. if (isNaN(rotMatInv.m[0])) {
  92567. // Matrix failed to invert.
  92568. // This can happen if scale is zero for example.
  92569. return false;
  92570. }
  92571. scaleMatrix.multiplyAtIndex(0, this._scalingDeterminant);
  92572. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  92573. return true;
  92574. };
  92575. /**
  92576. * Get the position of the bone in local or world space
  92577. * @param space The space that the returned position is in
  92578. * @param mesh The mesh that this bone is attached to. This is only used in world space
  92579. * @returns The position of the bone
  92580. */
  92581. Bone.prototype.getPosition = function (space, mesh) {
  92582. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  92583. if (mesh === void 0) { mesh = null; }
  92584. var pos = BABYLON.Vector3.Zero();
  92585. this.getPositionToRef(space, mesh, pos);
  92586. return pos;
  92587. };
  92588. /**
  92589. * Copy the position of the bone to a vector3 in local or world space
  92590. * @param space The space that the returned position is in
  92591. * @param mesh The mesh that this bone is attached to. This is only used in world space
  92592. * @param result The vector3 to copy the position to
  92593. */
  92594. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  92595. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  92596. if (space == BABYLON.Space.LOCAL) {
  92597. var lm = this.getLocalMatrix();
  92598. result.x = lm.m[12];
  92599. result.y = lm.m[13];
  92600. result.z = lm.m[14];
  92601. }
  92602. else {
  92603. var wm = null;
  92604. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  92605. if (mesh) {
  92606. wm = mesh.getWorldMatrix();
  92607. }
  92608. this._skeleton.computeAbsoluteTransforms();
  92609. var tmat = Bone._tmpMats[0];
  92610. if (mesh && wm) {
  92611. tmat.copyFrom(this.getAbsoluteTransform());
  92612. tmat.multiplyToRef(wm, tmat);
  92613. }
  92614. else {
  92615. tmat = this.getAbsoluteTransform();
  92616. }
  92617. result.x = tmat.m[12];
  92618. result.y = tmat.m[13];
  92619. result.z = tmat.m[14];
  92620. }
  92621. };
  92622. /**
  92623. * Get the absolute position of the bone (world space)
  92624. * @param mesh The mesh that this bone is attached to
  92625. * @returns The absolute position of the bone
  92626. */
  92627. Bone.prototype.getAbsolutePosition = function (mesh) {
  92628. if (mesh === void 0) { mesh = null; }
  92629. var pos = BABYLON.Vector3.Zero();
  92630. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  92631. return pos;
  92632. };
  92633. /**
  92634. * Copy the absolute position of the bone (world space) to the result param
  92635. * @param mesh The mesh that this bone is attached to
  92636. * @param result The vector3 to copy the absolute position to
  92637. */
  92638. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  92639. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  92640. };
  92641. /**
  92642. * Compute the absolute transforms of this bone and its children
  92643. */
  92644. Bone.prototype.computeAbsoluteTransforms = function () {
  92645. this._compose();
  92646. if (this._parent) {
  92647. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  92648. }
  92649. else {
  92650. this._absoluteTransform.copyFrom(this._localMatrix);
  92651. var poseMatrix = this._skeleton.getPoseMatrix();
  92652. if (poseMatrix) {
  92653. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  92654. }
  92655. }
  92656. var children = this.children;
  92657. var len = children.length;
  92658. for (var i = 0; i < len; i++) {
  92659. children[i].computeAbsoluteTransforms();
  92660. }
  92661. };
  92662. /**
  92663. * Get the world direction from an axis that is in the local space of the bone
  92664. * @param localAxis The local direction that is used to compute the world direction
  92665. * @param mesh The mesh that this bone is attached to
  92666. * @returns The world direction
  92667. */
  92668. Bone.prototype.getDirection = function (localAxis, mesh) {
  92669. if (mesh === void 0) { mesh = null; }
  92670. var result = BABYLON.Vector3.Zero();
  92671. this.getDirectionToRef(localAxis, mesh, result);
  92672. return result;
  92673. };
  92674. /**
  92675. * Copy the world direction to a vector3 from an axis that is in the local space of the bone
  92676. * @param localAxis The local direction that is used to compute the world direction
  92677. * @param mesh The mesh that this bone is attached to
  92678. * @param result The vector3 that the world direction will be copied to
  92679. */
  92680. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  92681. if (mesh === void 0) { mesh = null; }
  92682. var wm = null;
  92683. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  92684. if (mesh) {
  92685. wm = mesh.getWorldMatrix();
  92686. }
  92687. this._skeleton.computeAbsoluteTransforms();
  92688. var mat = Bone._tmpMats[0];
  92689. mat.copyFrom(this.getAbsoluteTransform());
  92690. if (mesh && wm) {
  92691. mat.multiplyToRef(wm, mat);
  92692. }
  92693. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  92694. result.normalize();
  92695. };
  92696. /**
  92697. * Get the euler rotation of the bone in local or world space
  92698. * @param space The space that the rotation should be in
  92699. * @param mesh The mesh that this bone is attached to. This is only used in world space
  92700. * @returns The euler rotation
  92701. */
  92702. Bone.prototype.getRotation = function (space, mesh) {
  92703. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  92704. if (mesh === void 0) { mesh = null; }
  92705. var result = BABYLON.Vector3.Zero();
  92706. this.getRotationToRef(space, mesh, result);
  92707. return result;
  92708. };
  92709. /**
  92710. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space
  92711. * @param space The space that the rotation should be in
  92712. * @param mesh The mesh that this bone is attached to. This is only used in world space
  92713. * @param result The vector3 that the rotation should be copied to
  92714. */
  92715. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  92716. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  92717. if (mesh === void 0) { mesh = null; }
  92718. var quat = Bone._tmpQuat;
  92719. this.getRotationQuaternionToRef(space, mesh, quat);
  92720. quat.toEulerAnglesToRef(result);
  92721. };
  92722. /**
  92723. * Get the quaternion rotation of the bone in either local or world space
  92724. * @param space The space that the rotation should be in
  92725. * @param mesh The mesh that this bone is attached to. This is only used in world space
  92726. * @returns The quaternion rotation
  92727. */
  92728. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  92729. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  92730. if (mesh === void 0) { mesh = null; }
  92731. var result = BABYLON.Quaternion.Identity();
  92732. this.getRotationQuaternionToRef(space, mesh, result);
  92733. return result;
  92734. };
  92735. /**
  92736. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space
  92737. * @param space The space that the rotation should be in
  92738. * @param mesh The mesh that this bone is attached to. This is only used in world space
  92739. * @param result The quaternion that the rotation should be copied to
  92740. */
  92741. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  92742. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  92743. if (mesh === void 0) { mesh = null; }
  92744. if (space == BABYLON.Space.LOCAL) {
  92745. this._decompose();
  92746. result.copyFrom(this._localRotation);
  92747. }
  92748. else {
  92749. var mat = Bone._tmpMats[0];
  92750. var amat = this.getAbsoluteTransform();
  92751. if (mesh) {
  92752. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  92753. }
  92754. else {
  92755. mat.copyFrom(amat);
  92756. }
  92757. mat.multiplyAtIndex(0, this._scalingDeterminant);
  92758. mat.multiplyAtIndex(1, this._scalingDeterminant);
  92759. mat.multiplyAtIndex(2, this._scalingDeterminant);
  92760. mat.decompose(undefined, result, undefined);
  92761. }
  92762. };
  92763. /**
  92764. * Get the rotation matrix of the bone in local or world space
  92765. * @param space The space that the rotation should be in
  92766. * @param mesh The mesh that this bone is attached to. This is only used in world space
  92767. * @returns The rotation matrix
  92768. */
  92769. Bone.prototype.getRotationMatrix = function (space, mesh) {
  92770. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  92771. var result = BABYLON.Matrix.Identity();
  92772. this.getRotationMatrixToRef(space, mesh, result);
  92773. return result;
  92774. };
  92775. /**
  92776. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space
  92777. * @param space The space that the rotation should be in
  92778. * @param mesh The mesh that this bone is attached to. This is only used in world space
  92779. * @param result The quaternion that the rotation should be copied to
  92780. */
  92781. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  92782. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  92783. if (space == BABYLON.Space.LOCAL) {
  92784. this.getLocalMatrix().getRotationMatrixToRef(result);
  92785. }
  92786. else {
  92787. var mat = Bone._tmpMats[0];
  92788. var amat = this.getAbsoluteTransform();
  92789. if (mesh) {
  92790. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  92791. }
  92792. else {
  92793. mat.copyFrom(amat);
  92794. }
  92795. mat.multiplyAtIndex(0, this._scalingDeterminant);
  92796. mat.multiplyAtIndex(1, this._scalingDeterminant);
  92797. mat.multiplyAtIndex(2, this._scalingDeterminant);
  92798. mat.getRotationMatrixToRef(result);
  92799. }
  92800. };
  92801. /**
  92802. * Get the world position of a point that is in the local space of the bone
  92803. * @param position The local position
  92804. * @param mesh The mesh that this bone is attached to
  92805. * @returns The world position
  92806. */
  92807. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  92808. if (mesh === void 0) { mesh = null; }
  92809. var result = BABYLON.Vector3.Zero();
  92810. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  92811. return result;
  92812. };
  92813. /**
  92814. * Get the world position of a point that is in the local space of the bone and copy it to the result param
  92815. * @param position The local position
  92816. * @param mesh The mesh that this bone is attached to
  92817. * @param result The vector3 that the world position should be copied to
  92818. */
  92819. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  92820. if (mesh === void 0) { mesh = null; }
  92821. var wm = null;
  92822. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  92823. if (mesh) {
  92824. wm = mesh.getWorldMatrix();
  92825. }
  92826. this._skeleton.computeAbsoluteTransforms();
  92827. var tmat = Bone._tmpMats[0];
  92828. if (mesh && wm) {
  92829. tmat.copyFrom(this.getAbsoluteTransform());
  92830. tmat.multiplyToRef(wm, tmat);
  92831. }
  92832. else {
  92833. tmat = this.getAbsoluteTransform();
  92834. }
  92835. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  92836. };
  92837. /**
  92838. * Get the local position of a point that is in world space
  92839. * @param position The world position
  92840. * @param mesh The mesh that this bone is attached to
  92841. * @returns The local position
  92842. */
  92843. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  92844. if (mesh === void 0) { mesh = null; }
  92845. var result = BABYLON.Vector3.Zero();
  92846. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  92847. return result;
  92848. };
  92849. /**
  92850. * Get the local position of a point that is in world space and copy it to the result param
  92851. * @param position The world position
  92852. * @param mesh The mesh that this bone is attached to
  92853. * @param result The vector3 that the local position should be copied to
  92854. */
  92855. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  92856. if (mesh === void 0) { mesh = null; }
  92857. var wm = null;
  92858. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  92859. if (mesh) {
  92860. wm = mesh.getWorldMatrix();
  92861. }
  92862. this._skeleton.computeAbsoluteTransforms();
  92863. var tmat = Bone._tmpMats[0];
  92864. tmat.copyFrom(this.getAbsoluteTransform());
  92865. if (mesh && wm) {
  92866. tmat.multiplyToRef(wm, tmat);
  92867. }
  92868. tmat.invert();
  92869. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  92870. };
  92871. Bone._tmpVecs = BABYLON.Tools.BuildArray(2, BABYLON.Vector3.Zero);
  92872. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  92873. Bone._tmpMats = BABYLON.Tools.BuildArray(5, BABYLON.Matrix.Identity);
  92874. return Bone;
  92875. }(BABYLON.Node));
  92876. BABYLON.Bone = Bone;
  92877. })(BABYLON || (BABYLON = {}));
  92878. //# sourceMappingURL=babylon.bone.js.map
  92879. var BABYLON;
  92880. (function (BABYLON) {
  92881. /**
  92882. * Class used to apply inverse kinematics to bones
  92883. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#boneikcontroller
  92884. */
  92885. var BoneIKController = /** @class */ (function () {
  92886. /**
  92887. * Creates a new BoneIKController
  92888. * @param mesh defines the mesh to control
  92889. * @param bone defines the bone to control
  92890. * @param options defines options to set up the controller
  92891. */
  92892. function BoneIKController(mesh, bone, options) {
  92893. /**
  92894. * Gets or sets the target position
  92895. */
  92896. this.targetPosition = BABYLON.Vector3.Zero();
  92897. /**
  92898. * Gets or sets the pole target position
  92899. */
  92900. this.poleTargetPosition = BABYLON.Vector3.Zero();
  92901. /**
  92902. * Gets or sets the pole target local offset
  92903. */
  92904. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  92905. /**
  92906. * Gets or sets the pole angle
  92907. */
  92908. this.poleAngle = 0;
  92909. /**
  92910. * 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)
  92911. */
  92912. this.slerpAmount = 1;
  92913. this._bone1Quat = BABYLON.Quaternion.Identity();
  92914. this._bone1Mat = BABYLON.Matrix.Identity();
  92915. this._bone2Ang = Math.PI;
  92916. this._maxAngle = Math.PI;
  92917. this._rightHandedSystem = false;
  92918. this._bendAxis = BABYLON.Vector3.Right();
  92919. this._slerping = false;
  92920. this._adjustRoll = 0;
  92921. this._bone2 = bone;
  92922. this._bone1 = bone.getParent();
  92923. if (!this._bone1) {
  92924. return;
  92925. }
  92926. this.mesh = mesh;
  92927. var bonePos = bone.getPosition();
  92928. if (bone.getAbsoluteTransform().determinant() > 0) {
  92929. this._rightHandedSystem = true;
  92930. this._bendAxis.x = 0;
  92931. this._bendAxis.y = 0;
  92932. this._bendAxis.z = -1;
  92933. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  92934. this._adjustRoll = Math.PI * .5;
  92935. this._bendAxis.z = 1;
  92936. }
  92937. }
  92938. if (this._bone1.length) {
  92939. var boneScale1 = this._bone1.getScale();
  92940. var boneScale2 = this._bone2.getScale();
  92941. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  92942. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  92943. }
  92944. else if (this._bone1.children[0]) {
  92945. mesh.computeWorldMatrix(true);
  92946. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  92947. var pos2 = this._bone2.getAbsolutePosition(mesh);
  92948. var pos3 = this._bone1.getAbsolutePosition(mesh);
  92949. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  92950. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  92951. }
  92952. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  92953. this.maxAngle = Math.PI;
  92954. if (options) {
  92955. if (options.targetMesh) {
  92956. this.targetMesh = options.targetMesh;
  92957. this.targetMesh.computeWorldMatrix(true);
  92958. }
  92959. if (options.poleTargetMesh) {
  92960. this.poleTargetMesh = options.poleTargetMesh;
  92961. this.poleTargetMesh.computeWorldMatrix(true);
  92962. }
  92963. else if (options.poleTargetBone) {
  92964. this.poleTargetBone = options.poleTargetBone;
  92965. }
  92966. else if (this._bone1.getParent()) {
  92967. this.poleTargetBone = this._bone1.getParent();
  92968. }
  92969. if (options.poleTargetLocalOffset) {
  92970. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  92971. }
  92972. if (options.poleAngle) {
  92973. this.poleAngle = options.poleAngle;
  92974. }
  92975. if (options.bendAxis) {
  92976. this._bendAxis.copyFrom(options.bendAxis);
  92977. }
  92978. if (options.maxAngle) {
  92979. this.maxAngle = options.maxAngle;
  92980. }
  92981. if (options.slerpAmount) {
  92982. this.slerpAmount = options.slerpAmount;
  92983. }
  92984. }
  92985. }
  92986. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  92987. /**
  92988. * Gets or sets maximum allowed angle
  92989. */
  92990. get: function () {
  92991. return this._maxAngle;
  92992. },
  92993. set: function (value) {
  92994. this._setMaxAngle(value);
  92995. },
  92996. enumerable: true,
  92997. configurable: true
  92998. });
  92999. BoneIKController.prototype._setMaxAngle = function (ang) {
  93000. if (ang < 0) {
  93001. ang = 0;
  93002. }
  93003. if (ang > Math.PI || ang == undefined) {
  93004. ang = Math.PI;
  93005. }
  93006. this._maxAngle = ang;
  93007. var a = this._bone1Length;
  93008. var b = this._bone2Length;
  93009. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  93010. };
  93011. /**
  93012. * Force the controller to update the bones
  93013. */
  93014. BoneIKController.prototype.update = function () {
  93015. var bone1 = this._bone1;
  93016. if (!bone1) {
  93017. return;
  93018. }
  93019. var target = this.targetPosition;
  93020. var poleTarget = this.poleTargetPosition;
  93021. var mat1 = BoneIKController._tmpMats[0];
  93022. var mat2 = BoneIKController._tmpMats[1];
  93023. if (this.targetMesh) {
  93024. target.copyFrom(this.targetMesh.getAbsolutePosition());
  93025. }
  93026. if (this.poleTargetBone) {
  93027. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  93028. }
  93029. else if (this.poleTargetMesh) {
  93030. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  93031. }
  93032. var bonePos = BoneIKController._tmpVecs[0];
  93033. var zaxis = BoneIKController._tmpVecs[1];
  93034. var xaxis = BoneIKController._tmpVecs[2];
  93035. var yaxis = BoneIKController._tmpVecs[3];
  93036. var upAxis = BoneIKController._tmpVecs[4];
  93037. var _tmpQuat = BoneIKController._tmpQuat;
  93038. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  93039. poleTarget.subtractToRef(bonePos, upAxis);
  93040. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  93041. upAxis.y = 1;
  93042. }
  93043. else {
  93044. upAxis.normalize();
  93045. }
  93046. target.subtractToRef(bonePos, yaxis);
  93047. yaxis.normalize();
  93048. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  93049. zaxis.normalize();
  93050. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  93051. xaxis.normalize();
  93052. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  93053. var a = this._bone1Length;
  93054. var b = this._bone2Length;
  93055. var c = BABYLON.Vector3.Distance(bonePos, target);
  93056. if (this._maxReach > 0) {
  93057. c = Math.min(this._maxReach, c);
  93058. }
  93059. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  93060. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  93061. if (acosa > 1) {
  93062. acosa = 1;
  93063. }
  93064. if (acosb > 1) {
  93065. acosb = 1;
  93066. }
  93067. if (acosa < -1) {
  93068. acosa = -1;
  93069. }
  93070. if (acosb < -1) {
  93071. acosb = -1;
  93072. }
  93073. var angA = Math.acos(acosa);
  93074. var angB = Math.acos(acosb);
  93075. var angC = -angA - angB;
  93076. if (this._rightHandedSystem) {
  93077. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  93078. mat2.multiplyToRef(mat1, mat1);
  93079. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  93080. mat2.multiplyToRef(mat1, mat1);
  93081. }
  93082. else {
  93083. var _tmpVec = BoneIKController._tmpVecs[5];
  93084. _tmpVec.copyFrom(this._bendAxis);
  93085. _tmpVec.x *= -1;
  93086. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  93087. mat2.multiplyToRef(mat1, mat1);
  93088. }
  93089. if (this.poleAngle) {
  93090. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  93091. mat1.multiplyToRef(mat2, mat1);
  93092. }
  93093. if (this._bone1) {
  93094. if (this.slerpAmount < 1) {
  93095. if (!this._slerping) {
  93096. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  93097. }
  93098. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  93099. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  93100. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  93101. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  93102. this._slerping = true;
  93103. }
  93104. else {
  93105. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  93106. this._bone1Mat.copyFrom(mat1);
  93107. this._slerping = false;
  93108. }
  93109. }
  93110. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  93111. this._bone2Ang = angC;
  93112. };
  93113. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  93114. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  93115. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  93116. return BoneIKController;
  93117. }());
  93118. BABYLON.BoneIKController = BoneIKController;
  93119. })(BABYLON || (BABYLON = {}));
  93120. //# sourceMappingURL=babylon.boneIKController.js.map
  93121. var BABYLON;
  93122. (function (BABYLON) {
  93123. /**
  93124. * Class used to make a bone look toward a point in space
  93125. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#bonelookcontroller
  93126. */
  93127. var BoneLookController = /** @class */ (function () {
  93128. /**
  93129. * Create a BoneLookController
  93130. * @param mesh the mesh that the bone belongs to
  93131. * @param bone the bone that will be looking to the target
  93132. * @param target the target Vector3 to look at
  93133. * @param settings optional settings:
  93134. * * maxYaw: the maximum angle the bone will yaw to
  93135. * * minYaw: the minimum angle the bone will yaw to
  93136. * * maxPitch: the maximum angle the bone will pitch to
  93137. * * minPitch: the minimum angle the bone will yaw to
  93138. * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  93139. * * upAxis: the up axis of the coordinate system
  93140. * * upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  93141. * * yawAxis: set yawAxis if the bone does not yaw on the y axis
  93142. * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  93143. * * adjustYaw: used to make an adjustment to the yaw of the bone
  93144. * * adjustPitch: used to make an adjustment to the pitch of the bone
  93145. * * adjustRoll: used to make an adjustment to the roll of the bone
  93146. **/
  93147. function BoneLookController(mesh, bone, target, options) {
  93148. /**
  93149. * The up axis of the coordinate system that is used when the bone is rotated
  93150. */
  93151. this.upAxis = BABYLON.Vector3.Up();
  93152. /**
  93153. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD
  93154. */
  93155. this.upAxisSpace = BABYLON.Space.LOCAL;
  93156. /**
  93157. * Used to make an adjustment to the yaw of the bone
  93158. */
  93159. this.adjustYaw = 0;
  93160. /**
  93161. * Used to make an adjustment to the pitch of the bone
  93162. */
  93163. this.adjustPitch = 0;
  93164. /**
  93165. * Used to make an adjustment to the roll of the bone
  93166. */
  93167. this.adjustRoll = 0;
  93168. /**
  93169. * 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)
  93170. */
  93171. this.slerpAmount = 1;
  93172. this._boneQuat = BABYLON.Quaternion.Identity();
  93173. this._slerping = false;
  93174. this._firstFrameSkipped = false;
  93175. this._fowardAxis = BABYLON.Vector3.Forward();
  93176. this.mesh = mesh;
  93177. this.bone = bone;
  93178. this.target = target;
  93179. if (options) {
  93180. if (options.adjustYaw) {
  93181. this.adjustYaw = options.adjustYaw;
  93182. }
  93183. if (options.adjustPitch) {
  93184. this.adjustPitch = options.adjustPitch;
  93185. }
  93186. if (options.adjustRoll) {
  93187. this.adjustRoll = options.adjustRoll;
  93188. }
  93189. if (options.maxYaw != null) {
  93190. this.maxYaw = options.maxYaw;
  93191. }
  93192. else {
  93193. this.maxYaw = Math.PI;
  93194. }
  93195. if (options.minYaw != null) {
  93196. this.minYaw = options.minYaw;
  93197. }
  93198. else {
  93199. this.minYaw = -Math.PI;
  93200. }
  93201. if (options.maxPitch != null) {
  93202. this.maxPitch = options.maxPitch;
  93203. }
  93204. else {
  93205. this.maxPitch = Math.PI;
  93206. }
  93207. if (options.minPitch != null) {
  93208. this.minPitch = options.minPitch;
  93209. }
  93210. else {
  93211. this.minPitch = -Math.PI;
  93212. }
  93213. if (options.slerpAmount != null) {
  93214. this.slerpAmount = options.slerpAmount;
  93215. }
  93216. if (options.upAxis != null) {
  93217. this.upAxis = options.upAxis;
  93218. }
  93219. if (options.upAxisSpace != null) {
  93220. this.upAxisSpace = options.upAxisSpace;
  93221. }
  93222. if (options.yawAxis != null || options.pitchAxis != null) {
  93223. var newYawAxis = BABYLON.Axis.Y;
  93224. var newPitchAxis = BABYLON.Axis.X;
  93225. if (options.yawAxis != null) {
  93226. newYawAxis = options.yawAxis.clone();
  93227. newYawAxis.normalize();
  93228. }
  93229. if (options.pitchAxis != null) {
  93230. newPitchAxis = options.pitchAxis.clone();
  93231. newPitchAxis.normalize();
  93232. }
  93233. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  93234. this._transformYawPitch = BABYLON.Matrix.Identity();
  93235. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  93236. this._transformYawPitchInv = this._transformYawPitch.clone();
  93237. this._transformYawPitch.invert();
  93238. }
  93239. }
  93240. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  93241. this.upAxisSpace = BABYLON.Space.LOCAL;
  93242. }
  93243. }
  93244. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  93245. /**
  93246. * Gets or sets the minimum yaw angle that the bone can look to
  93247. */
  93248. get: function () {
  93249. return this._minYaw;
  93250. },
  93251. set: function (value) {
  93252. this._minYaw = value;
  93253. this._minYawSin = Math.sin(value);
  93254. this._minYawCos = Math.cos(value);
  93255. if (this._maxYaw != null) {
  93256. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  93257. this._yawRange = this._maxYaw - this._minYaw;
  93258. }
  93259. },
  93260. enumerable: true,
  93261. configurable: true
  93262. });
  93263. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  93264. /**
  93265. * Gets or sets the maximum yaw angle that the bone can look to
  93266. */
  93267. get: function () {
  93268. return this._maxYaw;
  93269. },
  93270. set: function (value) {
  93271. this._maxYaw = value;
  93272. this._maxYawSin = Math.sin(value);
  93273. this._maxYawCos = Math.cos(value);
  93274. if (this._minYaw != null) {
  93275. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  93276. this._yawRange = this._maxYaw - this._minYaw;
  93277. }
  93278. },
  93279. enumerable: true,
  93280. configurable: true
  93281. });
  93282. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  93283. /**
  93284. * Gets or sets the minimum pitch angle that the bone can look to
  93285. */
  93286. get: function () {
  93287. return this._minPitch;
  93288. },
  93289. set: function (value) {
  93290. this._minPitch = value;
  93291. this._minPitchTan = Math.tan(value);
  93292. },
  93293. enumerable: true,
  93294. configurable: true
  93295. });
  93296. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  93297. /**
  93298. * Gets or sets the maximum pitch angle that the bone can look to
  93299. */
  93300. get: function () {
  93301. return this._maxPitch;
  93302. },
  93303. set: function (value) {
  93304. this._maxPitch = value;
  93305. this._maxPitchTan = Math.tan(value);
  93306. },
  93307. enumerable: true,
  93308. configurable: true
  93309. });
  93310. /**
  93311. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender())
  93312. */
  93313. BoneLookController.prototype.update = function () {
  93314. //skip the first frame when slerping so that the mesh rotation is correct
  93315. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  93316. this._firstFrameSkipped = true;
  93317. return;
  93318. }
  93319. var bone = this.bone;
  93320. var bonePos = BoneLookController._tmpVecs[0];
  93321. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  93322. var target = this.target;
  93323. var _tmpMat1 = BoneLookController._tmpMats[0];
  93324. var _tmpMat2 = BoneLookController._tmpMats[1];
  93325. var mesh = this.mesh;
  93326. var parentBone = bone.getParent();
  93327. var upAxis = BoneLookController._tmpVecs[1];
  93328. upAxis.copyFrom(this.upAxis);
  93329. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  93330. if (this._transformYawPitch) {
  93331. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  93332. }
  93333. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  93334. }
  93335. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  93336. mesh.getDirectionToRef(upAxis, upAxis);
  93337. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  93338. upAxis.normalize();
  93339. }
  93340. }
  93341. var checkYaw = false;
  93342. var checkPitch = false;
  93343. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  93344. checkYaw = true;
  93345. }
  93346. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  93347. checkPitch = true;
  93348. }
  93349. if (checkYaw || checkPitch) {
  93350. var spaceMat = BoneLookController._tmpMats[2];
  93351. var spaceMatInv = BoneLookController._tmpMats[3];
  93352. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  93353. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  93354. }
  93355. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  93356. spaceMat.copyFrom(mesh.getWorldMatrix());
  93357. }
  93358. else {
  93359. var forwardAxis = BoneLookController._tmpVecs[2];
  93360. forwardAxis.copyFrom(this._fowardAxis);
  93361. if (this._transformYawPitch) {
  93362. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  93363. }
  93364. if (parentBone) {
  93365. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  93366. }
  93367. else {
  93368. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  93369. }
  93370. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  93371. rightAxis.normalize();
  93372. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  93373. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  93374. }
  93375. spaceMat.invertToRef(spaceMatInv);
  93376. var xzlen = null;
  93377. if (checkPitch) {
  93378. var localTarget = BoneLookController._tmpVecs[3];
  93379. target.subtractToRef(bonePos, localTarget);
  93380. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  93381. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  93382. var pitch = Math.atan2(localTarget.y, xzlen);
  93383. var newPitch = pitch;
  93384. if (pitch > this._maxPitch) {
  93385. localTarget.y = this._maxPitchTan * xzlen;
  93386. newPitch = this._maxPitch;
  93387. }
  93388. else if (pitch < this._minPitch) {
  93389. localTarget.y = this._minPitchTan * xzlen;
  93390. newPitch = this._minPitch;
  93391. }
  93392. if (pitch != newPitch) {
  93393. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  93394. localTarget.addInPlace(bonePos);
  93395. target = localTarget;
  93396. }
  93397. }
  93398. if (checkYaw) {
  93399. var localTarget = BoneLookController._tmpVecs[4];
  93400. target.subtractToRef(bonePos, localTarget);
  93401. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  93402. var yaw = Math.atan2(localTarget.x, localTarget.z);
  93403. var newYaw = yaw;
  93404. if (yaw > this._maxYaw || yaw < this._minYaw) {
  93405. if (xzlen == null) {
  93406. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  93407. }
  93408. if (this._yawRange > Math.PI) {
  93409. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  93410. localTarget.z = this._maxYawCos * xzlen;
  93411. localTarget.x = this._maxYawSin * xzlen;
  93412. newYaw = this._maxYaw;
  93413. }
  93414. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  93415. localTarget.z = this._minYawCos * xzlen;
  93416. localTarget.x = this._minYawSin * xzlen;
  93417. newYaw = this._minYaw;
  93418. }
  93419. }
  93420. else {
  93421. if (yaw > this._maxYaw) {
  93422. localTarget.z = this._maxYawCos * xzlen;
  93423. localTarget.x = this._maxYawSin * xzlen;
  93424. newYaw = this._maxYaw;
  93425. }
  93426. else if (yaw < this._minYaw) {
  93427. localTarget.z = this._minYawCos * xzlen;
  93428. localTarget.x = this._minYawSin * xzlen;
  93429. newYaw = this._minYaw;
  93430. }
  93431. }
  93432. }
  93433. if (this._slerping && this._yawRange > Math.PI) {
  93434. //are we going to be crossing into the min/max region?
  93435. var boneFwd = BoneLookController._tmpVecs[8];
  93436. boneFwd.copyFrom(BABYLON.Axis.Z);
  93437. if (this._transformYawPitch) {
  93438. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  93439. }
  93440. var boneRotMat = BoneLookController._tmpMats[4];
  93441. this._boneQuat.toRotationMatrix(boneRotMat);
  93442. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  93443. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  93444. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  93445. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  93446. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  93447. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  93448. if (angBtwTar > angBtwMidYaw) {
  93449. if (xzlen == null) {
  93450. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  93451. }
  93452. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  93453. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  93454. if (angBtwMin < angBtwMax) {
  93455. newYaw = boneYaw + Math.PI * .75;
  93456. localTarget.z = Math.cos(newYaw) * xzlen;
  93457. localTarget.x = Math.sin(newYaw) * xzlen;
  93458. }
  93459. else {
  93460. newYaw = boneYaw - Math.PI * .75;
  93461. localTarget.z = Math.cos(newYaw) * xzlen;
  93462. localTarget.x = Math.sin(newYaw) * xzlen;
  93463. }
  93464. }
  93465. }
  93466. if (yaw != newYaw) {
  93467. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  93468. localTarget.addInPlace(bonePos);
  93469. target = localTarget;
  93470. }
  93471. }
  93472. }
  93473. var zaxis = BoneLookController._tmpVecs[5];
  93474. var xaxis = BoneLookController._tmpVecs[6];
  93475. var yaxis = BoneLookController._tmpVecs[7];
  93476. var _tmpQuat = BoneLookController._tmpQuat;
  93477. target.subtractToRef(bonePos, zaxis);
  93478. zaxis.normalize();
  93479. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  93480. xaxis.normalize();
  93481. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  93482. yaxis.normalize();
  93483. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  93484. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  93485. return;
  93486. }
  93487. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  93488. return;
  93489. }
  93490. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  93491. return;
  93492. }
  93493. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  93494. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  93495. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  93496. }
  93497. if (this.slerpAmount < 1) {
  93498. if (!this._slerping) {
  93499. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  93500. }
  93501. if (this._transformYawPitch) {
  93502. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  93503. }
  93504. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  93505. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  93506. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  93507. this._slerping = true;
  93508. }
  93509. else {
  93510. if (this._transformYawPitch) {
  93511. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  93512. }
  93513. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  93514. this._slerping = false;
  93515. }
  93516. };
  93517. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  93518. var angDiff = ang2 - ang1;
  93519. angDiff %= Math.PI * 2;
  93520. if (angDiff > Math.PI) {
  93521. angDiff -= Math.PI * 2;
  93522. }
  93523. else if (angDiff < -Math.PI) {
  93524. angDiff += Math.PI * 2;
  93525. }
  93526. return angDiff;
  93527. };
  93528. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  93529. ang1 %= (2 * Math.PI);
  93530. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  93531. ang2 %= (2 * Math.PI);
  93532. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  93533. var ab = 0;
  93534. if (ang1 < ang2) {
  93535. ab = ang2 - ang1;
  93536. }
  93537. else {
  93538. ab = ang1 - ang2;
  93539. }
  93540. if (ab > Math.PI) {
  93541. ab = Math.PI * 2 - ab;
  93542. }
  93543. return ab;
  93544. };
  93545. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  93546. ang %= (2 * Math.PI);
  93547. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  93548. ang1 %= (2 * Math.PI);
  93549. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  93550. ang2 %= (2 * Math.PI);
  93551. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  93552. if (ang1 < ang2) {
  93553. if (ang > ang1 && ang < ang2) {
  93554. return true;
  93555. }
  93556. }
  93557. else {
  93558. if (ang > ang2 && ang < ang1) {
  93559. return true;
  93560. }
  93561. }
  93562. return false;
  93563. };
  93564. BoneLookController._tmpVecs = BABYLON.Tools.BuildArray(10, BABYLON.Vector3.Zero);
  93565. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  93566. BoneLookController._tmpMats = BABYLON.Tools.BuildArray(5, BABYLON.Matrix.Identity);
  93567. return BoneLookController;
  93568. }());
  93569. BABYLON.BoneLookController = BoneLookController;
  93570. })(BABYLON || (BABYLON = {}));
  93571. //# sourceMappingURL=babylon.boneLookController.js.map
  93572. var BABYLON;
  93573. (function (BABYLON) {
  93574. /**
  93575. * Class used to handle skinning animations
  93576. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  93577. */
  93578. var Skeleton = /** @class */ (function () {
  93579. /**
  93580. * Creates a new skeleton
  93581. * @param name defines the skeleton name
  93582. * @param id defines the skeleton Id
  93583. * @param scene defines the hosting scene
  93584. */
  93585. function Skeleton(
  93586. /** defines the skeleton name */
  93587. name,
  93588. /** defines the skeleton Id */
  93589. id, scene) {
  93590. this.name = name;
  93591. this.id = id;
  93592. /**
  93593. * Gets the list of child bones
  93594. */
  93595. this.bones = new Array();
  93596. /**
  93597. * Gets a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value)
  93598. */
  93599. this.needInitialSkinMatrix = false;
  93600. this._isDirty = true;
  93601. this._meshesWithPoseMatrix = new Array();
  93602. this._identity = BABYLON.Matrix.Identity();
  93603. this._ranges = {};
  93604. this._lastAbsoluteTransformsUpdateId = -1;
  93605. this._canUseTextureForBones = false;
  93606. /**
  93607. * Specifies if the skeleton should be serialized
  93608. */
  93609. this.doNotSerialize = false;
  93610. /**
  93611. * Gets or sets a boolean indicating that bone matrices should be stored as a texture instead of using shader uniforms (default is true).
  93612. * Please note that this option is not available when needInitialSkinMatrix === true or if the hardware does not support it
  93613. */
  93614. this.useTextureToStoreBoneMatrices = true;
  93615. this._animationPropertiesOverride = null;
  93616. // Events
  93617. /**
  93618. * An observable triggered before computing the skeleton's matrices
  93619. */
  93620. this.onBeforeComputeObservable = new BABYLON.Observable();
  93621. this.bones = [];
  93622. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  93623. this._scene.skeletons.push(this);
  93624. //make sure it will recalculate the matrix next time prepare is called.
  93625. this._isDirty = true;
  93626. var engineCaps = this._scene.getEngine().getCaps();
  93627. this._canUseTextureForBones = engineCaps.textureFloat && engineCaps.maxVertexTextureImageUnits > 0;
  93628. }
  93629. Object.defineProperty(Skeleton.prototype, "animationPropertiesOverride", {
  93630. /**
  93631. * Gets or sets the animation properties override
  93632. */
  93633. get: function () {
  93634. if (!this._animationPropertiesOverride) {
  93635. return this._scene.animationPropertiesOverride;
  93636. }
  93637. return this._animationPropertiesOverride;
  93638. },
  93639. set: function (value) {
  93640. this._animationPropertiesOverride = value;
  93641. },
  93642. enumerable: true,
  93643. configurable: true
  93644. });
  93645. Object.defineProperty(Skeleton.prototype, "isUsingTextureForMatrices", {
  93646. /**
  93647. * Gets a boolean indicating that the skeleton effectively stores matrices into a texture
  93648. */
  93649. get: function () {
  93650. return this.useTextureToStoreBoneMatrices && this._canUseTextureForBones && !this.needInitialSkinMatrix;
  93651. },
  93652. enumerable: true,
  93653. configurable: true
  93654. });
  93655. // Members
  93656. /**
  93657. * Gets the list of transform matrices to send to shaders (one matrix per bone)
  93658. * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)
  93659. * @returns a Float32Array containing matrices data
  93660. */
  93661. Skeleton.prototype.getTransformMatrices = function (mesh) {
  93662. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  93663. return mesh._bonesTransformMatrices;
  93664. }
  93665. if (!this._transformMatrices) {
  93666. this.prepare();
  93667. }
  93668. return this._transformMatrices;
  93669. };
  93670. /**
  93671. * Gets the list of transform matrices to send to shaders inside a texture (one matrix per bone)
  93672. * @returns a raw texture containing the data
  93673. */
  93674. Skeleton.prototype.getTransformMatrixTexture = function () {
  93675. return this._transformMatrixTexture;
  93676. };
  93677. /**
  93678. * Gets the current hosting scene
  93679. * @returns a scene object
  93680. */
  93681. Skeleton.prototype.getScene = function () {
  93682. return this._scene;
  93683. };
  93684. // Methods
  93685. /**
  93686. * Gets a string representing the current skeleton data
  93687. * @param fullDetails defines a boolean indicating if we want a verbose version
  93688. * @returns a string representing the current skeleton data
  93689. */
  93690. Skeleton.prototype.toString = function (fullDetails) {
  93691. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  93692. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  93693. if (fullDetails) {
  93694. ret += ", Ranges: {";
  93695. var first = true;
  93696. for (var name_1 in this._ranges) {
  93697. if (first) {
  93698. ret += ", ";
  93699. first = false;
  93700. }
  93701. ret += name_1;
  93702. }
  93703. ret += "}";
  93704. }
  93705. return ret;
  93706. };
  93707. /**
  93708. * Get bone's index searching by name
  93709. * @param name defines bone's name to search for
  93710. * @return the indice of the bone. Returns -1 if not found
  93711. */
  93712. Skeleton.prototype.getBoneIndexByName = function (name) {
  93713. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  93714. if (this.bones[boneIndex].name === name) {
  93715. return boneIndex;
  93716. }
  93717. }
  93718. return -1;
  93719. };
  93720. /**
  93721. * Creater a new animation range
  93722. * @param name defines the name of the range
  93723. * @param from defines the start key
  93724. * @param to defines the end key
  93725. */
  93726. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  93727. // check name not already in use
  93728. if (!this._ranges[name]) {
  93729. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  93730. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  93731. if (this.bones[i].animations[0]) {
  93732. this.bones[i].animations[0].createRange(name, from, to);
  93733. }
  93734. }
  93735. }
  93736. };
  93737. /**
  93738. * Delete a specific animation range
  93739. * @param name defines the name of the range
  93740. * @param deleteFrames defines if frames must be removed as well
  93741. */
  93742. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  93743. if (deleteFrames === void 0) { deleteFrames = true; }
  93744. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  93745. if (this.bones[i].animations[0]) {
  93746. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  93747. }
  93748. }
  93749. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  93750. };
  93751. /**
  93752. * Gets a specific animation range
  93753. * @param name defines the name of the range to look for
  93754. * @returns the requested animation range or null if not found
  93755. */
  93756. Skeleton.prototype.getAnimationRange = function (name) {
  93757. return this._ranges[name];
  93758. };
  93759. /**
  93760. * Gets the list of all animation ranges defined on this skeleton
  93761. * @returns an array
  93762. */
  93763. Skeleton.prototype.getAnimationRanges = function () {
  93764. var animationRanges = [];
  93765. var name;
  93766. var i = 0;
  93767. for (name in this._ranges) {
  93768. animationRanges[i] = this._ranges[name];
  93769. i++;
  93770. }
  93771. return animationRanges;
  93772. };
  93773. /**
  93774. * Copy animation range from a source skeleton.
  93775. * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  93776. * @param source defines the source skeleton
  93777. * @param name defines the name of the range to copy
  93778. * @param rescaleAsRequired defines if rescaling must be applied if required
  93779. * @returns true if operation was successful
  93780. */
  93781. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  93782. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  93783. if (this._ranges[name] || !source.getAnimationRange(name)) {
  93784. return false;
  93785. }
  93786. var ret = true;
  93787. var frameOffset = this._getHighestAnimationFrame() + 1;
  93788. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  93789. var boneDict = {};
  93790. var sourceBones = source.bones;
  93791. var nBones;
  93792. var i;
  93793. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  93794. boneDict[sourceBones[i].name] = sourceBones[i];
  93795. }
  93796. if (this.bones.length !== sourceBones.length) {
  93797. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  93798. ret = false;
  93799. }
  93800. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  93801. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  93802. var boneName = this.bones[i].name;
  93803. var sourceBone = boneDict[boneName];
  93804. if (sourceBone) {
  93805. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  93806. }
  93807. else {
  93808. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  93809. ret = false;
  93810. }
  93811. }
  93812. // do not call createAnimationRange(), since it also is done to bones, which was already done
  93813. var range = source.getAnimationRange(name);
  93814. if (range) {
  93815. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  93816. }
  93817. return ret;
  93818. };
  93819. /**
  93820. * Forces the skeleton to go to rest pose
  93821. */
  93822. Skeleton.prototype.returnToRest = function () {
  93823. for (var index = 0; index < this.bones.length; index++) {
  93824. this.bones[index].returnToRest();
  93825. }
  93826. };
  93827. Skeleton.prototype._getHighestAnimationFrame = function () {
  93828. var ret = 0;
  93829. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  93830. if (this.bones[i].animations[0]) {
  93831. var highest = this.bones[i].animations[0].getHighestFrame();
  93832. if (ret < highest) {
  93833. ret = highest;
  93834. }
  93835. }
  93836. }
  93837. return ret;
  93838. };
  93839. /**
  93840. * Begin a specific animation range
  93841. * @param name defines the name of the range to start
  93842. * @param loop defines if looping must be turned on (false by default)
  93843. * @param speedRatio defines the speed ratio to apply (1 by default)
  93844. * @param onAnimationEnd defines a callback which will be called when animation will end
  93845. * @returns a new animatable
  93846. */
  93847. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  93848. var range = this.getAnimationRange(name);
  93849. if (!range) {
  93850. return null;
  93851. }
  93852. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  93853. };
  93854. /** @hidden */
  93855. Skeleton.prototype._markAsDirty = function () {
  93856. this._isDirty = true;
  93857. };
  93858. /** @hidden */
  93859. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  93860. this._meshesWithPoseMatrix.push(mesh);
  93861. };
  93862. /** @hidden */
  93863. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  93864. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  93865. if (index > -1) {
  93866. this._meshesWithPoseMatrix.splice(index, 1);
  93867. }
  93868. };
  93869. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  93870. this.onBeforeComputeObservable.notifyObservers(this);
  93871. for (var index = 0; index < this.bones.length; index++) {
  93872. var bone = this.bones[index];
  93873. var parentBone = bone.getParent();
  93874. if (parentBone) {
  93875. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  93876. }
  93877. else {
  93878. if (initialSkinMatrix) {
  93879. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  93880. }
  93881. else {
  93882. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  93883. }
  93884. }
  93885. if (bone._index !== -1) {
  93886. var mappedIndex = bone._index === null ? index : bone._index;
  93887. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  93888. }
  93889. }
  93890. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  93891. };
  93892. /**
  93893. * Build all resources required to render a skeleton
  93894. */
  93895. Skeleton.prototype.prepare = function () {
  93896. if (!this._isDirty) {
  93897. return;
  93898. }
  93899. if (this.needInitialSkinMatrix) {
  93900. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  93901. var mesh = this._meshesWithPoseMatrix[index];
  93902. var poseMatrix = mesh.getPoseMatrix();
  93903. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  93904. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  93905. }
  93906. if (this._synchronizedWithMesh !== mesh) {
  93907. this._synchronizedWithMesh = mesh;
  93908. // Prepare bones
  93909. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  93910. var bone = this.bones[boneIndex];
  93911. if (!bone.getParent()) {
  93912. var matrix = bone.getBaseMatrix();
  93913. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  93914. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  93915. }
  93916. }
  93917. }
  93918. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  93919. }
  93920. }
  93921. else {
  93922. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  93923. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  93924. if (this.isUsingTextureForMatrices) {
  93925. if (this._transformMatrixTexture) {
  93926. this._transformMatrixTexture.dispose();
  93927. }
  93928. this._transformMatrixTexture = BABYLON.RawTexture.CreateRGBATexture(this._transformMatrices, (this.bones.length + 1) * 4, 1, this._scene, false, false, BABYLON.Engine.TEXTURE_NEAREST_SAMPLINGMODE, BABYLON.Engine.TEXTURETYPE_FLOAT);
  93929. }
  93930. }
  93931. this._computeTransformMatrices(this._transformMatrices, null);
  93932. if (this.isUsingTextureForMatrices && this._transformMatrixTexture) {
  93933. this._transformMatrixTexture.update(this._transformMatrices);
  93934. }
  93935. }
  93936. this._isDirty = false;
  93937. this._scene._activeBones.addCount(this.bones.length, false);
  93938. };
  93939. /**
  93940. * Gets the list of animatables currently running for this skeleton
  93941. * @returns an array of animatables
  93942. */
  93943. Skeleton.prototype.getAnimatables = function () {
  93944. if (!this._animatables || this._animatables.length !== this.bones.length) {
  93945. this._animatables = [];
  93946. for (var index = 0; index < this.bones.length; index++) {
  93947. this._animatables.push(this.bones[index]);
  93948. }
  93949. }
  93950. return this._animatables;
  93951. };
  93952. /**
  93953. * Clone the current skeleton
  93954. * @param name defines the name of the new skeleton
  93955. * @param id defines the id of the enw skeleton
  93956. * @returns the new skeleton
  93957. */
  93958. Skeleton.prototype.clone = function (name, id) {
  93959. var result = new Skeleton(name, id || name, this._scene);
  93960. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  93961. for (var index = 0; index < this.bones.length; index++) {
  93962. var source = this.bones[index];
  93963. var parentBone = null;
  93964. var parent_1 = source.getParent();
  93965. if (parent_1) {
  93966. var parentIndex = this.bones.indexOf(parent_1);
  93967. parentBone = result.bones[parentIndex];
  93968. }
  93969. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  93970. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  93971. }
  93972. if (this._ranges) {
  93973. result._ranges = {};
  93974. for (var rangeName in this._ranges) {
  93975. var range = this._ranges[rangeName];
  93976. if (range) {
  93977. result._ranges[rangeName] = range.clone();
  93978. }
  93979. }
  93980. }
  93981. this._isDirty = true;
  93982. return result;
  93983. };
  93984. /**
  93985. * Enable animation blending for this skeleton
  93986. * @param blendingSpeed defines the blending speed to apply
  93987. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  93988. */
  93989. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  93990. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  93991. this.bones.forEach(function (bone) {
  93992. bone.animations.forEach(function (animation) {
  93993. animation.enableBlending = true;
  93994. animation.blendingSpeed = blendingSpeed;
  93995. });
  93996. });
  93997. };
  93998. /**
  93999. * Releases all resources associated with the current skeleton
  94000. */
  94001. Skeleton.prototype.dispose = function () {
  94002. this._meshesWithPoseMatrix = [];
  94003. // Animations
  94004. this.getScene().stopAnimation(this);
  94005. // Remove from scene
  94006. this.getScene().removeSkeleton(this);
  94007. if (this._transformMatrixTexture) {
  94008. this._transformMatrixTexture.dispose();
  94009. this._transformMatrixTexture = null;
  94010. }
  94011. };
  94012. /**
  94013. * Serialize the skeleton in a JSON object
  94014. * @returns a JSON object
  94015. */
  94016. Skeleton.prototype.serialize = function () {
  94017. var serializationObject = {};
  94018. serializationObject.name = this.name;
  94019. serializationObject.id = this.id;
  94020. if (this.dimensionsAtRest) {
  94021. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  94022. }
  94023. serializationObject.bones = [];
  94024. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  94025. for (var index = 0; index < this.bones.length; index++) {
  94026. var bone = this.bones[index];
  94027. var parent_2 = bone.getParent();
  94028. var serializedBone = {
  94029. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  94030. name: bone.name,
  94031. matrix: bone.getBaseMatrix().toArray(),
  94032. rest: bone.getRestPose().toArray()
  94033. };
  94034. serializationObject.bones.push(serializedBone);
  94035. if (bone.length) {
  94036. serializedBone.length = bone.length;
  94037. }
  94038. if (bone.metadata) {
  94039. serializedBone.metadata = bone.metadata;
  94040. }
  94041. if (bone.animations && bone.animations.length > 0) {
  94042. serializedBone.animation = bone.animations[0].serialize();
  94043. }
  94044. serializationObject.ranges = [];
  94045. for (var name in this._ranges) {
  94046. var source = this._ranges[name];
  94047. if (!source) {
  94048. continue;
  94049. }
  94050. var range = {};
  94051. range.name = name;
  94052. range.from = source.from;
  94053. range.to = source.to;
  94054. serializationObject.ranges.push(range);
  94055. }
  94056. }
  94057. return serializationObject;
  94058. };
  94059. /**
  94060. * Creates a new skeleton from serialized data
  94061. * @param parsedSkeleton defines the serialized data
  94062. * @param scene defines the hosting scene
  94063. * @returns a new skeleton
  94064. */
  94065. Skeleton.Parse = function (parsedSkeleton, scene) {
  94066. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  94067. if (parsedSkeleton.dimensionsAtRest) {
  94068. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  94069. }
  94070. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  94071. var index;
  94072. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  94073. var parsedBone = parsedSkeleton.bones[index];
  94074. var parentBone = null;
  94075. if (parsedBone.parentBoneIndex > -1) {
  94076. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  94077. }
  94078. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  94079. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  94080. if (parsedBone.id !== undefined && parsedBone.id !== null) {
  94081. bone.id = parsedBone.id;
  94082. }
  94083. if (parsedBone.length) {
  94084. bone.length = parsedBone.length;
  94085. }
  94086. if (parsedBone.metadata) {
  94087. bone.metadata = parsedBone.metadata;
  94088. }
  94089. if (parsedBone.animation) {
  94090. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  94091. }
  94092. }
  94093. // placed after bones, so createAnimationRange can cascade down
  94094. if (parsedSkeleton.ranges) {
  94095. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  94096. var data = parsedSkeleton.ranges[index];
  94097. skeleton.createAnimationRange(data.name, data.from, data.to);
  94098. }
  94099. }
  94100. return skeleton;
  94101. };
  94102. /**
  94103. * Compute all node absolute transforms
  94104. * @param forceUpdate defines if computation must be done even if cache is up to date
  94105. */
  94106. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  94107. if (forceUpdate === void 0) { forceUpdate = false; }
  94108. var renderId = this._scene.getRenderId();
  94109. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  94110. this.bones[0].computeAbsoluteTransforms();
  94111. this._lastAbsoluteTransformsUpdateId = renderId;
  94112. }
  94113. };
  94114. /**
  94115. * Gets the root pose matrix
  94116. * @returns a matrix
  94117. */
  94118. Skeleton.prototype.getPoseMatrix = function () {
  94119. var poseMatrix = null;
  94120. if (this._meshesWithPoseMatrix.length > 0) {
  94121. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  94122. }
  94123. return poseMatrix;
  94124. };
  94125. /**
  94126. * Sorts bones per internal index
  94127. */
  94128. Skeleton.prototype.sortBones = function () {
  94129. var bones = new Array();
  94130. var visited = new Array(this.bones.length);
  94131. for (var index = 0; index < this.bones.length; index++) {
  94132. this._sortBones(index, bones, visited);
  94133. }
  94134. this.bones = bones;
  94135. };
  94136. Skeleton.prototype._sortBones = function (index, bones, visited) {
  94137. if (visited[index]) {
  94138. return;
  94139. }
  94140. visited[index] = true;
  94141. var bone = this.bones[index];
  94142. if (bone._index === undefined) {
  94143. bone._index = index;
  94144. }
  94145. var parentBone = bone.getParent();
  94146. if (parentBone) {
  94147. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  94148. }
  94149. bones.push(bone);
  94150. };
  94151. return Skeleton;
  94152. }());
  94153. BABYLON.Skeleton = Skeleton;
  94154. })(BABYLON || (BABYLON = {}));
  94155. //# sourceMappingURL=babylon.skeleton.js.map
  94156. var BABYLON;
  94157. (function (BABYLON) {
  94158. /**
  94159. * This groups tools to convert HDR texture to native colors array.
  94160. */
  94161. var HDRTools = /** @class */ (function () {
  94162. function HDRTools() {
  94163. }
  94164. HDRTools.Ldexp = function (mantissa, exponent) {
  94165. if (exponent > 1023) {
  94166. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  94167. }
  94168. if (exponent < -1074) {
  94169. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  94170. }
  94171. return mantissa * Math.pow(2, exponent);
  94172. };
  94173. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  94174. if (exponent > 0) { /*nonzero pixel*/
  94175. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  94176. float32array[index + 0] = red * exponent;
  94177. float32array[index + 1] = green * exponent;
  94178. float32array[index + 2] = blue * exponent;
  94179. }
  94180. else {
  94181. float32array[index + 0] = 0;
  94182. float32array[index + 1] = 0;
  94183. float32array[index + 2] = 0;
  94184. }
  94185. };
  94186. HDRTools.readStringLine = function (uint8array, startIndex) {
  94187. var line = "";
  94188. var character = "";
  94189. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  94190. character = String.fromCharCode(uint8array[i]);
  94191. if (character == "\n") {
  94192. break;
  94193. }
  94194. line += character;
  94195. }
  94196. return line;
  94197. };
  94198. /**
  94199. * Reads header information from an RGBE texture stored in a native array.
  94200. * More information on this format are available here:
  94201. * https://en.wikipedia.org/wiki/RGBE_image_format
  94202. *
  94203. * @param uint8array The binary file stored in native array.
  94204. * @return The header information.
  94205. */
  94206. HDRTools.RGBE_ReadHeader = function (uint8array) {
  94207. var height = 0;
  94208. var width = 0;
  94209. var line = this.readStringLine(uint8array, 0);
  94210. if (line[0] != '#' || line[1] != '?') {
  94211. throw "Bad HDR Format.";
  94212. }
  94213. var endOfHeader = false;
  94214. var findFormat = false;
  94215. var lineIndex = 0;
  94216. do {
  94217. lineIndex += (line.length + 1);
  94218. line = this.readStringLine(uint8array, lineIndex);
  94219. if (line == "FORMAT=32-bit_rle_rgbe") {
  94220. findFormat = true;
  94221. }
  94222. else if (line.length == 0) {
  94223. endOfHeader = true;
  94224. }
  94225. } while (!endOfHeader);
  94226. if (!findFormat) {
  94227. throw "HDR Bad header format, unsupported FORMAT";
  94228. }
  94229. lineIndex += (line.length + 1);
  94230. line = this.readStringLine(uint8array, lineIndex);
  94231. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  94232. var match = sizeRegexp.exec(line);
  94233. // TODO. Support +Y and -X if needed.
  94234. if (!match || match.length < 3) {
  94235. throw "HDR Bad header format, no size";
  94236. }
  94237. width = parseInt(match[2]);
  94238. height = parseInt(match[1]);
  94239. if (width < 8 || width > 0x7fff) {
  94240. throw "HDR Bad header format, unsupported size";
  94241. }
  94242. lineIndex += (line.length + 1);
  94243. return {
  94244. height: height,
  94245. width: width,
  94246. dataPosition: lineIndex
  94247. };
  94248. };
  94249. /**
  94250. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  94251. * This RGBE texture needs to store the information as a panorama.
  94252. *
  94253. * More information on this format are available here:
  94254. * https://en.wikipedia.org/wiki/RGBE_image_format
  94255. *
  94256. * @param buffer The binary file stored in an array buffer.
  94257. * @param size The expected size of the extracted cubemap.
  94258. * @return The Cube Map information.
  94259. */
  94260. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  94261. var uint8array = new Uint8Array(buffer);
  94262. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  94263. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  94264. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  94265. return cubeMapData;
  94266. };
  94267. /**
  94268. * Returns the pixels data extracted from an RGBE texture.
  94269. * This pixels will be stored left to right up to down in the R G B order in one array.
  94270. *
  94271. * More information on this format are available here:
  94272. * https://en.wikipedia.org/wiki/RGBE_image_format
  94273. *
  94274. * @param uint8array The binary file stored in an array buffer.
  94275. * @param hdrInfo The header information of the file.
  94276. * @return The pixels data in RGB right to left up to down order.
  94277. */
  94278. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  94279. // Keep for multi format supports.
  94280. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  94281. };
  94282. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  94283. var num_scanlines = hdrInfo.height;
  94284. var scanline_width = hdrInfo.width;
  94285. var a, b, c, d, count;
  94286. var dataIndex = hdrInfo.dataPosition;
  94287. var index = 0, endIndex = 0, i = 0;
  94288. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  94289. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  94290. // 3 channels of 4 bytes per pixel in float.
  94291. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  94292. var resultArray = new Float32Array(resultBuffer);
  94293. // read in each successive scanline
  94294. while (num_scanlines > 0) {
  94295. a = uint8array[dataIndex++];
  94296. b = uint8array[dataIndex++];
  94297. c = uint8array[dataIndex++];
  94298. d = uint8array[dataIndex++];
  94299. if (a != 2 || b != 2 || (c & 0x80)) {
  94300. // this file is not run length encoded
  94301. throw "HDR Bad header format, not RLE";
  94302. }
  94303. if (((c << 8) | d) != scanline_width) {
  94304. throw "HDR Bad header format, wrong scan line width";
  94305. }
  94306. index = 0;
  94307. // read each of the four channels for the scanline into the buffer
  94308. for (i = 0; i < 4; i++) {
  94309. endIndex = (i + 1) * scanline_width;
  94310. while (index < endIndex) {
  94311. a = uint8array[dataIndex++];
  94312. b = uint8array[dataIndex++];
  94313. if (a > 128) {
  94314. // a run of the same value
  94315. count = a - 128;
  94316. if ((count == 0) || (count > endIndex - index)) {
  94317. throw "HDR Bad Format, bad scanline data (run)";
  94318. }
  94319. while (count-- > 0) {
  94320. scanLineArray[index++] = b;
  94321. }
  94322. }
  94323. else {
  94324. // a non-run
  94325. count = a;
  94326. if ((count == 0) || (count > endIndex - index)) {
  94327. throw "HDR Bad Format, bad scanline data (non-run)";
  94328. }
  94329. scanLineArray[index++] = b;
  94330. if (--count > 0) {
  94331. for (var j = 0; j < count; j++) {
  94332. scanLineArray[index++] = uint8array[dataIndex++];
  94333. }
  94334. }
  94335. }
  94336. }
  94337. }
  94338. // now convert data from buffer into floats
  94339. for (i = 0; i < scanline_width; i++) {
  94340. a = scanLineArray[i];
  94341. b = scanLineArray[i + scanline_width];
  94342. c = scanLineArray[i + 2 * scanline_width];
  94343. d = scanLineArray[i + 3 * scanline_width];
  94344. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  94345. }
  94346. num_scanlines--;
  94347. }
  94348. return resultArray;
  94349. };
  94350. return HDRTools;
  94351. }());
  94352. BABYLON.HDRTools = HDRTools;
  94353. })(BABYLON || (BABYLON = {}));
  94354. //# sourceMappingURL=babylon.hdr.js.map
  94355. var BABYLON;
  94356. (function (BABYLON) {
  94357. /**
  94358. * This represents a texture coming from an HDR input.
  94359. *
  94360. * The only supported format is currently panorama picture stored in RGBE format.
  94361. * Example of such files can be found on HDRLib: http://hdrlib.com/
  94362. */
  94363. var HDRCubeTexture = /** @class */ (function (_super) {
  94364. __extends(HDRCubeTexture, _super);
  94365. /**
  94366. * Instantiates an HDRTexture from the following parameters.
  94367. *
  94368. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  94369. * @param scene The scene the texture will be used in
  94370. * @param size The cubemap desired size (the more it increases the longer the generation will be)
  94371. * @param noMipmap Forces to not generate the mipmap if true
  94372. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  94373. * @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)
  94374. * @param reserved Reserved flag for internal use.
  94375. */
  94376. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, gammaSpace, reserved, onLoad, onError) {
  94377. if (noMipmap === void 0) { noMipmap = false; }
  94378. if (generateHarmonics === void 0) { generateHarmonics = true; }
  94379. if (gammaSpace === void 0) { gammaSpace = false; }
  94380. if (reserved === void 0) { reserved = false; }
  94381. if (onLoad === void 0) { onLoad = null; }
  94382. if (onError === void 0) { onError = null; }
  94383. var _this = _super.call(this, scene) || this;
  94384. _this._generateHarmonics = true;
  94385. _this._onLoad = null;
  94386. _this._onError = null;
  94387. /**
  94388. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  94389. */
  94390. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  94391. _this._isBlocking = true;
  94392. _this._rotationY = 0;
  94393. /**
  94394. * Gets or sets the center of the bounding box associated with the cube texture
  94395. * It must define where the camera used to render the texture was set
  94396. */
  94397. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  94398. if (!url) {
  94399. return _this;
  94400. }
  94401. _this.name = url;
  94402. _this.url = url;
  94403. _this.hasAlpha = false;
  94404. _this.isCube = true;
  94405. _this._textureMatrix = BABYLON.Matrix.Identity();
  94406. _this._onLoad = onLoad;
  94407. _this._onError = onError;
  94408. _this.gammaSpace = gammaSpace;
  94409. _this._noMipmap = noMipmap;
  94410. _this._size = size;
  94411. _this._texture = _this._getFromCache(url, _this._noMipmap);
  94412. if (!_this._texture) {
  94413. if (!scene.useDelayedTextureLoading) {
  94414. _this.loadTexture();
  94415. }
  94416. else {
  94417. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  94418. }
  94419. }
  94420. return _this;
  94421. }
  94422. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  94423. /**
  94424. * Gets wether or not the texture is blocking during loading.
  94425. */
  94426. get: function () {
  94427. return this._isBlocking;
  94428. },
  94429. /**
  94430. * Sets wether or not the texture is blocking during loading.
  94431. */
  94432. set: function (value) {
  94433. this._isBlocking = value;
  94434. },
  94435. enumerable: true,
  94436. configurable: true
  94437. });
  94438. Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
  94439. /**
  94440. * Gets texture matrix rotation angle around Y axis radians.
  94441. */
  94442. get: function () {
  94443. return this._rotationY;
  94444. },
  94445. /**
  94446. * Sets texture matrix rotation angle around Y axis in radians.
  94447. */
  94448. set: function (value) {
  94449. this._rotationY = value;
  94450. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  94451. },
  94452. enumerable: true,
  94453. configurable: true
  94454. });
  94455. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  94456. get: function () {
  94457. return this._boundingBoxSize;
  94458. },
  94459. /**
  94460. * Gets or sets the size of the bounding box associated with the cube texture
  94461. * When defined, the cubemap will switch to local mode
  94462. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  94463. * @example https://www.babylonjs-playground.com/#RNASML
  94464. */
  94465. set: function (value) {
  94466. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  94467. return;
  94468. }
  94469. this._boundingBoxSize = value;
  94470. var scene = this.getScene();
  94471. if (scene) {
  94472. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  94473. }
  94474. },
  94475. enumerable: true,
  94476. configurable: true
  94477. });
  94478. /**
  94479. * Occurs when the file is raw .hdr file.
  94480. */
  94481. HDRCubeTexture.prototype.loadTexture = function () {
  94482. var _this = this;
  94483. var callback = function (buffer) {
  94484. _this.lodGenerationOffset = 0.0;
  94485. _this.lodGenerationScale = 0.8;
  94486. var scene = _this.getScene();
  94487. if (!scene) {
  94488. return null;
  94489. }
  94490. // Extract the raw linear data.
  94491. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  94492. // Generate harmonics if needed.
  94493. if (_this._generateHarmonics) {
  94494. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  94495. _this.sphericalPolynomial = sphericalPolynomial;
  94496. }
  94497. var results = [];
  94498. var byteArray = null;
  94499. // Push each faces.
  94500. for (var j = 0; j < 6; j++) {
  94501. // Create uintarray fallback.
  94502. if (!scene.getEngine().getCaps().textureFloat) {
  94503. // 3 channels of 1 bytes per pixel in bytes.
  94504. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  94505. byteArray = new Uint8Array(byteBuffer);
  94506. }
  94507. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  94508. // If special cases.
  94509. if (_this.gammaSpace || byteArray) {
  94510. for (var i = 0; i < _this._size * _this._size; i++) {
  94511. // Put in gamma space if requested.
  94512. if (_this.gammaSpace) {
  94513. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  94514. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  94515. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  94516. }
  94517. // Convert to int texture for fallback.
  94518. if (byteArray) {
  94519. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  94520. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  94521. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  94522. // May use luminance instead if the result is not accurate.
  94523. var max = Math.max(Math.max(r, g), b);
  94524. if (max > 255) {
  94525. var scale = 255 / max;
  94526. r *= scale;
  94527. g *= scale;
  94528. b *= scale;
  94529. }
  94530. byteArray[(i * 3) + 0] = r;
  94531. byteArray[(i * 3) + 1] = g;
  94532. byteArray[(i * 3) + 2] = b;
  94533. }
  94534. }
  94535. }
  94536. if (byteArray) {
  94537. results.push(byteArray);
  94538. }
  94539. else {
  94540. results.push(dataFace);
  94541. }
  94542. }
  94543. return results;
  94544. };
  94545. var scene = this.getScene();
  94546. if (scene) {
  94547. 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);
  94548. }
  94549. };
  94550. HDRCubeTexture.prototype.clone = function () {
  94551. var scene = this.getScene();
  94552. if (!scene) {
  94553. return this;
  94554. }
  94555. var newTexture = new HDRCubeTexture(this.url, scene, this._size, this._noMipmap, this._generateHarmonics, this.gammaSpace);
  94556. // Base texture
  94557. newTexture.level = this.level;
  94558. newTexture.wrapU = this.wrapU;
  94559. newTexture.wrapV = this.wrapV;
  94560. newTexture.coordinatesIndex = this.coordinatesIndex;
  94561. newTexture.coordinatesMode = this.coordinatesMode;
  94562. return newTexture;
  94563. };
  94564. // Methods
  94565. HDRCubeTexture.prototype.delayLoad = function () {
  94566. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  94567. return;
  94568. }
  94569. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  94570. this._texture = this._getFromCache(this.url, this._noMipmap);
  94571. if (!this._texture) {
  94572. this.loadTexture();
  94573. }
  94574. };
  94575. /**
  94576. * Get the texture reflection matrix used to rotate/transform the reflection.
  94577. * @returns the reflection matrix
  94578. */
  94579. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  94580. return this._textureMatrix;
  94581. };
  94582. /**
  94583. * Set the texture reflection matrix used to rotate/transform the reflection.
  94584. * @param value Define the reflection matrix to set
  94585. */
  94586. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  94587. this._textureMatrix = value;
  94588. };
  94589. /**
  94590. * Parses a JSON representation of an HDR Texture in order to create the texture
  94591. * @param parsedTexture Define the JSON representation
  94592. * @param scene Define the scene the texture should be created in
  94593. * @param rootUrl Define the root url in case we need to load relative dependencies
  94594. * @returns the newly created texture after parsing
  94595. */
  94596. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  94597. var texture = null;
  94598. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  94599. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace);
  94600. texture.name = parsedTexture.name;
  94601. texture.hasAlpha = parsedTexture.hasAlpha;
  94602. texture.level = parsedTexture.level;
  94603. texture.coordinatesMode = parsedTexture.coordinatesMode;
  94604. texture.isBlocking = parsedTexture.isBlocking;
  94605. }
  94606. if (texture) {
  94607. if (parsedTexture.boundingBoxPosition) {
  94608. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  94609. }
  94610. if (parsedTexture.boundingBoxSize) {
  94611. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  94612. }
  94613. if (parsedTexture.rotationY) {
  94614. texture.rotationY = parsedTexture.rotationY;
  94615. }
  94616. }
  94617. return texture;
  94618. };
  94619. HDRCubeTexture.prototype.serialize = function () {
  94620. if (!this.name) {
  94621. return null;
  94622. }
  94623. var serializationObject = {};
  94624. serializationObject.name = this.name;
  94625. serializationObject.hasAlpha = this.hasAlpha;
  94626. serializationObject.isCube = true;
  94627. serializationObject.level = this.level;
  94628. serializationObject.size = this._size;
  94629. serializationObject.coordinatesMode = this.coordinatesMode;
  94630. serializationObject.useInGammaSpace = this.gammaSpace;
  94631. serializationObject.generateHarmonics = this._generateHarmonics;
  94632. serializationObject.customType = "BABYLON.HDRCubeTexture";
  94633. serializationObject.noMipmap = this._noMipmap;
  94634. serializationObject.isBlocking = this._isBlocking;
  94635. serializationObject.rotationY = this._rotationY;
  94636. return serializationObject;
  94637. };
  94638. HDRCubeTexture._facesMapping = [
  94639. "right",
  94640. "left",
  94641. "up",
  94642. "down",
  94643. "front",
  94644. "back"
  94645. ];
  94646. return HDRCubeTexture;
  94647. }(BABYLON.BaseTexture));
  94648. BABYLON.HDRCubeTexture = HDRCubeTexture;
  94649. })(BABYLON || (BABYLON = {}));
  94650. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  94651. var BABYLON;
  94652. (function (BABYLON) {
  94653. /**
  94654. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  94655. */
  94656. var PanoramaToCubeMapTools = /** @class */ (function () {
  94657. function PanoramaToCubeMapTools() {
  94658. }
  94659. /**
  94660. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  94661. *
  94662. * @param float32Array The source data.
  94663. * @param inputWidth The width of the input panorama.
  94664. * @param inputHeight The height of the input panorama.
  94665. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  94666. * @return The cubemap data
  94667. */
  94668. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  94669. if (!float32Array) {
  94670. throw "ConvertPanoramaToCubemap: input cannot be null";
  94671. }
  94672. if (float32Array.length != inputWidth * inputHeight * 3) {
  94673. throw "ConvertPanoramaToCubemap: input size is wrong";
  94674. }
  94675. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  94676. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  94677. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  94678. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  94679. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  94680. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  94681. return {
  94682. front: textureFront,
  94683. back: textureBack,
  94684. left: textureLeft,
  94685. right: textureRight,
  94686. up: textureUp,
  94687. down: textureDown,
  94688. size: size,
  94689. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  94690. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  94691. gammaSpace: false,
  94692. };
  94693. };
  94694. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  94695. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  94696. var textureArray = new Float32Array(buffer);
  94697. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  94698. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  94699. var dy = 1 / texSize;
  94700. var fy = 0;
  94701. for (var y = 0; y < texSize; y++) {
  94702. var xv1 = faceData[0];
  94703. var xv2 = faceData[2];
  94704. for (var x = 0; x < texSize; x++) {
  94705. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  94706. v.normalize();
  94707. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  94708. // 3 channels per pixels
  94709. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  94710. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  94711. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  94712. xv1 = xv1.add(rotDX1);
  94713. xv2 = xv2.add(rotDX2);
  94714. }
  94715. fy += dy;
  94716. }
  94717. return textureArray;
  94718. };
  94719. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  94720. var theta = Math.atan2(vDir.z, vDir.x);
  94721. var phi = Math.acos(vDir.y);
  94722. while (theta < -Math.PI) {
  94723. theta += 2 * Math.PI;
  94724. }
  94725. while (theta > Math.PI) {
  94726. theta -= 2 * Math.PI;
  94727. }
  94728. var dx = theta / Math.PI;
  94729. var dy = phi / Math.PI;
  94730. // recenter.
  94731. dx = dx * 0.5 + 0.5;
  94732. var px = Math.round(dx * inputWidth);
  94733. if (px < 0) {
  94734. px = 0;
  94735. }
  94736. else if (px >= inputWidth) {
  94737. px = inputWidth - 1;
  94738. }
  94739. var py = Math.round(dy * inputHeight);
  94740. if (py < 0) {
  94741. py = 0;
  94742. }
  94743. else if (py >= inputHeight) {
  94744. py = inputHeight - 1;
  94745. }
  94746. var inputY = (inputHeight - py - 1);
  94747. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  94748. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  94749. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  94750. return {
  94751. r: r,
  94752. g: g,
  94753. b: b
  94754. };
  94755. };
  94756. PanoramaToCubeMapTools.FACE_FRONT = [
  94757. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  94758. new BABYLON.Vector3(1.0, -1.0, -1.0),
  94759. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  94760. new BABYLON.Vector3(1.0, 1.0, -1.0)
  94761. ];
  94762. PanoramaToCubeMapTools.FACE_BACK = [
  94763. new BABYLON.Vector3(1.0, -1.0, 1.0),
  94764. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  94765. new BABYLON.Vector3(1.0, 1.0, 1.0),
  94766. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  94767. ];
  94768. PanoramaToCubeMapTools.FACE_RIGHT = [
  94769. new BABYLON.Vector3(1.0, -1.0, -1.0),
  94770. new BABYLON.Vector3(1.0, -1.0, 1.0),
  94771. new BABYLON.Vector3(1.0, 1.0, -1.0),
  94772. new BABYLON.Vector3(1.0, 1.0, 1.0)
  94773. ];
  94774. PanoramaToCubeMapTools.FACE_LEFT = [
  94775. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  94776. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  94777. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  94778. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  94779. ];
  94780. PanoramaToCubeMapTools.FACE_DOWN = [
  94781. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  94782. new BABYLON.Vector3(1.0, 1.0, -1.0),
  94783. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  94784. new BABYLON.Vector3(1.0, 1.0, 1.0)
  94785. ];
  94786. PanoramaToCubeMapTools.FACE_UP = [
  94787. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  94788. new BABYLON.Vector3(1.0, -1.0, 1.0),
  94789. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  94790. new BABYLON.Vector3(1.0, -1.0, -1.0)
  94791. ];
  94792. return PanoramaToCubeMapTools;
  94793. }());
  94794. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  94795. })(BABYLON || (BABYLON = {}));
  94796. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  94797. var BABYLON;
  94798. (function (BABYLON) {
  94799. /**
  94800. * Vector2 wth index property
  94801. */
  94802. var IndexedVector2 = /** @class */ (function (_super) {
  94803. __extends(IndexedVector2, _super);
  94804. function IndexedVector2(original,
  94805. /** Index of the vector2 */
  94806. index) {
  94807. var _this = _super.call(this, original.x, original.y) || this;
  94808. _this.index = index;
  94809. return _this;
  94810. }
  94811. return IndexedVector2;
  94812. }(BABYLON.Vector2));
  94813. /**
  94814. * Defines points to create a polygon
  94815. */
  94816. var PolygonPoints = /** @class */ (function () {
  94817. function PolygonPoints() {
  94818. this.elements = new Array();
  94819. }
  94820. PolygonPoints.prototype.add = function (originalPoints) {
  94821. var _this = this;
  94822. var result = new Array();
  94823. originalPoints.forEach(function (point) {
  94824. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  94825. var newPoint = new IndexedVector2(point, _this.elements.length);
  94826. result.push(newPoint);
  94827. _this.elements.push(newPoint);
  94828. }
  94829. });
  94830. return result;
  94831. };
  94832. PolygonPoints.prototype.computeBounds = function () {
  94833. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  94834. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  94835. this.elements.forEach(function (point) {
  94836. // x
  94837. if (point.x < lmin.x) {
  94838. lmin.x = point.x;
  94839. }
  94840. else if (point.x > lmax.x) {
  94841. lmax.x = point.x;
  94842. }
  94843. // y
  94844. if (point.y < lmin.y) {
  94845. lmin.y = point.y;
  94846. }
  94847. else if (point.y > lmax.y) {
  94848. lmax.y = point.y;
  94849. }
  94850. });
  94851. return {
  94852. min: lmin,
  94853. max: lmax,
  94854. width: lmax.x - lmin.x,
  94855. height: lmax.y - lmin.y
  94856. };
  94857. };
  94858. return PolygonPoints;
  94859. }());
  94860. /**
  94861. * Polygon
  94862. * @see https://doc.babylonjs.com/how_to/parametric_shapes#non-regular-polygon
  94863. */
  94864. var Polygon = /** @class */ (function () {
  94865. function Polygon() {
  94866. }
  94867. /**
  94868. * Creates a rectangle
  94869. * @param xmin bottom X coord
  94870. * @param ymin bottom Y coord
  94871. * @param xmax top X coord
  94872. * @param ymax top Y coord
  94873. * @returns points that make the resulting rectation
  94874. */
  94875. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  94876. return [
  94877. new BABYLON.Vector2(xmin, ymin),
  94878. new BABYLON.Vector2(xmax, ymin),
  94879. new BABYLON.Vector2(xmax, ymax),
  94880. new BABYLON.Vector2(xmin, ymax)
  94881. ];
  94882. };
  94883. /**
  94884. * Creates a circle
  94885. * @param radius radius of circle
  94886. * @param cx scale in x
  94887. * @param cy scale in y
  94888. * @param numberOfSides number of sides that make up the circle
  94889. * @returns points that make the resulting circle
  94890. */
  94891. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  94892. if (cx === void 0) { cx = 0; }
  94893. if (cy === void 0) { cy = 0; }
  94894. if (numberOfSides === void 0) { numberOfSides = 32; }
  94895. var result = new Array();
  94896. var angle = 0;
  94897. var increment = (Math.PI * 2) / numberOfSides;
  94898. for (var i = 0; i < numberOfSides; i++) {
  94899. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  94900. angle -= increment;
  94901. }
  94902. return result;
  94903. };
  94904. /**
  94905. * Creates a polygon from input string
  94906. * @param input Input polygon data
  94907. * @returns the parsed points
  94908. */
  94909. Polygon.Parse = function (input) {
  94910. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  94911. var i, result = [];
  94912. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  94913. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  94914. }
  94915. return result;
  94916. };
  94917. /**
  94918. * Starts building a polygon from x and y coordinates
  94919. * @param x x coordinate
  94920. * @param y y coordinate
  94921. * @returns the started path2
  94922. */
  94923. Polygon.StartingAt = function (x, y) {
  94924. return BABYLON.Path2.StartingAt(x, y);
  94925. };
  94926. return Polygon;
  94927. }());
  94928. BABYLON.Polygon = Polygon;
  94929. /**
  94930. * Builds a polygon
  94931. * @see https://doc.babylonjs.com/how_to/polygonmeshbuilder
  94932. */
  94933. var PolygonMeshBuilder = /** @class */ (function () {
  94934. /**
  94935. * Creates a PolygonMeshBuilder
  94936. * @param name name of the builder
  94937. * @param contours Path of the polygon
  94938. * @param scene scene to add to
  94939. */
  94940. function PolygonMeshBuilder(name, contours, scene) {
  94941. this._points = new PolygonPoints();
  94942. this._outlinepoints = new PolygonPoints();
  94943. this._holes = new Array();
  94944. this._epoints = new Array();
  94945. this._eholes = new Array();
  94946. this._name = name;
  94947. this._scene = scene;
  94948. var points;
  94949. if (contours instanceof BABYLON.Path2) {
  94950. points = contours.getPoints();
  94951. }
  94952. else {
  94953. points = contours;
  94954. }
  94955. this._addToepoint(points);
  94956. this._points.add(points);
  94957. this._outlinepoints.add(points);
  94958. if (typeof earcut === 'undefined') {
  94959. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  94960. }
  94961. }
  94962. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  94963. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  94964. var p = points_1[_i];
  94965. this._epoints.push(p.x, p.y);
  94966. }
  94967. };
  94968. /**
  94969. * Adds a whole within the polygon
  94970. * @param hole Array of points defining the hole
  94971. * @returns this
  94972. */
  94973. PolygonMeshBuilder.prototype.addHole = function (hole) {
  94974. this._points.add(hole);
  94975. var holepoints = new PolygonPoints();
  94976. holepoints.add(hole);
  94977. this._holes.push(holepoints);
  94978. this._eholes.push(this._epoints.length / 2);
  94979. this._addToepoint(hole);
  94980. return this;
  94981. };
  94982. /**
  94983. * Creates the polygon
  94984. * @param updatable If the mesh should be updatable
  94985. * @param depth The depth of the mesh created
  94986. * @returns the created mesh
  94987. */
  94988. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  94989. var _this = this;
  94990. if (updatable === void 0) { updatable = false; }
  94991. if (depth === void 0) { depth = 0; }
  94992. var result = new BABYLON.Mesh(this._name, this._scene);
  94993. var normals = new Array();
  94994. var positions = new Array();
  94995. var uvs = new Array();
  94996. var bounds = this._points.computeBounds();
  94997. this._points.elements.forEach(function (p) {
  94998. normals.push(0, 1.0, 0);
  94999. positions.push(p.x, 0, p.y);
  95000. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  95001. });
  95002. var indices = new Array();
  95003. var res = earcut(this._epoints, this._eholes, 2);
  95004. for (var i = 0; i < res.length; i++) {
  95005. indices.push(res[i]);
  95006. }
  95007. if (depth > 0) {
  95008. var positionscount = (positions.length / 3); //get the current pointcount
  95009. this._points.elements.forEach(function (p) {
  95010. normals.push(0, -1.0, 0);
  95011. positions.push(p.x, -depth, p.y);
  95012. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  95013. });
  95014. var totalCount = indices.length;
  95015. for (var i = 0; i < totalCount; i += 3) {
  95016. var i0 = indices[i + 0];
  95017. var i1 = indices[i + 1];
  95018. var i2 = indices[i + 2];
  95019. indices.push(i2 + positionscount);
  95020. indices.push(i1 + positionscount);
  95021. indices.push(i0 + positionscount);
  95022. }
  95023. //Add the sides
  95024. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  95025. this._holes.forEach(function (hole) {
  95026. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  95027. });
  95028. }
  95029. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  95030. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  95031. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  95032. result.setIndices(indices);
  95033. return result;
  95034. };
  95035. /**
  95036. * Adds a side to the polygon
  95037. * @param positions points that make the polygon
  95038. * @param normals normals of the polygon
  95039. * @param uvs uvs of the polygon
  95040. * @param indices indices of the polygon
  95041. * @param bounds bounds of the polygon
  95042. * @param points points of the polygon
  95043. * @param depth depth of the polygon
  95044. * @param flip flip of the polygon
  95045. */
  95046. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  95047. var StartIndex = positions.length / 3;
  95048. var ulength = 0;
  95049. for (var i = 0; i < points.elements.length; i++) {
  95050. var p = points.elements[i];
  95051. var p1;
  95052. if ((i + 1) > points.elements.length - 1) {
  95053. p1 = points.elements[0];
  95054. }
  95055. else {
  95056. p1 = points.elements[i + 1];
  95057. }
  95058. positions.push(p.x, 0, p.y);
  95059. positions.push(p.x, -depth, p.y);
  95060. positions.push(p1.x, 0, p1.y);
  95061. positions.push(p1.x, -depth, p1.y);
  95062. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  95063. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  95064. var v3 = v2.subtract(v1);
  95065. var v4 = new BABYLON.Vector3(0, 1, 0);
  95066. var vn = BABYLON.Vector3.Cross(v3, v4);
  95067. vn = vn.normalize();
  95068. uvs.push(ulength / bounds.width, 0);
  95069. uvs.push(ulength / bounds.width, 1);
  95070. ulength += v3.length();
  95071. uvs.push((ulength / bounds.width), 0);
  95072. uvs.push((ulength / bounds.width), 1);
  95073. if (!flip) {
  95074. normals.push(-vn.x, -vn.y, -vn.z);
  95075. normals.push(-vn.x, -vn.y, -vn.z);
  95076. normals.push(-vn.x, -vn.y, -vn.z);
  95077. normals.push(-vn.x, -vn.y, -vn.z);
  95078. indices.push(StartIndex);
  95079. indices.push(StartIndex + 1);
  95080. indices.push(StartIndex + 2);
  95081. indices.push(StartIndex + 1);
  95082. indices.push(StartIndex + 3);
  95083. indices.push(StartIndex + 2);
  95084. }
  95085. else {
  95086. normals.push(vn.x, vn.y, vn.z);
  95087. normals.push(vn.x, vn.y, vn.z);
  95088. normals.push(vn.x, vn.y, vn.z);
  95089. normals.push(vn.x, vn.y, vn.z);
  95090. indices.push(StartIndex);
  95091. indices.push(StartIndex + 2);
  95092. indices.push(StartIndex + 1);
  95093. indices.push(StartIndex + 1);
  95094. indices.push(StartIndex + 2);
  95095. indices.push(StartIndex + 3);
  95096. }
  95097. StartIndex += 4;
  95098. }
  95099. };
  95100. return PolygonMeshBuilder;
  95101. }());
  95102. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  95103. })(BABYLON || (BABYLON = {}));
  95104. //# sourceMappingURL=babylon.polygonMesh.js.map
  95105. var BABYLON;
  95106. (function (BABYLON) {
  95107. /**
  95108. * Unique ID when we import meshes from Babylon to CSG
  95109. */
  95110. var currentCSGMeshId = 0;
  95111. /**
  95112. * Represents a vertex of a polygon. Use your own vertex class instead of this
  95113. * one to provide additional features like texture coordinates and vertex
  95114. * colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  95115. * `flip()`, and `interpolate()` methods that behave analogous to the ones
  95116. * defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  95117. * functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  95118. * is not used anywhere else.
  95119. * Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  95120. */
  95121. var Vertex = /** @class */ (function () {
  95122. /**
  95123. * Initializes the vertex
  95124. * @param pos The position of the vertex
  95125. * @param normal The normal of the vertex
  95126. * @param uv The texture coordinate of the vertex
  95127. */
  95128. function Vertex(
  95129. /**
  95130. * The position of the vertex
  95131. */
  95132. pos,
  95133. /**
  95134. * The normal of the vertex
  95135. */
  95136. normal,
  95137. /**
  95138. * The texture coordinate of the vertex
  95139. */
  95140. uv) {
  95141. this.pos = pos;
  95142. this.normal = normal;
  95143. this.uv = uv;
  95144. }
  95145. /**
  95146. * Make a clone, or deep copy, of the vertex
  95147. * @returns A new Vertex
  95148. */
  95149. Vertex.prototype.clone = function () {
  95150. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  95151. };
  95152. /**
  95153. * Invert all orientation-specific data (e.g. vertex normal). Called when the
  95154. * orientation of a polygon is flipped.
  95155. */
  95156. Vertex.prototype.flip = function () {
  95157. this.normal = this.normal.scale(-1);
  95158. };
  95159. /**
  95160. * Create a new vertex between this vertex and `other` by linearly
  95161. * interpolating all properties using a parameter of `t`. Subclasses should
  95162. * override this to interpolate additional properties.
  95163. * @param other the vertex to interpolate against
  95164. * @param t The factor used to linearly interpolate between the vertices
  95165. */
  95166. Vertex.prototype.interpolate = function (other, t) {
  95167. 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));
  95168. };
  95169. return Vertex;
  95170. }());
  95171. /**
  95172. * Represents a plane in 3D space.
  95173. */
  95174. var Plane = /** @class */ (function () {
  95175. /**
  95176. * Initializes the plane
  95177. * @param normal The normal for the plane
  95178. * @param w
  95179. */
  95180. function Plane(normal, w) {
  95181. this.normal = normal;
  95182. this.w = w;
  95183. }
  95184. /**
  95185. * Construct a plane from three points
  95186. * @param a Point a
  95187. * @param b Point b
  95188. * @param c Point c
  95189. */
  95190. Plane.FromPoints = function (a, b, c) {
  95191. var v0 = c.subtract(a);
  95192. var v1 = b.subtract(a);
  95193. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  95194. return null;
  95195. }
  95196. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  95197. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  95198. };
  95199. /**
  95200. * Clone, or make a deep copy of the plane
  95201. * @returns a new Plane
  95202. */
  95203. Plane.prototype.clone = function () {
  95204. return new Plane(this.normal.clone(), this.w);
  95205. };
  95206. /**
  95207. * Flip the face of the plane
  95208. */
  95209. Plane.prototype.flip = function () {
  95210. this.normal.scaleInPlace(-1);
  95211. this.w = -this.w;
  95212. };
  95213. /**
  95214. * Split `polygon` by this plane if needed, then put the polygon or polygon
  95215. * fragments in the appropriate lists. Coplanar polygons go into either
  95216. `* coplanarFront` or `coplanarBack` depending on their orientation with
  95217. * respect to this plane. Polygons in front or in back of this plane go into
  95218. * either `front` or `back`
  95219. * @param polygon The polygon to be split
  95220. * @param coplanarFront Will contain polygons coplanar with the plane that are oriented to the front of the plane
  95221. * @param coplanarBack Will contain polygons coplanar with the plane that are oriented to the back of the plane
  95222. * @param front Will contain the polygons in front of the plane
  95223. * @param back Will contain the polygons begind the plane
  95224. */
  95225. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  95226. var COPLANAR = 0;
  95227. var FRONT = 1;
  95228. var BACK = 2;
  95229. var SPANNING = 3;
  95230. // Classify each point as well as the entire polygon into one of the above
  95231. // four classes.
  95232. var polygonType = 0;
  95233. var types = [];
  95234. var i;
  95235. var t;
  95236. for (i = 0; i < polygon.vertices.length; i++) {
  95237. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  95238. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  95239. polygonType |= type;
  95240. types.push(type);
  95241. }
  95242. // Put the polygon in the correct list, splitting it when necessary
  95243. switch (polygonType) {
  95244. case COPLANAR:
  95245. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  95246. break;
  95247. case FRONT:
  95248. front.push(polygon);
  95249. break;
  95250. case BACK:
  95251. back.push(polygon);
  95252. break;
  95253. case SPANNING:
  95254. var f = [], b = [];
  95255. for (i = 0; i < polygon.vertices.length; i++) {
  95256. var j = (i + 1) % polygon.vertices.length;
  95257. var ti = types[i], tj = types[j];
  95258. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  95259. if (ti !== BACK) {
  95260. f.push(vi);
  95261. }
  95262. if (ti !== FRONT) {
  95263. b.push(ti !== BACK ? vi.clone() : vi);
  95264. }
  95265. if ((ti | tj) === SPANNING) {
  95266. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  95267. var v = vi.interpolate(vj, t);
  95268. f.push(v);
  95269. b.push(v.clone());
  95270. }
  95271. }
  95272. var poly;
  95273. if (f.length >= 3) {
  95274. poly = new Polygon(f, polygon.shared);
  95275. if (poly.plane) {
  95276. front.push(poly);
  95277. }
  95278. }
  95279. if (b.length >= 3) {
  95280. poly = new Polygon(b, polygon.shared);
  95281. if (poly.plane) {
  95282. back.push(poly);
  95283. }
  95284. }
  95285. break;
  95286. }
  95287. };
  95288. /**
  95289. * `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  95290. * point is on the plane
  95291. */
  95292. Plane.EPSILON = 1e-5;
  95293. return Plane;
  95294. }());
  95295. /**
  95296. * Represents a convex polygon. The vertices used to initialize a polygon must
  95297. * be coplanar and form a convex loop.
  95298. *
  95299. * Each convex polygon has a `shared` property, which is shared between all
  95300. * polygons that are clones of each other or were split from the same polygon.
  95301. * This can be used to define per-polygon properties (such as surface color)
  95302. */
  95303. var Polygon = /** @class */ (function () {
  95304. /**
  95305. * Initializes the polygon
  95306. * @param vertices The vertices of the polygon
  95307. * @param shared The properties shared across all polygons
  95308. */
  95309. function Polygon(vertices, shared) {
  95310. this.vertices = vertices;
  95311. this.shared = shared;
  95312. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  95313. }
  95314. /**
  95315. * Clones, or makes a deep copy, or the polygon
  95316. */
  95317. Polygon.prototype.clone = function () {
  95318. var vertices = this.vertices.map(function (v) { return v.clone(); });
  95319. return new Polygon(vertices, this.shared);
  95320. };
  95321. /**
  95322. * Flips the faces of the polygon
  95323. */
  95324. Polygon.prototype.flip = function () {
  95325. this.vertices.reverse().map(function (v) { v.flip(); });
  95326. this.plane.flip();
  95327. };
  95328. return Polygon;
  95329. }());
  95330. /**
  95331. * Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  95332. * by picking a polygon to split along. That polygon (and all other coplanar
  95333. * polygons) are added directly to that node and the other polygons are added to
  95334. * the front and/or back subtrees. This is not a leafy BSP tree since there is
  95335. * no distinction between internal and leaf nodes
  95336. */
  95337. var Node = /** @class */ (function () {
  95338. /**
  95339. * Initializes the node
  95340. * @param polygons A collection of polygons held in the node
  95341. */
  95342. function Node(polygons) {
  95343. this.plane = null;
  95344. this.front = null;
  95345. this.back = null;
  95346. this.polygons = new Array();
  95347. if (polygons) {
  95348. this.build(polygons);
  95349. }
  95350. }
  95351. /**
  95352. * Clones, or makes a deep copy, of the node
  95353. * @returns The cloned node
  95354. */
  95355. Node.prototype.clone = function () {
  95356. var node = new Node();
  95357. node.plane = this.plane && this.plane.clone();
  95358. node.front = this.front && this.front.clone();
  95359. node.back = this.back && this.back.clone();
  95360. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  95361. return node;
  95362. };
  95363. /**
  95364. * Convert solid space to empty space and empty space to solid space
  95365. */
  95366. Node.prototype.invert = function () {
  95367. for (var i = 0; i < this.polygons.length; i++) {
  95368. this.polygons[i].flip();
  95369. }
  95370. if (this.plane) {
  95371. this.plane.flip();
  95372. }
  95373. if (this.front) {
  95374. this.front.invert();
  95375. }
  95376. if (this.back) {
  95377. this.back.invert();
  95378. }
  95379. var temp = this.front;
  95380. this.front = this.back;
  95381. this.back = temp;
  95382. };
  95383. /**
  95384. * Recursively remove all polygons in `polygons` that are inside this BSP
  95385. * tree.
  95386. * @param polygons Polygons to remove from the BSP
  95387. * @returns Polygons clipped from the BSP
  95388. */
  95389. Node.prototype.clipPolygons = function (polygons) {
  95390. if (!this.plane) {
  95391. return polygons.slice();
  95392. }
  95393. var front = new Array(), back = new Array();
  95394. for (var i = 0; i < polygons.length; i++) {
  95395. this.plane.splitPolygon(polygons[i], front, back, front, back);
  95396. }
  95397. if (this.front) {
  95398. front = this.front.clipPolygons(front);
  95399. }
  95400. if (this.back) {
  95401. back = this.back.clipPolygons(back);
  95402. }
  95403. else {
  95404. back = [];
  95405. }
  95406. return front.concat(back);
  95407. };
  95408. /**
  95409. * Remove all polygons in this BSP tree that are inside the other BSP tree
  95410. * `bsp`.
  95411. * @param bsp BSP containing polygons to remove from this BSP
  95412. */
  95413. Node.prototype.clipTo = function (bsp) {
  95414. this.polygons = bsp.clipPolygons(this.polygons);
  95415. if (this.front) {
  95416. this.front.clipTo(bsp);
  95417. }
  95418. if (this.back) {
  95419. this.back.clipTo(bsp);
  95420. }
  95421. };
  95422. /**
  95423. * Return a list of all polygons in this BSP tree
  95424. * @returns List of all polygons in this BSP tree
  95425. */
  95426. Node.prototype.allPolygons = function () {
  95427. var polygons = this.polygons.slice();
  95428. if (this.front) {
  95429. polygons = polygons.concat(this.front.allPolygons());
  95430. }
  95431. if (this.back) {
  95432. polygons = polygons.concat(this.back.allPolygons());
  95433. }
  95434. return polygons;
  95435. };
  95436. /**
  95437. * Build a BSP tree out of `polygons`. When called on an existing tree, the
  95438. * new polygons are filtered down to the bottom of the tree and become new
  95439. * nodes there. Each set of polygons is partitioned using the first polygon
  95440. * (no heuristic is used to pick a good split)
  95441. * @param polygons Polygons used to construct the BSP tree
  95442. */
  95443. Node.prototype.build = function (polygons) {
  95444. if (!polygons.length) {
  95445. return;
  95446. }
  95447. if (!this.plane) {
  95448. this.plane = polygons[0].plane.clone();
  95449. }
  95450. var front = new Array(), back = new Array();
  95451. for (var i = 0; i < polygons.length; i++) {
  95452. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  95453. }
  95454. if (front.length) {
  95455. if (!this.front) {
  95456. this.front = new Node();
  95457. }
  95458. this.front.build(front);
  95459. }
  95460. if (back.length) {
  95461. if (!this.back) {
  95462. this.back = new Node();
  95463. }
  95464. this.back.build(back);
  95465. }
  95466. };
  95467. return Node;
  95468. }());
  95469. /**
  95470. * Class for building Constructive Solid Geometry
  95471. */
  95472. var CSG = /** @class */ (function () {
  95473. function CSG() {
  95474. this.polygons = new Array();
  95475. }
  95476. /**
  95477. * Convert the BABYLON.Mesh to BABYLON.CSG
  95478. * @param mesh The BABYLON.Mesh to convert to BABYLON.CSG
  95479. * @returns A new BABYLON.CSG from the BABYLON.Mesh
  95480. */
  95481. CSG.FromMesh = function (mesh) {
  95482. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  95483. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  95484. if (mesh instanceof BABYLON.Mesh) {
  95485. mesh.computeWorldMatrix(true);
  95486. matrix = mesh.getWorldMatrix();
  95487. meshPosition = mesh.position.clone();
  95488. meshRotation = mesh.rotation.clone();
  95489. if (mesh.rotationQuaternion) {
  95490. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  95491. }
  95492. meshScaling = mesh.scaling.clone();
  95493. }
  95494. else {
  95495. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  95496. }
  95497. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  95498. var subMeshes = mesh.subMeshes;
  95499. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  95500. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  95501. vertices = [];
  95502. for (var j = 0; j < 3; j++) {
  95503. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  95504. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  95505. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  95506. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  95507. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  95508. vertex = new Vertex(position, normal, uv);
  95509. vertices.push(vertex);
  95510. }
  95511. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  95512. // To handle the case of degenerated triangle
  95513. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  95514. if (polygon.plane) {
  95515. polygons.push(polygon);
  95516. }
  95517. }
  95518. }
  95519. var csg = CSG.FromPolygons(polygons);
  95520. csg.matrix = matrix;
  95521. csg.position = meshPosition;
  95522. csg.rotation = meshRotation;
  95523. csg.scaling = meshScaling;
  95524. csg.rotationQuaternion = meshRotationQuaternion;
  95525. currentCSGMeshId++;
  95526. return csg;
  95527. };
  95528. /**
  95529. * Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  95530. * @param polygons Polygons used to construct a BABYLON.CSG solid
  95531. */
  95532. CSG.FromPolygons = function (polygons) {
  95533. var csg = new CSG();
  95534. csg.polygons = polygons;
  95535. return csg;
  95536. };
  95537. /**
  95538. * Clones, or makes a deep copy, of the BABYLON.CSG
  95539. * @returns A new BABYLON.CSG
  95540. */
  95541. CSG.prototype.clone = function () {
  95542. var csg = new CSG();
  95543. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  95544. csg.copyTransformAttributes(this);
  95545. return csg;
  95546. };
  95547. /**
  95548. * Unions this CSG with another CSG
  95549. * @param csg The CSG to union against this CSG
  95550. * @returns The unioned CSG
  95551. */
  95552. CSG.prototype.union = function (csg) {
  95553. var a = new Node(this.clone().polygons);
  95554. var b = new Node(csg.clone().polygons);
  95555. a.clipTo(b);
  95556. b.clipTo(a);
  95557. b.invert();
  95558. b.clipTo(a);
  95559. b.invert();
  95560. a.build(b.allPolygons());
  95561. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  95562. };
  95563. /**
  95564. * Unions this CSG with another CSG in place
  95565. * @param csg The CSG to union against this CSG
  95566. */
  95567. CSG.prototype.unionInPlace = function (csg) {
  95568. var a = new Node(this.polygons);
  95569. var b = new Node(csg.polygons);
  95570. a.clipTo(b);
  95571. b.clipTo(a);
  95572. b.invert();
  95573. b.clipTo(a);
  95574. b.invert();
  95575. a.build(b.allPolygons());
  95576. this.polygons = a.allPolygons();
  95577. };
  95578. /**
  95579. * Subtracts this CSG with another CSG
  95580. * @param csg The CSG to subtract against this CSG
  95581. * @returns A new BABYLON.CSG
  95582. */
  95583. CSG.prototype.subtract = function (csg) {
  95584. var a = new Node(this.clone().polygons);
  95585. var b = new Node(csg.clone().polygons);
  95586. a.invert();
  95587. a.clipTo(b);
  95588. b.clipTo(a);
  95589. b.invert();
  95590. b.clipTo(a);
  95591. b.invert();
  95592. a.build(b.allPolygons());
  95593. a.invert();
  95594. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  95595. };
  95596. /**
  95597. * Subtracts this CSG with another CSG in place
  95598. * @param csg The CSG to subtact against this CSG
  95599. */
  95600. CSG.prototype.subtractInPlace = function (csg) {
  95601. var a = new Node(this.polygons);
  95602. var b = new Node(csg.polygons);
  95603. a.invert();
  95604. a.clipTo(b);
  95605. b.clipTo(a);
  95606. b.invert();
  95607. b.clipTo(a);
  95608. b.invert();
  95609. a.build(b.allPolygons());
  95610. a.invert();
  95611. this.polygons = a.allPolygons();
  95612. };
  95613. /**
  95614. * Intersect this CSG with another CSG
  95615. * @param csg The CSG to intersect against this CSG
  95616. * @returns A new BABYLON.CSG
  95617. */
  95618. CSG.prototype.intersect = function (csg) {
  95619. var a = new Node(this.clone().polygons);
  95620. var b = new Node(csg.clone().polygons);
  95621. a.invert();
  95622. b.clipTo(a);
  95623. b.invert();
  95624. a.clipTo(b);
  95625. b.clipTo(a);
  95626. a.build(b.allPolygons());
  95627. a.invert();
  95628. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  95629. };
  95630. /**
  95631. * Intersects this CSG with another CSG in place
  95632. * @param csg The CSG to intersect against this CSG
  95633. */
  95634. CSG.prototype.intersectInPlace = function (csg) {
  95635. var a = new Node(this.polygons);
  95636. var b = new Node(csg.polygons);
  95637. a.invert();
  95638. b.clipTo(a);
  95639. b.invert();
  95640. a.clipTo(b);
  95641. b.clipTo(a);
  95642. a.build(b.allPolygons());
  95643. a.invert();
  95644. this.polygons = a.allPolygons();
  95645. };
  95646. /**
  95647. * Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  95648. * not modified.
  95649. * @returns A new BABYLON.CSG solid with solid and empty space switched
  95650. */
  95651. CSG.prototype.inverse = function () {
  95652. var csg = this.clone();
  95653. csg.inverseInPlace();
  95654. return csg;
  95655. };
  95656. /**
  95657. * Inverses the BABYLON.CSG in place
  95658. */
  95659. CSG.prototype.inverseInPlace = function () {
  95660. this.polygons.map(function (p) { p.flip(); });
  95661. };
  95662. /**
  95663. * This is used to keep meshes transformations so they can be restored
  95664. * when we build back a Babylon Mesh
  95665. * NB : All CSG operations are performed in world coordinates
  95666. * @param csg The BABYLON.CSG to copy the transform attributes from
  95667. * @returns This BABYLON.CSG
  95668. */
  95669. CSG.prototype.copyTransformAttributes = function (csg) {
  95670. this.matrix = csg.matrix;
  95671. this.position = csg.position;
  95672. this.rotation = csg.rotation;
  95673. this.scaling = csg.scaling;
  95674. this.rotationQuaternion = csg.rotationQuaternion;
  95675. return this;
  95676. };
  95677. /**
  95678. * Build Raw mesh from CSG
  95679. * Coordinates here are in world space
  95680. * @param name The name of the mesh geometry
  95681. * @param scene The BABYLON.Scene
  95682. * @param keepSubMeshes Specifies if the submeshes should be kept
  95683. * @returns A new BABYLON.Mesh
  95684. */
  95685. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  95686. var matrix = this.matrix.clone();
  95687. matrix.invert();
  95688. 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;
  95689. if (keepSubMeshes) {
  95690. // Sort Polygons, since subMeshes are indices range
  95691. polygons.sort(function (a, b) {
  95692. if (a.shared.meshId === b.shared.meshId) {
  95693. return a.shared.subMeshId - b.shared.subMeshId;
  95694. }
  95695. else {
  95696. return a.shared.meshId - b.shared.meshId;
  95697. }
  95698. });
  95699. }
  95700. for (var i = 0, il = polygons.length; i < il; i++) {
  95701. polygon = polygons[i];
  95702. // Building SubMeshes
  95703. if (!subMesh_dict[polygon.shared.meshId]) {
  95704. subMesh_dict[polygon.shared.meshId] = {};
  95705. }
  95706. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  95707. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  95708. indexStart: +Infinity,
  95709. indexEnd: -Infinity,
  95710. materialIndex: polygon.shared.materialIndex
  95711. };
  95712. }
  95713. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  95714. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  95715. polygonIndices[0] = 0;
  95716. polygonIndices[1] = j - 1;
  95717. polygonIndices[2] = j;
  95718. for (var k = 0; k < 3; k++) {
  95719. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  95720. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  95721. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  95722. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  95723. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  95724. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  95725. // Check if 2 points can be merged
  95726. if (!(typeof vertex_idx !== 'undefined' &&
  95727. normals[vertex_idx * 3] === localNormal.x &&
  95728. normals[vertex_idx * 3 + 1] === localNormal.y &&
  95729. normals[vertex_idx * 3 + 2] === localNormal.z &&
  95730. uvs[vertex_idx * 2] === uv.x &&
  95731. uvs[vertex_idx * 2 + 1] === uv.y)) {
  95732. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  95733. uvs.push(uv.x, uv.y);
  95734. normals.push(normal.x, normal.y, normal.z);
  95735. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  95736. }
  95737. indices.push(vertex_idx);
  95738. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  95739. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  95740. currentIndex++;
  95741. }
  95742. }
  95743. }
  95744. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  95745. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  95746. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  95747. mesh.setIndices(indices, null);
  95748. if (keepSubMeshes) {
  95749. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  95750. var materialIndexOffset = 0, materialMaxIndex;
  95751. mesh.subMeshes = new Array();
  95752. for (var m in subMesh_dict) {
  95753. materialMaxIndex = -1;
  95754. for (var sm in subMesh_dict[m]) {
  95755. subMesh_obj = subMesh_dict[m][sm];
  95756. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  95757. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  95758. }
  95759. materialIndexOffset += ++materialMaxIndex;
  95760. }
  95761. }
  95762. return mesh;
  95763. };
  95764. /**
  95765. * Build Mesh from CSG taking material and transforms into account
  95766. * @param name The name of the BABYLON.Mesh
  95767. * @param material The material of the BABYLON.Mesh
  95768. * @param scene The BABYLON.Scene
  95769. * @param keepSubMeshes Specifies if submeshes should be kept
  95770. * @returns The new BABYLON.Mesh
  95771. */
  95772. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  95773. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  95774. mesh.material = material;
  95775. mesh.position.copyFrom(this.position);
  95776. mesh.rotation.copyFrom(this.rotation);
  95777. if (this.rotationQuaternion) {
  95778. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  95779. }
  95780. mesh.scaling.copyFrom(this.scaling);
  95781. mesh.computeWorldMatrix(true);
  95782. return mesh;
  95783. };
  95784. return CSG;
  95785. }());
  95786. BABYLON.CSG = CSG;
  95787. })(BABYLON || (BABYLON = {}));
  95788. //# sourceMappingURL=babylon.csg.js.map
  95789. var BABYLON;
  95790. (function (BABYLON) {
  95791. /**
  95792. * This represents one of the lens effect in a `BABYLON.lensFlareSystem`.
  95793. * It controls one of the indiviual texture used in the effect.
  95794. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  95795. */
  95796. var LensFlare = /** @class */ (function () {
  95797. /**
  95798. * Instantiates a new Lens Flare.
  95799. * This represents one of the lens effect in a `BABYLON.lensFlareSystem`.
  95800. * It controls one of the indiviual texture used in the effect.
  95801. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  95802. * @param size Define the size of the lens flare in the system (a floating value between 0 and 1)
  95803. * @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.
  95804. * @param color Define the lens color
  95805. * @param imgUrl Define the lens texture url
  95806. * @param system Define the `lensFlareSystem` this flare is part of
  95807. */
  95808. function LensFlare(
  95809. /**
  95810. * Define the size of the lens flare in the system (a floating value between 0 and 1)
  95811. */
  95812. size,
  95813. /**
  95814. * 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.
  95815. */
  95816. position, color, imgUrl, system) {
  95817. this.size = size;
  95818. this.position = position;
  95819. /**
  95820. * Define the alpha mode to render this particular lens.
  95821. */
  95822. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  95823. this.color = color || new BABYLON.Color3(1, 1, 1);
  95824. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  95825. this._system = system;
  95826. system.lensFlares.push(this);
  95827. }
  95828. /**
  95829. * Creates a new Lens Flare.
  95830. * This represents one of the lens effect in a `BABYLON.lensFlareSystem`.
  95831. * It controls one of the indiviual texture used in the effect.
  95832. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  95833. * @param size Define the size of the lens flare (a floating value between 0 and 1)
  95834. * @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.
  95835. * @param color Define the lens color
  95836. * @param imgUrl Define the lens texture url
  95837. * @param system Define the `lensFlareSystem` this flare is part of
  95838. * @returns The newly created Lens Flare
  95839. */
  95840. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  95841. return new LensFlare(size, position, color, imgUrl, system);
  95842. };
  95843. /**
  95844. * Dispose and release the lens flare with its associated resources.
  95845. */
  95846. LensFlare.prototype.dispose = function () {
  95847. if (this.texture) {
  95848. this.texture.dispose();
  95849. }
  95850. // Remove from scene
  95851. var index = this._system.lensFlares.indexOf(this);
  95852. this._system.lensFlares.splice(index, 1);
  95853. };
  95854. return LensFlare;
  95855. }());
  95856. BABYLON.LensFlare = LensFlare;
  95857. })(BABYLON || (BABYLON = {}));
  95858. //# sourceMappingURL=babylon.lensFlare.js.map
  95859. var BABYLON;
  95860. (function (BABYLON) {
  95861. // Adds the parser to the scene parsers.
  95862. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM, function (parsedData, scene, container, rootUrl) {
  95863. // Lens flares
  95864. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  95865. if (!container.lensFlareSystems) {
  95866. container.lensFlareSystems = new Array();
  95867. }
  95868. for (var index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  95869. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  95870. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  95871. container.lensFlareSystems.push(lf);
  95872. }
  95873. }
  95874. });
  95875. BABYLON.AbstractScene.prototype.getLensFlareSystemByName = function (name) {
  95876. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  95877. if (this.lensFlareSystems[index].name === name) {
  95878. return this.lensFlareSystems[index];
  95879. }
  95880. }
  95881. return null;
  95882. };
  95883. BABYLON.AbstractScene.prototype.getLensFlareSystemByID = function (id) {
  95884. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  95885. if (this.lensFlareSystems[index].id === id) {
  95886. return this.lensFlareSystems[index];
  95887. }
  95888. }
  95889. return null;
  95890. };
  95891. BABYLON.AbstractScene.prototype.removeLensFlareSystem = function (toRemove) {
  95892. var index = this.lensFlareSystems.indexOf(toRemove);
  95893. if (index !== -1) {
  95894. this.lensFlareSystems.splice(index, 1);
  95895. }
  95896. return index;
  95897. };
  95898. BABYLON.AbstractScene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  95899. this.lensFlareSystems.push(newLensFlareSystem);
  95900. };
  95901. /**
  95902. * Defines the lens flare scene component responsible to manage any lens flares
  95903. * in a given scene.
  95904. */
  95905. var LensFlareSystemSceneComponent = /** @class */ (function () {
  95906. /**
  95907. * Creates a new instance of the component for the given scene
  95908. * @param scene Defines the scene to register the component in
  95909. */
  95910. function LensFlareSystemSceneComponent(scene) {
  95911. /**
  95912. * The component name helpfull to identify the component in the list of scene components.
  95913. */
  95914. this.name = BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM;
  95915. this.scene = scene;
  95916. scene.lensFlareSystems = new Array();
  95917. }
  95918. /**
  95919. * Registers the component in a given scene
  95920. */
  95921. LensFlareSystemSceneComponent.prototype.register = function () {
  95922. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM, this, this._draw);
  95923. };
  95924. /**
  95925. * Rebuilds the elements related to this component in case of
  95926. * context lost for instance.
  95927. */
  95928. LensFlareSystemSceneComponent.prototype.rebuild = function () {
  95929. // Nothing to do for lens flare
  95930. };
  95931. /**
  95932. * Adds all the element from the container to the scene
  95933. * @param container the container holding the elements
  95934. */
  95935. LensFlareSystemSceneComponent.prototype.addFromContainer = function (container) {
  95936. var _this = this;
  95937. if (!container.lensFlareSystems) {
  95938. return;
  95939. }
  95940. container.lensFlareSystems.forEach(function (o) {
  95941. _this.scene.addLensFlareSystem(o);
  95942. });
  95943. };
  95944. /**
  95945. * Removes all the elements in the container from the scene
  95946. * @param container contains the elements to remove
  95947. */
  95948. LensFlareSystemSceneComponent.prototype.removeFromContainer = function (container) {
  95949. var _this = this;
  95950. if (!container.lensFlareSystems) {
  95951. return;
  95952. }
  95953. container.lensFlareSystems.forEach(function (o) {
  95954. _this.scene.removeLensFlareSystem(o);
  95955. });
  95956. };
  95957. /**
  95958. * Serializes the component data to the specified json object
  95959. * @param serializationObject The object to serialize to
  95960. */
  95961. LensFlareSystemSceneComponent.prototype.serialize = function (serializationObject) {
  95962. // Lens flares
  95963. serializationObject.lensFlareSystems = [];
  95964. var lensFlareSystems = this.scene.lensFlareSystems;
  95965. for (var _i = 0, lensFlareSystems_1 = lensFlareSystems; _i < lensFlareSystems_1.length; _i++) {
  95966. var lensFlareSystem = lensFlareSystems_1[_i];
  95967. serializationObject.lensFlareSystems.push(lensFlareSystem.serialize());
  95968. }
  95969. };
  95970. /**
  95971. * Disposes the component and the associated ressources.
  95972. */
  95973. LensFlareSystemSceneComponent.prototype.dispose = function () {
  95974. var lensFlareSystems = this.scene.lensFlareSystems;
  95975. while (lensFlareSystems.length) {
  95976. lensFlareSystems[0].dispose();
  95977. }
  95978. };
  95979. LensFlareSystemSceneComponent.prototype._draw = function (camera) {
  95980. // Lens flares
  95981. if (this.scene.lensFlaresEnabled) {
  95982. var lensFlareSystems = this.scene.lensFlareSystems;
  95983. BABYLON.Tools.StartPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
  95984. for (var _i = 0, lensFlareSystems_2 = lensFlareSystems; _i < lensFlareSystems_2.length; _i++) {
  95985. var lensFlareSystem = lensFlareSystems_2[_i];
  95986. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  95987. lensFlareSystem.render();
  95988. }
  95989. }
  95990. BABYLON.Tools.EndPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
  95991. }
  95992. };
  95993. return LensFlareSystemSceneComponent;
  95994. }());
  95995. BABYLON.LensFlareSystemSceneComponent = LensFlareSystemSceneComponent;
  95996. })(BABYLON || (BABYLON = {}));
  95997. //# sourceMappingURL=babylon.lensFlareSystemSceneComponent.js.map
  95998. var BABYLON;
  95999. (function (BABYLON) {
  96000. /**
  96001. * This represents a Lens Flare System or the shiny effect created by the light reflection on the camera lenses.
  96002. * It is usually composed of several `BABYLON.lensFlare`.
  96003. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  96004. */
  96005. var LensFlareSystem = /** @class */ (function () {
  96006. /**
  96007. * Instantiates a lens flare system.
  96008. * This represents a Lens Flare System or the shiny effect created by the light reflection on the camera lenses.
  96009. * It is usually composed of several `BABYLON.lensFlare`.
  96010. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  96011. * @param name Define the name of the lens flare system in the scene
  96012. * @param emitter Define the source (the emitter) of the lens flares (it can be a camera, a light or a mesh).
  96013. * @param scene Define the scene the lens flare system belongs to
  96014. */
  96015. function LensFlareSystem(
  96016. /**
  96017. * Define the name of the lens flare system
  96018. */
  96019. name, emitter, scene) {
  96020. this.name = name;
  96021. /**
  96022. * List of lens flares used in this system.
  96023. */
  96024. this.lensFlares = new Array();
  96025. /**
  96026. * Define a limit from the border the lens flare can be visible.
  96027. */
  96028. this.borderLimit = 300;
  96029. /**
  96030. * Define a viewport border we do not want to see the lens flare in.
  96031. */
  96032. this.viewportBorder = 0;
  96033. /**
  96034. * Restricts the rendering of the effect to only the camera rendering this layer mask.
  96035. */
  96036. this.layerMask = 0x0FFFFFFF;
  96037. this._vertexBuffers = {};
  96038. this._isEnabled = true;
  96039. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  96040. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM);
  96041. if (!component) {
  96042. component = new BABYLON.LensFlareSystemSceneComponent(this._scene);
  96043. scene._addComponent(component);
  96044. }
  96045. this._emitter = emitter;
  96046. this.id = name;
  96047. scene.lensFlareSystems.push(this);
  96048. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  96049. var engine = scene.getEngine();
  96050. // VBO
  96051. var vertices = [];
  96052. vertices.push(1, 1);
  96053. vertices.push(-1, 1);
  96054. vertices.push(-1, -1);
  96055. vertices.push(1, -1);
  96056. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  96057. // Indices
  96058. var indices = [];
  96059. indices.push(0);
  96060. indices.push(1);
  96061. indices.push(2);
  96062. indices.push(0);
  96063. indices.push(2);
  96064. indices.push(3);
  96065. this._indexBuffer = engine.createIndexBuffer(indices);
  96066. // Effects
  96067. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  96068. }
  96069. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  96070. /**
  96071. * Define if the lens flare system is enabled.
  96072. */
  96073. get: function () {
  96074. return this._isEnabled;
  96075. },
  96076. set: function (value) {
  96077. this._isEnabled = value;
  96078. },
  96079. enumerable: true,
  96080. configurable: true
  96081. });
  96082. /**
  96083. * Get the scene the effects belongs to.
  96084. * @returns the scene holding the lens flare system
  96085. */
  96086. LensFlareSystem.prototype.getScene = function () {
  96087. return this._scene;
  96088. };
  96089. /**
  96090. * Get the emitter of the lens flare system.
  96091. * It defines the source of the lens flares (it can be a camera, a light or a mesh).
  96092. * @returns the emitter of the lens flare system
  96093. */
  96094. LensFlareSystem.prototype.getEmitter = function () {
  96095. return this._emitter;
  96096. };
  96097. /**
  96098. * Set the emitter of the lens flare system.
  96099. * It defines the source of the lens flares (it can be a camera, a light or a mesh).
  96100. * @param newEmitter Define the new emitter of the system
  96101. */
  96102. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  96103. this._emitter = newEmitter;
  96104. };
  96105. /**
  96106. * Get the lens flare system emitter position.
  96107. * The emitter defines the source of the lens flares (it can be a camera, a light or a mesh).
  96108. * @returns the position
  96109. */
  96110. LensFlareSystem.prototype.getEmitterPosition = function () {
  96111. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  96112. };
  96113. /**
  96114. * @hidden
  96115. */
  96116. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  96117. var position = this.getEmitterPosition();
  96118. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  96119. this._positionX = position.x;
  96120. this._positionY = position.y;
  96121. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  96122. if (this.viewportBorder > 0) {
  96123. globalViewport.x -= this.viewportBorder;
  96124. globalViewport.y -= this.viewportBorder;
  96125. globalViewport.width += this.viewportBorder * 2;
  96126. globalViewport.height += this.viewportBorder * 2;
  96127. position.x += this.viewportBorder;
  96128. position.y += this.viewportBorder;
  96129. this._positionX += this.viewportBorder;
  96130. this._positionY += this.viewportBorder;
  96131. }
  96132. if (position.z > 0) {
  96133. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  96134. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height)) {
  96135. return true;
  96136. }
  96137. }
  96138. return true;
  96139. }
  96140. return false;
  96141. };
  96142. /** @hidden */
  96143. LensFlareSystem.prototype._isVisible = function () {
  96144. if (!this._isEnabled || !this._scene.activeCamera) {
  96145. return false;
  96146. }
  96147. var emitterPosition = this.getEmitterPosition();
  96148. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  96149. var distance = direction.length();
  96150. direction.normalize();
  96151. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  96152. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  96153. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  96154. };
  96155. /**
  96156. * @hidden
  96157. */
  96158. LensFlareSystem.prototype.render = function () {
  96159. if (!this._effect.isReady() || !this._scene.activeCamera) {
  96160. return false;
  96161. }
  96162. var engine = this._scene.getEngine();
  96163. var viewport = this._scene.activeCamera.viewport;
  96164. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  96165. // Position
  96166. if (!this.computeEffectivePosition(globalViewport)) {
  96167. return false;
  96168. }
  96169. // Visibility
  96170. if (!this._isVisible()) {
  96171. return false;
  96172. }
  96173. // Intensity
  96174. var awayX;
  96175. var awayY;
  96176. if (this._positionX < this.borderLimit + globalViewport.x) {
  96177. awayX = this.borderLimit + globalViewport.x - this._positionX;
  96178. }
  96179. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  96180. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  96181. }
  96182. else {
  96183. awayX = 0;
  96184. }
  96185. if (this._positionY < this.borderLimit + globalViewport.y) {
  96186. awayY = this.borderLimit + globalViewport.y - this._positionY;
  96187. }
  96188. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  96189. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  96190. }
  96191. else {
  96192. awayY = 0;
  96193. }
  96194. var away = (awayX > awayY) ? awayX : awayY;
  96195. away -= this.viewportBorder;
  96196. if (away > this.borderLimit) {
  96197. away = this.borderLimit;
  96198. }
  96199. var intensity = 1.0 - BABYLON.Scalar.Clamp(away / this.borderLimit, 0, 1);
  96200. if (intensity < 0) {
  96201. return false;
  96202. }
  96203. if (intensity > 1.0) {
  96204. intensity = 1.0;
  96205. }
  96206. if (this.viewportBorder > 0) {
  96207. globalViewport.x += this.viewportBorder;
  96208. globalViewport.y += this.viewportBorder;
  96209. globalViewport.width -= this.viewportBorder * 2;
  96210. globalViewport.height -= this.viewportBorder * 2;
  96211. this._positionX -= this.viewportBorder;
  96212. this._positionY -= this.viewportBorder;
  96213. }
  96214. // Position
  96215. var centerX = globalViewport.x + globalViewport.width / 2;
  96216. var centerY = globalViewport.y + globalViewport.height / 2;
  96217. var distX = centerX - this._positionX;
  96218. var distY = centerY - this._positionY;
  96219. // Effects
  96220. engine.enableEffect(this._effect);
  96221. engine.setState(false);
  96222. engine.setDepthBuffer(false);
  96223. // VBOs
  96224. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  96225. // Flares
  96226. for (var index = 0; index < this.lensFlares.length; index++) {
  96227. var flare = this.lensFlares[index];
  96228. engine.setAlphaMode(flare.alphaMode);
  96229. var x = centerX - (distX * flare.position);
  96230. var y = centerY - (distY * flare.position);
  96231. var cw = flare.size;
  96232. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  96233. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  96234. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  96235. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  96236. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  96237. // Texture
  96238. this._effect.setTexture("textureSampler", flare.texture);
  96239. // Color
  96240. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  96241. // Draw order
  96242. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  96243. }
  96244. engine.setDepthBuffer(true);
  96245. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  96246. return true;
  96247. };
  96248. /**
  96249. * Dispose and release the lens flare with its associated resources.
  96250. */
  96251. LensFlareSystem.prototype.dispose = function () {
  96252. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  96253. if (vertexBuffer) {
  96254. vertexBuffer.dispose();
  96255. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  96256. }
  96257. if (this._indexBuffer) {
  96258. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  96259. this._indexBuffer = null;
  96260. }
  96261. while (this.lensFlares.length) {
  96262. this.lensFlares[0].dispose();
  96263. }
  96264. // Remove from scene
  96265. var index = this._scene.lensFlareSystems.indexOf(this);
  96266. this._scene.lensFlareSystems.splice(index, 1);
  96267. };
  96268. /**
  96269. * Parse a lens flare system from a JSON repressentation
  96270. * @param parsedLensFlareSystem Define the JSON to parse
  96271. * @param scene Define the scene the parsed system should be instantiated in
  96272. * @param rootUrl Define the rootUrl of the load sequence to easily find a load relative dependencies such as textures
  96273. * @returns the parsed system
  96274. */
  96275. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  96276. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  96277. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  96278. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  96279. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  96280. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  96281. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  96282. var parsedFlare = parsedLensFlareSystem.flares[index];
  96283. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  96284. }
  96285. return lensFlareSystem;
  96286. };
  96287. /**
  96288. * Serialize the current Lens Flare System into a JSON representation.
  96289. * @returns the serialized JSON
  96290. */
  96291. LensFlareSystem.prototype.serialize = function () {
  96292. var serializationObject = {};
  96293. serializationObject.id = this.id;
  96294. serializationObject.name = this.name;
  96295. serializationObject.emitterId = this.getEmitter().id;
  96296. serializationObject.borderLimit = this.borderLimit;
  96297. serializationObject.flares = [];
  96298. for (var index = 0; index < this.lensFlares.length; index++) {
  96299. var flare = this.lensFlares[index];
  96300. serializationObject.flares.push({
  96301. size: flare.size,
  96302. position: flare.position,
  96303. color: flare.color.asArray(),
  96304. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  96305. });
  96306. }
  96307. return serializationObject;
  96308. };
  96309. return LensFlareSystem;
  96310. }());
  96311. BABYLON.LensFlareSystem = LensFlareSystem;
  96312. })(BABYLON || (BABYLON = {}));
  96313. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  96314. var BABYLON;
  96315. (function (BABYLON) {
  96316. /**
  96317. * This is a holder class for the physics joint created by the physics plugin
  96318. * It holds a set of functions to control the underlying joint
  96319. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  96320. */
  96321. var PhysicsJoint = /** @class */ (function () {
  96322. /**
  96323. * Initializes the physics joint
  96324. * @param type The type of the physics joint
  96325. * @param jointData The data for the physics joint
  96326. */
  96327. function PhysicsJoint(
  96328. /**
  96329. * The type of the physics joint
  96330. */
  96331. type,
  96332. /**
  96333. * The data for the physics joint
  96334. */
  96335. jointData) {
  96336. this.type = type;
  96337. this.jointData = jointData;
  96338. jointData.nativeParams = jointData.nativeParams || {};
  96339. }
  96340. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  96341. /**
  96342. * Gets the physics joint
  96343. */
  96344. get: function () {
  96345. return this._physicsJoint;
  96346. },
  96347. /**
  96348. * Sets the physics joint
  96349. */
  96350. set: function (newJoint) {
  96351. if (this._physicsJoint) {
  96352. //remove from the wolrd
  96353. }
  96354. this._physicsJoint = newJoint;
  96355. },
  96356. enumerable: true,
  96357. configurable: true
  96358. });
  96359. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  96360. /**
  96361. * Sets the physics plugin
  96362. */
  96363. set: function (physicsPlugin) {
  96364. this._physicsPlugin = physicsPlugin;
  96365. },
  96366. enumerable: true,
  96367. configurable: true
  96368. });
  96369. /**
  96370. * Execute a function that is physics-plugin specific.
  96371. * @param {Function} func the function that will be executed.
  96372. * It accepts two parameters: the physics world and the physics joint
  96373. */
  96374. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  96375. func(this._physicsPlugin.world, this._physicsJoint);
  96376. };
  96377. //TODO check if the native joints are the same
  96378. //Joint Types
  96379. /**
  96380. * Distance-Joint type
  96381. */
  96382. PhysicsJoint.DistanceJoint = 0;
  96383. /**
  96384. * Hinge-Joint type
  96385. */
  96386. PhysicsJoint.HingeJoint = 1;
  96387. /**
  96388. * Ball-and-Socket joint type
  96389. */
  96390. PhysicsJoint.BallAndSocketJoint = 2;
  96391. /**
  96392. * Wheel-Joint type
  96393. */
  96394. PhysicsJoint.WheelJoint = 3;
  96395. /**
  96396. * Slider-Joint type
  96397. */
  96398. PhysicsJoint.SliderJoint = 4;
  96399. //OIMO
  96400. /**
  96401. * Prismatic-Joint type
  96402. */
  96403. PhysicsJoint.PrismaticJoint = 5;
  96404. //
  96405. /**
  96406. * Universal-Joint type
  96407. * ENERGY FTW! (compare with this - @see http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  96408. */
  96409. PhysicsJoint.UniversalJoint = 6;
  96410. /**
  96411. * Hinge-Joint 2 type
  96412. */
  96413. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  96414. //Cannon
  96415. /**
  96416. * Point to Point Joint type. Similar to a Ball-Joint. Different in parameters
  96417. */
  96418. PhysicsJoint.PointToPointJoint = 8;
  96419. //Cannon only at the moment
  96420. /**
  96421. * Spring-Joint type
  96422. */
  96423. PhysicsJoint.SpringJoint = 9;
  96424. /**
  96425. * Lock-Joint type
  96426. */
  96427. PhysicsJoint.LockJoint = 10;
  96428. return PhysicsJoint;
  96429. }());
  96430. BABYLON.PhysicsJoint = PhysicsJoint;
  96431. /**
  96432. * A class representing a physics distance joint
  96433. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  96434. */
  96435. var DistanceJoint = /** @class */ (function (_super) {
  96436. __extends(DistanceJoint, _super);
  96437. /**
  96438. *
  96439. * @param jointData The data for the Distance-Joint
  96440. */
  96441. function DistanceJoint(jointData) {
  96442. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  96443. }
  96444. /**
  96445. * Update the predefined distance.
  96446. * @param maxDistance The maximum preferred distance
  96447. * @param minDistance The minimum preferred distance
  96448. */
  96449. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  96450. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  96451. };
  96452. return DistanceJoint;
  96453. }(PhysicsJoint));
  96454. BABYLON.DistanceJoint = DistanceJoint;
  96455. /**
  96456. * Represents a Motor-Enabled Joint
  96457. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  96458. */
  96459. var MotorEnabledJoint = /** @class */ (function (_super) {
  96460. __extends(MotorEnabledJoint, _super);
  96461. /**
  96462. * Initializes the Motor-Enabled Joint
  96463. * @param type The type of the joint
  96464. * @param jointData The physica joint data for the joint
  96465. */
  96466. function MotorEnabledJoint(type, jointData) {
  96467. return _super.call(this, type, jointData) || this;
  96468. }
  96469. /**
  96470. * Set the motor values.
  96471. * Attention, this function is plugin specific. Engines won't react 100% the same.
  96472. * @param force the force to apply
  96473. * @param maxForce max force for this motor.
  96474. */
  96475. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  96476. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  96477. };
  96478. /**
  96479. * Set the motor's limits.
  96480. * Attention, this function is plugin specific. Engines won't react 100% the same.
  96481. * @param upperLimit The upper limit of the motor
  96482. * @param lowerLimit The lower limit of the motor
  96483. */
  96484. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  96485. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  96486. };
  96487. return MotorEnabledJoint;
  96488. }(PhysicsJoint));
  96489. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  96490. /**
  96491. * This class represents a single physics Hinge-Joint
  96492. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  96493. */
  96494. var HingeJoint = /** @class */ (function (_super) {
  96495. __extends(HingeJoint, _super);
  96496. /**
  96497. * Initializes the Hinge-Joint
  96498. * @param jointData The joint data for the Hinge-Joint
  96499. */
  96500. function HingeJoint(jointData) {
  96501. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  96502. }
  96503. /**
  96504. * Set the motor values.
  96505. * Attention, this function is plugin specific. Engines won't react 100% the same.
  96506. * @param {number} force the force to apply
  96507. * @param {number} maxForce max force for this motor.
  96508. */
  96509. HingeJoint.prototype.setMotor = function (force, maxForce) {
  96510. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  96511. };
  96512. /**
  96513. * Set the motor's limits.
  96514. * Attention, this function is plugin specific. Engines won't react 100% the same.
  96515. * @param upperLimit The upper limit of the motor
  96516. * @param lowerLimit The lower limit of the motor
  96517. */
  96518. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  96519. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  96520. };
  96521. return HingeJoint;
  96522. }(MotorEnabledJoint));
  96523. BABYLON.HingeJoint = HingeJoint;
  96524. /**
  96525. * This class represents a dual hinge physics joint (same as wheel joint)
  96526. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  96527. */
  96528. var Hinge2Joint = /** @class */ (function (_super) {
  96529. __extends(Hinge2Joint, _super);
  96530. /**
  96531. * Initializes the Hinge2-Joint
  96532. * @param jointData The joint data for the Hinge2-Joint
  96533. */
  96534. function Hinge2Joint(jointData) {
  96535. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  96536. }
  96537. /**
  96538. * Set the motor values.
  96539. * Attention, this function is plugin specific. Engines won't react 100% the same.
  96540. * @param {number} force the force to apply
  96541. * @param {number} maxForce max force for this motor.
  96542. * @param {motorIndex} the motor's index, 0 or 1.
  96543. */
  96544. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  96545. if (motorIndex === void 0) { motorIndex = 0; }
  96546. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  96547. };
  96548. /**
  96549. * Set the motor limits.
  96550. * Attention, this function is plugin specific. Engines won't react 100% the same.
  96551. * @param {number} upperLimit the upper limit
  96552. * @param {number} lowerLimit lower limit
  96553. * @param {motorIndex} the motor's index, 0 or 1.
  96554. */
  96555. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  96556. if (motorIndex === void 0) { motorIndex = 0; }
  96557. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  96558. };
  96559. return Hinge2Joint;
  96560. }(MotorEnabledJoint));
  96561. BABYLON.Hinge2Joint = Hinge2Joint;
  96562. })(BABYLON || (BABYLON = {}));
  96563. //# sourceMappingURL=babylon.physicsJoint.js.map
  96564. var BABYLON;
  96565. (function (BABYLON) {
  96566. /**
  96567. * Represents a physics imposter
  96568. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  96569. */
  96570. var PhysicsImpostor = /** @class */ (function () {
  96571. /**
  96572. * Initializes the physics imposter
  96573. * @param object The physics-enabled object used as the physics imposter
  96574. * @param type The type of the physics imposter
  96575. * @param _options The options for the physics imposter
  96576. * @param _scene The Babylon scene
  96577. */
  96578. function PhysicsImpostor(
  96579. /**
  96580. * The physics-enabled object used as the physics imposter
  96581. */
  96582. object,
  96583. /**
  96584. * The type of the physics imposter
  96585. */
  96586. type, _options, _scene) {
  96587. if (_options === void 0) { _options = { mass: 0 }; }
  96588. var _this = this;
  96589. this.object = object;
  96590. this.type = type;
  96591. this._options = _options;
  96592. this._scene = _scene;
  96593. this._bodyUpdateRequired = false;
  96594. this._onBeforePhysicsStepCallbacks = new Array();
  96595. this._onAfterPhysicsStepCallbacks = new Array();
  96596. this._onPhysicsCollideCallbacks = [];
  96597. this._deltaPosition = BABYLON.Vector3.Zero();
  96598. this._isDisposed = false;
  96599. //temp variables for parent rotation calculations
  96600. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  96601. this._tmpQuat = new BABYLON.Quaternion();
  96602. this._tmpQuat2 = new BABYLON.Quaternion();
  96603. /**
  96604. * this function is executed by the physics engine.
  96605. */
  96606. this.beforeStep = function () {
  96607. if (!_this._physicsEngine) {
  96608. return;
  96609. }
  96610. _this.object.translate(_this._deltaPosition, -1);
  96611. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  96612. _this.object.computeWorldMatrix(false);
  96613. if (_this.object.parent && _this.object.rotationQuaternion) {
  96614. _this.getParentsRotation();
  96615. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  96616. }
  96617. else {
  96618. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  96619. }
  96620. if (!_this._options.disableBidirectionalTransformation) {
  96621. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  96622. }
  96623. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  96624. func(_this);
  96625. });
  96626. };
  96627. /**
  96628. * this function is executed by the physics engine
  96629. */
  96630. this.afterStep = function () {
  96631. if (!_this._physicsEngine) {
  96632. return;
  96633. }
  96634. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  96635. func(_this);
  96636. });
  96637. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  96638. // object has now its world rotation. needs to be converted to local.
  96639. if (_this.object.parent && _this.object.rotationQuaternion) {
  96640. _this.getParentsRotation();
  96641. _this._tmpQuat.conjugateInPlace();
  96642. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  96643. }
  96644. // take the position set and make it the absolute position of this object.
  96645. _this.object.setAbsolutePosition(_this.object.position);
  96646. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  96647. _this.object.translate(_this._deltaPosition, 1);
  96648. };
  96649. /**
  96650. * Legacy collision detection event support
  96651. */
  96652. this.onCollideEvent = null;
  96653. /**
  96654. * event and body object due to cannon's event-based architecture.
  96655. */
  96656. this.onCollide = function (e) {
  96657. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  96658. return;
  96659. }
  96660. if (!_this._physicsEngine) {
  96661. return;
  96662. }
  96663. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  96664. if (otherImpostor) {
  96665. // Legacy collision detection event support
  96666. if (_this.onCollideEvent) {
  96667. _this.onCollideEvent(_this, otherImpostor);
  96668. }
  96669. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  96670. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  96671. }).forEach(function (obj) {
  96672. obj.callback(_this, otherImpostor);
  96673. });
  96674. }
  96675. };
  96676. //sanity check!
  96677. if (!this.object) {
  96678. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  96679. return;
  96680. }
  96681. // Legacy support for old syntax.
  96682. if (!this._scene && object.getScene) {
  96683. this._scene = object.getScene();
  96684. }
  96685. if (!this._scene) {
  96686. return;
  96687. }
  96688. this._physicsEngine = this._scene.getPhysicsEngine();
  96689. if (!this._physicsEngine) {
  96690. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  96691. }
  96692. else {
  96693. //set the object's quaternion, if not set
  96694. if (!this.object.rotationQuaternion) {
  96695. if (this.object.rotation) {
  96696. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  96697. }
  96698. else {
  96699. this.object.rotationQuaternion = new BABYLON.Quaternion();
  96700. }
  96701. }
  96702. //default options params
  96703. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  96704. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  96705. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  96706. this._joints = [];
  96707. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  96708. if (!this.object.parent || this._options.ignoreParent) {
  96709. this._init();
  96710. }
  96711. else if (this.object.parent.physicsImpostor) {
  96712. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  96713. }
  96714. }
  96715. }
  96716. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  96717. /**
  96718. * Specifies if the physics imposter is disposed
  96719. */
  96720. get: function () {
  96721. return this._isDisposed;
  96722. },
  96723. enumerable: true,
  96724. configurable: true
  96725. });
  96726. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  96727. /**
  96728. * Gets the mass of the physics imposter
  96729. */
  96730. get: function () {
  96731. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  96732. },
  96733. set: function (value) {
  96734. this.setMass(value);
  96735. },
  96736. enumerable: true,
  96737. configurable: true
  96738. });
  96739. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  96740. /**
  96741. * Gets the coefficient of friction
  96742. */
  96743. get: function () {
  96744. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  96745. },
  96746. /**
  96747. * Sets the coefficient of friction
  96748. */
  96749. set: function (value) {
  96750. if (!this._physicsEngine) {
  96751. return;
  96752. }
  96753. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  96754. },
  96755. enumerable: true,
  96756. configurable: true
  96757. });
  96758. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  96759. /**
  96760. * Gets the coefficient of restitution
  96761. */
  96762. get: function () {
  96763. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  96764. },
  96765. /**
  96766. * Sets the coefficient of restitution
  96767. */
  96768. set: function (value) {
  96769. if (!this._physicsEngine) {
  96770. return;
  96771. }
  96772. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  96773. },
  96774. enumerable: true,
  96775. configurable: true
  96776. });
  96777. /**
  96778. * This function will completly initialize this impostor.
  96779. * It will create a new body - but only if this mesh has no parent.
  96780. * If it has, this impostor will not be used other than to define the impostor
  96781. * of the child mesh.
  96782. * @hidden
  96783. */
  96784. PhysicsImpostor.prototype._init = function () {
  96785. if (!this._physicsEngine) {
  96786. return;
  96787. }
  96788. this._physicsEngine.removeImpostor(this);
  96789. this.physicsBody = null;
  96790. this._parent = this._parent || this._getPhysicsParent();
  96791. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  96792. this._physicsEngine.addImpostor(this);
  96793. }
  96794. };
  96795. PhysicsImpostor.prototype._getPhysicsParent = function () {
  96796. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  96797. var parentMesh = this.object.parent;
  96798. return parentMesh.physicsImpostor;
  96799. }
  96800. return null;
  96801. };
  96802. /**
  96803. * Should a new body be generated.
  96804. * @returns boolean specifying if body initialization is required
  96805. */
  96806. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  96807. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  96808. };
  96809. /**
  96810. * Sets the updated scaling
  96811. * @param updated Specifies if the scaling is updated
  96812. */
  96813. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  96814. this.forceUpdate();
  96815. };
  96816. /**
  96817. * Force a regeneration of this or the parent's impostor's body.
  96818. * Use under cautious - This will remove all joints already implemented.
  96819. */
  96820. PhysicsImpostor.prototype.forceUpdate = function () {
  96821. this._init();
  96822. if (this.parent && !this._options.ignoreParent) {
  96823. this.parent.forceUpdate();
  96824. }
  96825. };
  96826. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  96827. /*public get mesh(): AbstractMesh {
  96828. return this._mesh;
  96829. }*/
  96830. /**
  96831. * Gets the body that holds this impostor. Either its own, or its parent.
  96832. */
  96833. get: function () {
  96834. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  96835. },
  96836. /**
  96837. * Set the physics body. Used mainly by the physics engine/plugin
  96838. */
  96839. set: function (physicsBody) {
  96840. if (this._physicsBody && this._physicsEngine) {
  96841. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  96842. }
  96843. this._physicsBody = physicsBody;
  96844. this.resetUpdateFlags();
  96845. },
  96846. enumerable: true,
  96847. configurable: true
  96848. });
  96849. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  96850. /**
  96851. * Get the parent of the physics imposter
  96852. * @returns Physics imposter or null
  96853. */
  96854. get: function () {
  96855. return !this._options.ignoreParent && this._parent ? this._parent : null;
  96856. },
  96857. /**
  96858. * Sets the parent of the physics imposter
  96859. */
  96860. set: function (value) {
  96861. this._parent = value;
  96862. },
  96863. enumerable: true,
  96864. configurable: true
  96865. });
  96866. /**
  96867. * Resets the update flags
  96868. */
  96869. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  96870. this._bodyUpdateRequired = false;
  96871. };
  96872. /**
  96873. * Gets the object extend size
  96874. * @returns the object extend size
  96875. */
  96876. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  96877. if (this.object.getBoundingInfo) {
  96878. var q = this.object.rotationQuaternion;
  96879. //reset rotation
  96880. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  96881. //calculate the world matrix with no rotation
  96882. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  96883. var boundingInfo = this.object.getBoundingInfo();
  96884. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  96885. //bring back the rotation
  96886. this.object.rotationQuaternion = q;
  96887. //calculate the world matrix with the new rotation
  96888. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  96889. return size;
  96890. }
  96891. else {
  96892. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  96893. }
  96894. };
  96895. /**
  96896. * Gets the object center
  96897. * @returns The object center
  96898. */
  96899. PhysicsImpostor.prototype.getObjectCenter = function () {
  96900. if (this.object.getBoundingInfo) {
  96901. var boundingInfo = this.object.getBoundingInfo();
  96902. return boundingInfo.boundingBox.centerWorld;
  96903. }
  96904. else {
  96905. return this.object.position;
  96906. }
  96907. };
  96908. /**
  96909. * Get a specific parametes from the options parameter
  96910. * @param paramName The object parameter name
  96911. * @returns The object parameter
  96912. */
  96913. PhysicsImpostor.prototype.getParam = function (paramName) {
  96914. return this._options[paramName];
  96915. };
  96916. /**
  96917. * Sets a specific parameter in the options given to the physics plugin
  96918. * @param paramName The parameter name
  96919. * @param value The value of the parameter
  96920. */
  96921. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  96922. this._options[paramName] = value;
  96923. this._bodyUpdateRequired = true;
  96924. };
  96925. /**
  96926. * Specifically change the body's mass option. Won't recreate the physics body object
  96927. * @param mass The mass of the physics imposter
  96928. */
  96929. PhysicsImpostor.prototype.setMass = function (mass) {
  96930. if (this.getParam("mass") !== mass) {
  96931. this.setParam("mass", mass);
  96932. }
  96933. if (this._physicsEngine) {
  96934. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  96935. }
  96936. };
  96937. /**
  96938. * Gets the linear velocity
  96939. * @returns linear velocity or null
  96940. */
  96941. PhysicsImpostor.prototype.getLinearVelocity = function () {
  96942. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  96943. };
  96944. /**
  96945. * Sets the linear velocity
  96946. * @param velocity linear velocity or null
  96947. */
  96948. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  96949. if (this._physicsEngine) {
  96950. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  96951. }
  96952. };
  96953. /**
  96954. * Gets the angular velocity
  96955. * @returns angular velocity or null
  96956. */
  96957. PhysicsImpostor.prototype.getAngularVelocity = function () {
  96958. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  96959. };
  96960. /**
  96961. * Sets the angular velocity
  96962. * @param velocity The velocity or null
  96963. */
  96964. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  96965. if (this._physicsEngine) {
  96966. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  96967. }
  96968. };
  96969. /**
  96970. * Execute a function with the physics plugin native code
  96971. * Provide a function the will have two variables - the world object and the physics body object
  96972. * @param func The function to execute with the physics plugin native code
  96973. */
  96974. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  96975. if (this._physicsEngine) {
  96976. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  96977. }
  96978. };
  96979. /**
  96980. * Register a function that will be executed before the physics world is stepping forward
  96981. * @param func The function to execute before the physics world is stepped forward
  96982. */
  96983. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  96984. this._onBeforePhysicsStepCallbacks.push(func);
  96985. };
  96986. /**
  96987. * Unregister a function that will be executed before the physics world is stepping forward
  96988. * @param func The function to execute before the physics world is stepped forward
  96989. */
  96990. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  96991. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  96992. if (index > -1) {
  96993. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  96994. }
  96995. else {
  96996. BABYLON.Tools.Warn("Function to remove was not found");
  96997. }
  96998. };
  96999. /**
  97000. * Register a function that will be executed after the physics step
  97001. * @param func The function to execute after physics step
  97002. */
  97003. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  97004. this._onAfterPhysicsStepCallbacks.push(func);
  97005. };
  97006. /**
  97007. * Unregisters a function that will be executed after the physics step
  97008. * @param func The function to execute after physics step
  97009. */
  97010. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  97011. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  97012. if (index > -1) {
  97013. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  97014. }
  97015. else {
  97016. BABYLON.Tools.Warn("Function to remove was not found");
  97017. }
  97018. };
  97019. /**
  97020. * register a function that will be executed when this impostor collides against a different body
  97021. * @param collideAgainst Physics imposter, or array of physics imposters to collide against
  97022. * @param func Callback that is executed on collision
  97023. */
  97024. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  97025. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  97026. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  97027. };
  97028. /**
  97029. * Unregisters the physics imposter on contact
  97030. * @param collideAgainst The physics object to collide against
  97031. * @param func Callback to execute on collision
  97032. */
  97033. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  97034. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  97035. var index = -1;
  97036. var found = this._onPhysicsCollideCallbacks.some(function (cbDef, idx) {
  97037. if (cbDef.callback === func && cbDef.otherImpostors.length === collidedAgainstList.length) {
  97038. // chcek the arrays match
  97039. var sameList = cbDef.otherImpostors.every(function (impostor) {
  97040. return collidedAgainstList.indexOf(impostor) > -1;
  97041. });
  97042. if (sameList) {
  97043. index = idx;
  97044. }
  97045. return sameList;
  97046. }
  97047. return false;
  97048. });
  97049. if (found) {
  97050. this._onPhysicsCollideCallbacks.splice(index, 1);
  97051. }
  97052. else {
  97053. BABYLON.Tools.Warn("Function to remove was not found");
  97054. }
  97055. };
  97056. /**
  97057. * Get the parent rotation
  97058. * @returns The parent rotation
  97059. */
  97060. PhysicsImpostor.prototype.getParentsRotation = function () {
  97061. var parent = this.object.parent;
  97062. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  97063. while (parent) {
  97064. if (parent.rotationQuaternion) {
  97065. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  97066. }
  97067. else {
  97068. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  97069. }
  97070. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  97071. parent = parent.parent;
  97072. }
  97073. return this._tmpQuat;
  97074. };
  97075. /**
  97076. * Apply a force
  97077. * @param force The force to apply
  97078. * @param contactPoint The contact point for the force
  97079. * @returns The physics imposter
  97080. */
  97081. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  97082. if (this._physicsEngine) {
  97083. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  97084. }
  97085. return this;
  97086. };
  97087. /**
  97088. * Apply an impulse
  97089. * @param force The impulse force
  97090. * @param contactPoint The contact point for the impulse force
  97091. * @returns The physics imposter
  97092. */
  97093. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  97094. if (this._physicsEngine) {
  97095. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  97096. }
  97097. return this;
  97098. };
  97099. /**
  97100. * A help function to create a joint
  97101. * @param otherImpostor A physics imposter used to create a joint
  97102. * @param jointType The type of joint
  97103. * @param jointData The data for the joint
  97104. * @returns The physics imposter
  97105. */
  97106. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  97107. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  97108. this.addJoint(otherImpostor, joint);
  97109. return this;
  97110. };
  97111. /**
  97112. * Add a joint to this impostor with a different impostor
  97113. * @param otherImpostor A physics imposter used to add a joint
  97114. * @param joint The joint to add
  97115. * @returns The physics imposter
  97116. */
  97117. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  97118. this._joints.push({
  97119. otherImpostor: otherImpostor,
  97120. joint: joint
  97121. });
  97122. if (this._physicsEngine) {
  97123. this._physicsEngine.addJoint(this, otherImpostor, joint);
  97124. }
  97125. return this;
  97126. };
  97127. /**
  97128. * Will keep this body still, in a sleep mode.
  97129. * @returns the physics imposter
  97130. */
  97131. PhysicsImpostor.prototype.sleep = function () {
  97132. if (this._physicsEngine) {
  97133. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  97134. }
  97135. return this;
  97136. };
  97137. /**
  97138. * Wake the body up.
  97139. * @returns The physics imposter
  97140. */
  97141. PhysicsImpostor.prototype.wakeUp = function () {
  97142. if (this._physicsEngine) {
  97143. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  97144. }
  97145. return this;
  97146. };
  97147. /**
  97148. * Clones the physics imposter
  97149. * @param newObject The physics imposter clones to this physics-enabled object
  97150. * @returns A nullable physics imposter
  97151. */
  97152. PhysicsImpostor.prototype.clone = function (newObject) {
  97153. if (!newObject) {
  97154. return null;
  97155. }
  97156. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  97157. };
  97158. /**
  97159. * Disposes the physics imposter
  97160. */
  97161. PhysicsImpostor.prototype.dispose = function ( /*disposeChildren: boolean = true*/) {
  97162. var _this = this;
  97163. //no dispose if no physics engine is available.
  97164. if (!this._physicsEngine) {
  97165. return;
  97166. }
  97167. this._joints.forEach(function (j) {
  97168. if (_this._physicsEngine) {
  97169. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  97170. }
  97171. });
  97172. //dispose the physics body
  97173. this._physicsEngine.removeImpostor(this);
  97174. if (this.parent) {
  97175. this.parent.forceUpdate();
  97176. }
  97177. else {
  97178. /*this._object.getChildMeshes().forEach(function(mesh) {
  97179. if (mesh.physicsImpostor) {
  97180. if (disposeChildren) {
  97181. mesh.physicsImpostor.dispose();
  97182. mesh.physicsImpostor = null;
  97183. }
  97184. }
  97185. })*/
  97186. }
  97187. this._isDisposed = true;
  97188. };
  97189. /**
  97190. * Sets the delta position
  97191. * @param position The delta position amount
  97192. */
  97193. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  97194. this._deltaPosition.copyFrom(position);
  97195. };
  97196. /**
  97197. * Sets the delta rotation
  97198. * @param rotation The delta rotation amount
  97199. */
  97200. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  97201. if (!this._deltaRotation) {
  97202. this._deltaRotation = new BABYLON.Quaternion();
  97203. }
  97204. this._deltaRotation.copyFrom(rotation);
  97205. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  97206. };
  97207. /**
  97208. * Gets the box size of the physics imposter and stores the result in the input parameter
  97209. * @param result Stores the box size
  97210. * @returns The physics imposter
  97211. */
  97212. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  97213. if (this._physicsEngine) {
  97214. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  97215. }
  97216. return this;
  97217. };
  97218. /**
  97219. * Gets the radius of the physics imposter
  97220. * @returns Radius of the physics imposter
  97221. */
  97222. PhysicsImpostor.prototype.getRadius = function () {
  97223. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  97224. };
  97225. /**
  97226. * Sync a bone with this impostor
  97227. * @param bone The bone to sync to the impostor.
  97228. * @param boneMesh The mesh that the bone is influencing.
  97229. * @param jointPivot The pivot of the joint / bone in local space.
  97230. * @param distToJoint Optional distance from the impostor to the joint.
  97231. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  97232. */
  97233. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  97234. var tempVec = PhysicsImpostor._tmpVecs[0];
  97235. var mesh = this.object;
  97236. if (mesh.rotationQuaternion) {
  97237. if (adjustRotation) {
  97238. var tempQuat = PhysicsImpostor._tmpQuat;
  97239. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  97240. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  97241. }
  97242. else {
  97243. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  97244. }
  97245. }
  97246. tempVec.x = 0;
  97247. tempVec.y = 0;
  97248. tempVec.z = 0;
  97249. if (jointPivot) {
  97250. tempVec.x = jointPivot.x;
  97251. tempVec.y = jointPivot.y;
  97252. tempVec.z = jointPivot.z;
  97253. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  97254. if (distToJoint === undefined || distToJoint === null) {
  97255. distToJoint = jointPivot.length();
  97256. }
  97257. tempVec.x *= distToJoint;
  97258. tempVec.y *= distToJoint;
  97259. tempVec.z *= distToJoint;
  97260. }
  97261. if (bone.getParent()) {
  97262. tempVec.addInPlace(mesh.getAbsolutePosition());
  97263. bone.setAbsolutePosition(tempVec, boneMesh);
  97264. }
  97265. else {
  97266. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  97267. boneMesh.position.x -= tempVec.x;
  97268. boneMesh.position.y -= tempVec.y;
  97269. boneMesh.position.z -= tempVec.z;
  97270. }
  97271. };
  97272. /**
  97273. * Sync impostor to a bone
  97274. * @param bone The bone that the impostor will be synced to.
  97275. * @param boneMesh The mesh that the bone is influencing.
  97276. * @param jointPivot The pivot of the joint / bone in local space.
  97277. * @param distToJoint Optional distance from the impostor to the joint.
  97278. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  97279. * @param boneAxis Optional vector3 axis the bone is aligned with
  97280. */
  97281. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  97282. var mesh = this.object;
  97283. if (mesh.rotationQuaternion) {
  97284. if (adjustRotation) {
  97285. var tempQuat = PhysicsImpostor._tmpQuat;
  97286. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  97287. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  97288. }
  97289. else {
  97290. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  97291. }
  97292. }
  97293. var pos = PhysicsImpostor._tmpVecs[0];
  97294. var boneDir = PhysicsImpostor._tmpVecs[1];
  97295. if (!boneAxis) {
  97296. boneAxis = PhysicsImpostor._tmpVecs[2];
  97297. boneAxis.x = 0;
  97298. boneAxis.y = 1;
  97299. boneAxis.z = 0;
  97300. }
  97301. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  97302. bone.getAbsolutePositionToRef(boneMesh, pos);
  97303. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  97304. distToJoint = jointPivot.length();
  97305. }
  97306. if (distToJoint !== undefined && distToJoint !== null) {
  97307. pos.x += boneDir.x * distToJoint;
  97308. pos.y += boneDir.y * distToJoint;
  97309. pos.z += boneDir.z * distToJoint;
  97310. }
  97311. mesh.setAbsolutePosition(pos);
  97312. };
  97313. /**
  97314. * The default object size of the imposter
  97315. */
  97316. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  97317. /**
  97318. * The identity quaternion of the imposter
  97319. */
  97320. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  97321. PhysicsImpostor._tmpVecs = BABYLON.Tools.BuildArray(3, BABYLON.Vector3.Zero);
  97322. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  97323. //Impostor types
  97324. /**
  97325. * No-Imposter type
  97326. */
  97327. PhysicsImpostor.NoImpostor = 0;
  97328. /**
  97329. * Sphere-Imposter type
  97330. */
  97331. PhysicsImpostor.SphereImpostor = 1;
  97332. /**
  97333. * Box-Imposter type
  97334. */
  97335. PhysicsImpostor.BoxImpostor = 2;
  97336. /**
  97337. * Plane-Imposter type
  97338. */
  97339. PhysicsImpostor.PlaneImpostor = 3;
  97340. /**
  97341. * Mesh-imposter type
  97342. */
  97343. PhysicsImpostor.MeshImpostor = 4;
  97344. /**
  97345. * Cylinder-Imposter type
  97346. */
  97347. PhysicsImpostor.CylinderImpostor = 7;
  97348. /**
  97349. * Particle-Imposter type
  97350. */
  97351. PhysicsImpostor.ParticleImpostor = 8;
  97352. /**
  97353. * Heightmap-Imposter type
  97354. */
  97355. PhysicsImpostor.HeightmapImpostor = 9;
  97356. return PhysicsImpostor;
  97357. }());
  97358. BABYLON.PhysicsImpostor = PhysicsImpostor;
  97359. })(BABYLON || (BABYLON = {}));
  97360. //# sourceMappingURL=babylon.physicsImpostor.js.map
  97361. var BABYLON;
  97362. (function (BABYLON) {
  97363. /**
  97364. * Class used to control physics engine
  97365. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  97366. */
  97367. var PhysicsEngine = /** @class */ (function () {
  97368. /**
  97369. * Creates a new Physics Engine
  97370. * @param gravity defines the gravity vector used by the simulation
  97371. * @param _physicsPlugin defines the plugin to use (CannonJS by default)
  97372. */
  97373. function PhysicsEngine(gravity, _physicsPlugin) {
  97374. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  97375. this._physicsPlugin = _physicsPlugin;
  97376. this._impostors = [];
  97377. this._joints = [];
  97378. if (!this._physicsPlugin.isSupported()) {
  97379. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  97380. + "Please make sure it is included.");
  97381. }
  97382. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  97383. this.setGravity(gravity);
  97384. this.setTimeStep();
  97385. }
  97386. /**
  97387. * Sets the gravity vector used by the simulation
  97388. * @param gravity defines the gravity vector to use
  97389. */
  97390. PhysicsEngine.prototype.setGravity = function (gravity) {
  97391. this.gravity = gravity;
  97392. this._physicsPlugin.setGravity(this.gravity);
  97393. };
  97394. /**
  97395. * Set the time step of the physics engine.
  97396. * Default is 1/60.
  97397. * To slow it down, enter 1/600 for example.
  97398. * To speed it up, 1/30
  97399. * @param newTimeStep defines the new timestep to apply to this world.
  97400. */
  97401. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  97402. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  97403. this._physicsPlugin.setTimeStep(newTimeStep);
  97404. };
  97405. /**
  97406. * Get the time step of the physics engine.
  97407. * @returns the current time step
  97408. */
  97409. PhysicsEngine.prototype.getTimeStep = function () {
  97410. return this._physicsPlugin.getTimeStep();
  97411. };
  97412. /**
  97413. * Release all resources
  97414. */
  97415. PhysicsEngine.prototype.dispose = function () {
  97416. this._impostors.forEach(function (impostor) {
  97417. impostor.dispose();
  97418. });
  97419. this._physicsPlugin.dispose();
  97420. };
  97421. /**
  97422. * Gets the name of the current physics plugin
  97423. * @returns the name of the plugin
  97424. */
  97425. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  97426. return this._physicsPlugin.name;
  97427. };
  97428. /**
  97429. * Adding a new impostor for the impostor tracking.
  97430. * This will be done by the impostor itself.
  97431. * @param impostor the impostor to add
  97432. */
  97433. PhysicsEngine.prototype.addImpostor = function (impostor) {
  97434. impostor.uniqueId = this._impostors.push(impostor);
  97435. //if no parent, generate the body
  97436. if (!impostor.parent) {
  97437. this._physicsPlugin.generatePhysicsBody(impostor);
  97438. }
  97439. };
  97440. /**
  97441. * Remove an impostor from the engine.
  97442. * This impostor and its mesh will not longer be updated by the physics engine.
  97443. * @param impostor the impostor to remove
  97444. */
  97445. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  97446. var index = this._impostors.indexOf(impostor);
  97447. if (index > -1) {
  97448. var removed = this._impostors.splice(index, 1);
  97449. //Is it needed?
  97450. if (removed.length) {
  97451. //this will also remove it from the world.
  97452. removed[0].physicsBody = null;
  97453. }
  97454. }
  97455. };
  97456. /**
  97457. * Add a joint to the physics engine
  97458. * @param mainImpostor defines the main impostor to which the joint is added.
  97459. * @param connectedImpostor defines the impostor that is connected to the main impostor using this joint
  97460. * @param joint defines the joint that will connect both impostors.
  97461. */
  97462. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  97463. var impostorJoint = {
  97464. mainImpostor: mainImpostor,
  97465. connectedImpostor: connectedImpostor,
  97466. joint: joint
  97467. };
  97468. joint.physicsPlugin = this._physicsPlugin;
  97469. this._joints.push(impostorJoint);
  97470. this._physicsPlugin.generateJoint(impostorJoint);
  97471. };
  97472. /**
  97473. * Removes a joint from the simulation
  97474. * @param mainImpostor defines the impostor used with the joint
  97475. * @param connectedImpostor defines the other impostor connected to the main one by the joint
  97476. * @param joint defines the joint to remove
  97477. */
  97478. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  97479. var matchingJoints = this._joints.filter(function (impostorJoint) {
  97480. return (impostorJoint.connectedImpostor === connectedImpostor
  97481. && impostorJoint.joint === joint
  97482. && impostorJoint.mainImpostor === mainImpostor);
  97483. });
  97484. if (matchingJoints.length) {
  97485. this._physicsPlugin.removeJoint(matchingJoints[0]);
  97486. //TODO remove it from the list as well
  97487. }
  97488. };
  97489. /**
  97490. * Called by the scene. No need to call it.
  97491. * @param delta defines the timespam between frames
  97492. */
  97493. PhysicsEngine.prototype._step = function (delta) {
  97494. var _this = this;
  97495. //check if any mesh has no body / requires an update
  97496. this._impostors.forEach(function (impostor) {
  97497. if (impostor.isBodyInitRequired()) {
  97498. _this._physicsPlugin.generatePhysicsBody(impostor);
  97499. }
  97500. });
  97501. if (delta > 0.1) {
  97502. delta = 0.1;
  97503. }
  97504. else if (delta <= 0) {
  97505. delta = 1.0 / 60.0;
  97506. }
  97507. this._physicsPlugin.executeStep(delta, this._impostors);
  97508. };
  97509. /**
  97510. * Gets the current plugin used to run the simulation
  97511. * @returns current plugin
  97512. */
  97513. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  97514. return this._physicsPlugin;
  97515. };
  97516. /**
  97517. * Gets the list of physic impostors
  97518. * @returns an array of PhysicsImpostor
  97519. */
  97520. PhysicsEngine.prototype.getImpostors = function () {
  97521. return this._impostors;
  97522. };
  97523. /**
  97524. * Gets the impostor for a physics enabled object
  97525. * @param object defines the object impersonated by the impostor
  97526. * @returns the PhysicsImpostor or null if not found
  97527. */
  97528. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  97529. for (var i = 0; i < this._impostors.length; ++i) {
  97530. if (this._impostors[i].object === object) {
  97531. return this._impostors[i];
  97532. }
  97533. }
  97534. return null;
  97535. };
  97536. /**
  97537. * Gets the impostor for a physics body object
  97538. * @param body defines physics body used by the impostor
  97539. * @returns the PhysicsImpostor or null if not found
  97540. */
  97541. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  97542. for (var i = 0; i < this._impostors.length; ++i) {
  97543. if (this._impostors[i].physicsBody === body) {
  97544. return this._impostors[i];
  97545. }
  97546. }
  97547. return null;
  97548. };
  97549. /**
  97550. * Global value used to control the smallest number supported by the simulation
  97551. */
  97552. PhysicsEngine.Epsilon = 0.001;
  97553. return PhysicsEngine;
  97554. }());
  97555. BABYLON.PhysicsEngine = PhysicsEngine;
  97556. })(BABYLON || (BABYLON = {}));
  97557. //# sourceMappingURL=babylon.physicsEngine.js.map
  97558. var BABYLON;
  97559. (function (BABYLON) {
  97560. /**
  97561. * A helper for physics simulations
  97562. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  97563. */
  97564. var PhysicsHelper = /** @class */ (function () {
  97565. /**
  97566. * Initializes the Physics helper
  97567. * @param scene Babylon.js scene
  97568. */
  97569. function PhysicsHelper(scene) {
  97570. this._scene = scene;
  97571. this._physicsEngine = this._scene.getPhysicsEngine();
  97572. if (!this._physicsEngine) {
  97573. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  97574. }
  97575. }
  97576. /**
  97577. * Applies a radial explosion impulse
  97578. * @param origin the origin of the explosion
  97579. * @param radius the explosion radius
  97580. * @param strength the explosion strength
  97581. * @param falloff possible options: Constant & Linear. Defaults to Constant
  97582. * @returns A physics radial explosion event, or null
  97583. */
  97584. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  97585. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  97586. if (!this._physicsEngine) {
  97587. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  97588. return null;
  97589. }
  97590. var impostors = this._physicsEngine.getImpostors();
  97591. if (impostors.length === 0) {
  97592. return null;
  97593. }
  97594. var event = new PhysicsRadialExplosionEvent(this._scene);
  97595. impostors.forEach(function (impostor) {
  97596. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  97597. if (!impostorForceAndContactPoint) {
  97598. return;
  97599. }
  97600. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  97601. });
  97602. event.dispose(false);
  97603. return event;
  97604. };
  97605. /**
  97606. * Applies a radial explosion force
  97607. * @param origin the origin of the explosion
  97608. * @param radius the explosion radius
  97609. * @param strength the explosion strength
  97610. * @param falloff possible options: Constant & Linear. Defaults to Constant
  97611. * @returns A physics radial explosion event, or null
  97612. */
  97613. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  97614. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  97615. if (!this._physicsEngine) {
  97616. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  97617. return null;
  97618. }
  97619. var impostors = this._physicsEngine.getImpostors();
  97620. if (impostors.length === 0) {
  97621. return null;
  97622. }
  97623. var event = new PhysicsRadialExplosionEvent(this._scene);
  97624. impostors.forEach(function (impostor) {
  97625. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  97626. if (!impostorForceAndContactPoint) {
  97627. return;
  97628. }
  97629. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  97630. });
  97631. event.dispose(false);
  97632. return event;
  97633. };
  97634. /**
  97635. * Creates a gravitational field
  97636. * @param origin the origin of the explosion
  97637. * @param radius the explosion radius
  97638. * @param strength the explosion strength
  97639. * @param falloff possible options: Constant & Linear. Defaults to Constant
  97640. * @returns A physics gravitational field event, or null
  97641. */
  97642. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  97643. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  97644. if (!this._physicsEngine) {
  97645. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  97646. return null;
  97647. }
  97648. var impostors = this._physicsEngine.getImpostors();
  97649. if (impostors.length === 0) {
  97650. return null;
  97651. }
  97652. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  97653. event.dispose(false);
  97654. return event;
  97655. };
  97656. /**
  97657. * Creates a physics updraft event
  97658. * @param origin the origin of the updraft
  97659. * @param radius the radius of the updraft
  97660. * @param strength the strength of the updraft
  97661. * @param height the height of the updraft
  97662. * @param updraftMode possible options: Center & Perpendicular. Defaults to Center
  97663. * @returns A physics updraft event, or null
  97664. */
  97665. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  97666. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  97667. if (!this._physicsEngine) {
  97668. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  97669. return null;
  97670. }
  97671. if (this._physicsEngine.getImpostors().length === 0) {
  97672. return null;
  97673. }
  97674. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  97675. event.dispose(false);
  97676. return event;
  97677. };
  97678. /**
  97679. * Creates a physics vortex event
  97680. * @param origin the of the vortex
  97681. * @param radius the radius of the vortex
  97682. * @param strength the strength of the vortex
  97683. * @param height the height of the vortex
  97684. * @returns a Physics vortex event, or null
  97685. * A physics vortex event or null
  97686. */
  97687. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  97688. if (!this._physicsEngine) {
  97689. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  97690. return null;
  97691. }
  97692. if (this._physicsEngine.getImpostors().length === 0) {
  97693. return null;
  97694. }
  97695. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  97696. event.dispose(false);
  97697. return event;
  97698. };
  97699. return PhysicsHelper;
  97700. }());
  97701. BABYLON.PhysicsHelper = PhysicsHelper;
  97702. /**
  97703. * Represents a physics radial explosion event
  97704. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  97705. */
  97706. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  97707. /**
  97708. * Initializes a radial explosioin event
  97709. * @param scene BabylonJS scene
  97710. */
  97711. function PhysicsRadialExplosionEvent(scene) {
  97712. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  97713. this._rays = [];
  97714. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  97715. this._scene = scene;
  97716. }
  97717. /**
  97718. * Returns the data related to the radial explosion event (sphere & rays).
  97719. * @returns The radial explosion event data
  97720. */
  97721. PhysicsRadialExplosionEvent.prototype.getData = function () {
  97722. this._dataFetched = true;
  97723. return {
  97724. sphere: this._sphere,
  97725. rays: this._rays,
  97726. };
  97727. };
  97728. /**
  97729. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  97730. * @param impostor A physics imposter
  97731. * @param origin the origin of the explosion
  97732. * @param radius the explosion radius
  97733. * @param strength the explosion strength
  97734. * @param falloff possible options: Constant & Linear
  97735. * @returns {Nullable<PhysicsForceAndContactPoint>} A physics force and contact point, or null
  97736. */
  97737. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  97738. if (impostor.mass === 0) {
  97739. return null;
  97740. }
  97741. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  97742. return null;
  97743. }
  97744. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  97745. return null;
  97746. }
  97747. var impostorObjectCenter = impostor.getObjectCenter();
  97748. var direction = impostorObjectCenter.subtract(origin);
  97749. var ray = new BABYLON.Ray(origin, direction, radius);
  97750. this._rays.push(ray);
  97751. var hit = ray.intersectsMesh(impostor.object);
  97752. var contactPoint = hit.pickedPoint;
  97753. if (!contactPoint) {
  97754. return null;
  97755. }
  97756. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  97757. if (distanceFromOrigin > radius) {
  97758. return null;
  97759. }
  97760. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  97761. ? strength
  97762. : strength * (1 - (distanceFromOrigin / radius));
  97763. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  97764. return { force: force, contactPoint: contactPoint };
  97765. };
  97766. /**
  97767. * Disposes the sphere.
  97768. * @param force Specifies if the sphere should be disposed by force
  97769. */
  97770. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  97771. var _this = this;
  97772. if (force === void 0) { force = true; }
  97773. if (force) {
  97774. this._sphere.dispose();
  97775. }
  97776. else {
  97777. setTimeout(function () {
  97778. if (!_this._dataFetched) {
  97779. _this._sphere.dispose();
  97780. }
  97781. }, 0);
  97782. }
  97783. };
  97784. /*** Helpers ***/
  97785. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  97786. if (!this._sphere) {
  97787. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  97788. this._sphere.isVisible = false;
  97789. }
  97790. };
  97791. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  97792. var impostorObject = impostor.object;
  97793. this._prepareSphere();
  97794. this._sphere.position = origin;
  97795. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  97796. this._sphere._updateBoundingInfo();
  97797. this._sphere.computeWorldMatrix(true);
  97798. return this._sphere.intersectsMesh(impostorObject, true);
  97799. };
  97800. return PhysicsRadialExplosionEvent;
  97801. }());
  97802. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  97803. /**
  97804. * Represents a gravitational field event
  97805. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  97806. */
  97807. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  97808. /**
  97809. * Initializes the physics gravitational field event
  97810. * @param physicsHelper A physics helper
  97811. * @param scene BabylonJS scene
  97812. * @param origin The origin position of the gravitational field event
  97813. * @param radius The radius of the gravitational field event
  97814. * @param strength The strength of the gravitational field event
  97815. * @param falloff The falloff for the gravitational field event
  97816. */
  97817. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  97818. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  97819. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  97820. this._physicsHelper = physicsHelper;
  97821. this._scene = scene;
  97822. this._origin = origin;
  97823. this._radius = radius;
  97824. this._strength = strength;
  97825. this._falloff = falloff;
  97826. this._tickCallback = this._tick.bind(this);
  97827. }
  97828. /**
  97829. * Returns the data related to the gravitational field event (sphere).
  97830. * @returns A gravitational field event
  97831. */
  97832. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  97833. this._dataFetched = true;
  97834. return {
  97835. sphere: this._sphere,
  97836. };
  97837. };
  97838. /**
  97839. * Enables the gravitational field.
  97840. */
  97841. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  97842. this._tickCallback.call(this);
  97843. this._scene.registerBeforeRender(this._tickCallback);
  97844. };
  97845. /**
  97846. * Disables the gravitational field.
  97847. */
  97848. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  97849. this._scene.unregisterBeforeRender(this._tickCallback);
  97850. };
  97851. /**
  97852. * Disposes the sphere.
  97853. * @param force The force to dispose from the gravitational field event
  97854. */
  97855. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  97856. var _this = this;
  97857. if (force === void 0) { force = true; }
  97858. if (force) {
  97859. this._sphere.dispose();
  97860. }
  97861. else {
  97862. setTimeout(function () {
  97863. if (!_this._dataFetched) {
  97864. _this._sphere.dispose();
  97865. }
  97866. }, 0);
  97867. }
  97868. };
  97869. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  97870. // Since the params won't change, we fetch the event only once
  97871. if (this._sphere) {
  97872. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  97873. }
  97874. else {
  97875. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  97876. if (radialExplosionEvent) {
  97877. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  97878. }
  97879. }
  97880. };
  97881. return PhysicsGravitationalFieldEvent;
  97882. }());
  97883. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  97884. /**
  97885. * Represents a physics updraft event
  97886. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  97887. */
  97888. var PhysicsUpdraftEvent = /** @class */ (function () {
  97889. /**
  97890. * Initializes the physics updraft event
  97891. * @param _scene BabylonJS scene
  97892. * @param _origin The origin position of the updraft
  97893. * @param _radius The radius of the updraft
  97894. * @param _strength The strength of the updraft
  97895. * @param _height The height of the updraft
  97896. * @param _updraftMode The mode of the updraft
  97897. */
  97898. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  97899. this._scene = _scene;
  97900. this._origin = _origin;
  97901. this._radius = _radius;
  97902. this._strength = _strength;
  97903. this._height = _height;
  97904. this._updraftMode = _updraftMode;
  97905. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  97906. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  97907. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  97908. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  97909. this._physicsEngine = this._scene.getPhysicsEngine();
  97910. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  97911. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  97912. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  97913. this._originDirection = this._origin.subtract(this._originTop).normalize();
  97914. }
  97915. this._tickCallback = this._tick.bind(this);
  97916. }
  97917. /**
  97918. * Returns the data related to the updraft event (cylinder).
  97919. * @returns A physics updraft event
  97920. */
  97921. PhysicsUpdraftEvent.prototype.getData = function () {
  97922. this._dataFetched = true;
  97923. return {
  97924. cylinder: this._cylinder,
  97925. };
  97926. };
  97927. /**
  97928. * Enables the updraft.
  97929. */
  97930. PhysicsUpdraftEvent.prototype.enable = function () {
  97931. this._tickCallback.call(this);
  97932. this._scene.registerBeforeRender(this._tickCallback);
  97933. };
  97934. /**
  97935. * Disables the cortex.
  97936. */
  97937. PhysicsUpdraftEvent.prototype.disable = function () {
  97938. this._scene.unregisterBeforeRender(this._tickCallback);
  97939. };
  97940. /**
  97941. * Disposes the sphere.
  97942. * @param force Specifies if the updraft should be disposed by force
  97943. */
  97944. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  97945. var _this = this;
  97946. if (force === void 0) { force = true; }
  97947. if (force) {
  97948. this._cylinder.dispose();
  97949. }
  97950. else {
  97951. setTimeout(function () {
  97952. if (!_this._dataFetched) {
  97953. _this._cylinder.dispose();
  97954. }
  97955. }, 0);
  97956. }
  97957. };
  97958. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  97959. if (impostor.mass === 0) {
  97960. return null;
  97961. }
  97962. if (!this._intersectsWithCylinder(impostor)) {
  97963. return null;
  97964. }
  97965. var impostorObjectCenter = impostor.getObjectCenter();
  97966. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  97967. var direction = this._originDirection;
  97968. }
  97969. else {
  97970. var direction = impostorObjectCenter.subtract(this._originTop);
  97971. }
  97972. var multiplier = this._strength * -1;
  97973. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  97974. return { force: force, contactPoint: impostorObjectCenter };
  97975. };
  97976. PhysicsUpdraftEvent.prototype._tick = function () {
  97977. var _this = this;
  97978. this._physicsEngine.getImpostors().forEach(function (impostor) {
  97979. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  97980. if (!impostorForceAndContactPoint) {
  97981. return;
  97982. }
  97983. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  97984. });
  97985. };
  97986. /*** Helpers ***/
  97987. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  97988. if (!this._cylinder) {
  97989. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  97990. height: this._height,
  97991. diameter: this._radius * 2,
  97992. }, this._scene);
  97993. this._cylinder.isVisible = false;
  97994. }
  97995. };
  97996. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  97997. var impostorObject = impostor.object;
  97998. this._prepareCylinder();
  97999. this._cylinder.position = this._cylinderPosition;
  98000. return this._cylinder.intersectsMesh(impostorObject, true);
  98001. };
  98002. return PhysicsUpdraftEvent;
  98003. }());
  98004. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  98005. /**
  98006. * Represents a physics vortex event
  98007. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  98008. */
  98009. var PhysicsVortexEvent = /** @class */ (function () {
  98010. /**
  98011. * Initializes the physics vortex event
  98012. * @param _scene The BabylonJS scene
  98013. * @param _origin The origin position of the vortex
  98014. * @param _radius The radius of the vortex
  98015. * @param _strength The strength of the vortex
  98016. * @param _height The height of the vortex
  98017. */
  98018. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  98019. this._scene = _scene;
  98020. this._origin = _origin;
  98021. this._radius = _radius;
  98022. this._strength = _strength;
  98023. this._height = _height;
  98024. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  98025. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  98026. this._updraftMultiplier = 0.02;
  98027. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  98028. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  98029. this._physicsEngine = this._scene.getPhysicsEngine();
  98030. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  98031. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  98032. this._tickCallback = this._tick.bind(this);
  98033. }
  98034. /**
  98035. * Returns the data related to the vortex event (cylinder).
  98036. * @returns The physics vortex event data
  98037. */
  98038. PhysicsVortexEvent.prototype.getData = function () {
  98039. this._dataFetched = true;
  98040. return {
  98041. cylinder: this._cylinder,
  98042. };
  98043. };
  98044. /**
  98045. * Enables the vortex.
  98046. */
  98047. PhysicsVortexEvent.prototype.enable = function () {
  98048. this._tickCallback.call(this);
  98049. this._scene.registerBeforeRender(this._tickCallback);
  98050. };
  98051. /**
  98052. * Disables the cortex.
  98053. */
  98054. PhysicsVortexEvent.prototype.disable = function () {
  98055. this._scene.unregisterBeforeRender(this._tickCallback);
  98056. };
  98057. /**
  98058. * Disposes the sphere.
  98059. * @param force
  98060. */
  98061. PhysicsVortexEvent.prototype.dispose = function (force) {
  98062. var _this = this;
  98063. if (force === void 0) { force = true; }
  98064. if (force) {
  98065. this._cylinder.dispose();
  98066. }
  98067. else {
  98068. setTimeout(function () {
  98069. if (!_this._dataFetched) {
  98070. _this._cylinder.dispose();
  98071. }
  98072. }, 0);
  98073. }
  98074. };
  98075. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  98076. if (impostor.mass === 0) {
  98077. return null;
  98078. }
  98079. if (!this._intersectsWithCylinder(impostor)) {
  98080. return null;
  98081. }
  98082. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  98083. return null;
  98084. }
  98085. var impostorObjectCenter = impostor.getObjectCenter();
  98086. 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)
  98087. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  98088. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  98089. var hit = ray.intersectsMesh(impostor.object);
  98090. var contactPoint = hit.pickedPoint;
  98091. if (!contactPoint) {
  98092. return null;
  98093. }
  98094. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  98095. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  98096. var directionToOrigin = contactPoint.normalize();
  98097. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  98098. directionToOrigin = directionToOrigin.negate();
  98099. }
  98100. // TODO: find a more physically based solution
  98101. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  98102. var forceX = directionToOrigin.x * this._strength / 8;
  98103. var forceY = directionToOrigin.y * this._updraftMultiplier;
  98104. var forceZ = directionToOrigin.z * this._strength / 8;
  98105. }
  98106. else {
  98107. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  98108. var forceY = this._originTop.y * this._updraftMultiplier;
  98109. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  98110. }
  98111. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  98112. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  98113. return { force: force, contactPoint: impostorObjectCenter };
  98114. };
  98115. PhysicsVortexEvent.prototype._tick = function () {
  98116. var _this = this;
  98117. this._physicsEngine.getImpostors().forEach(function (impostor) {
  98118. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  98119. if (!impostorForceAndContactPoint) {
  98120. return;
  98121. }
  98122. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  98123. });
  98124. };
  98125. /*** Helpers ***/
  98126. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  98127. if (!this._cylinder) {
  98128. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  98129. height: this._height,
  98130. diameter: this._radius * 2,
  98131. }, this._scene);
  98132. this._cylinder.isVisible = false;
  98133. }
  98134. };
  98135. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  98136. var impostorObject = impostor.object;
  98137. this._prepareCylinder();
  98138. this._cylinder.position = this._cylinderPosition;
  98139. return this._cylinder.intersectsMesh(impostorObject, true);
  98140. };
  98141. return PhysicsVortexEvent;
  98142. }());
  98143. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  98144. /**
  98145. * The strenght of the force in correspondence to the distance of the affected object
  98146. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  98147. */
  98148. var PhysicsRadialImpulseFalloff;
  98149. (function (PhysicsRadialImpulseFalloff) {
  98150. /** Defines that impulse is constant in strength across it's whole radius */
  98151. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  98152. /** DEfines that impulse gets weaker if it's further from the origin */
  98153. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear";
  98154. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  98155. /**
  98156. * The strength of the force in correspondence to the distance of the affected object
  98157. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  98158. */
  98159. var PhysicsUpdraftMode;
  98160. (function (PhysicsUpdraftMode) {
  98161. /** Defines that the upstream forces will pull towards the top center of the cylinder */
  98162. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  98163. /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */
  98164. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular";
  98165. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  98166. })(BABYLON || (BABYLON = {}));
  98167. //# sourceMappingURL=babylon.physicsHelper.js.map
  98168. var BABYLON;
  98169. (function (BABYLON) {
  98170. /** @hidden */
  98171. var CannonJSPlugin = /** @class */ (function () {
  98172. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  98173. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  98174. if (iterations === void 0) { iterations = 10; }
  98175. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  98176. this.name = "CannonJSPlugin";
  98177. this._physicsMaterials = new Array();
  98178. this._fixedTimeStep = 1 / 60;
  98179. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  98180. this.BJSCANNON = CANNON;
  98181. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  98182. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  98183. this._tmpPosition = BABYLON.Vector3.Zero();
  98184. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  98185. this._tmpUnityRotation = new BABYLON.Quaternion();
  98186. if (!this.isSupported()) {
  98187. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  98188. return;
  98189. }
  98190. this._extendNamespace();
  98191. this.world = new this.BJSCANNON.World();
  98192. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  98193. this.world.solver.iterations = iterations;
  98194. }
  98195. CannonJSPlugin.prototype.setGravity = function (gravity) {
  98196. this.world.gravity.copy(gravity);
  98197. };
  98198. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  98199. this._fixedTimeStep = timeStep;
  98200. };
  98201. CannonJSPlugin.prototype.getTimeStep = function () {
  98202. return this._fixedTimeStep;
  98203. };
  98204. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  98205. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  98206. };
  98207. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  98208. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  98209. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  98210. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  98211. };
  98212. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  98213. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  98214. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  98215. impostor.physicsBody.applyForce(impulse, worldPoint);
  98216. };
  98217. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  98218. //parent-child relationship. Does this impostor has a parent impostor?
  98219. if (impostor.parent) {
  98220. if (impostor.physicsBody) {
  98221. this.removePhysicsBody(impostor);
  98222. //TODO is that needed?
  98223. impostor.forceUpdate();
  98224. }
  98225. return;
  98226. }
  98227. //should a new body be created for this impostor?
  98228. if (impostor.isBodyInitRequired()) {
  98229. var shape = this._createShape(impostor);
  98230. //unregister events, if body is being changed
  98231. var oldBody = impostor.physicsBody;
  98232. if (oldBody) {
  98233. this.removePhysicsBody(impostor);
  98234. }
  98235. //create the body and material
  98236. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  98237. var bodyCreationObject = {
  98238. mass: impostor.getParam("mass"),
  98239. material: material
  98240. };
  98241. // A simple extend, in case native options were used.
  98242. var nativeOptions = impostor.getParam("nativeOptions");
  98243. for (var key in nativeOptions) {
  98244. if (nativeOptions.hasOwnProperty(key)) {
  98245. bodyCreationObject[key] = nativeOptions[key];
  98246. }
  98247. }
  98248. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  98249. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  98250. this.world.addEventListener("preStep", impostor.beforeStep);
  98251. this.world.addEventListener("postStep", impostor.afterStep);
  98252. impostor.physicsBody.addShape(shape);
  98253. this.world.add(impostor.physicsBody);
  98254. //try to keep the body moving in the right direction by taking old properties.
  98255. //Should be tested!
  98256. if (oldBody) {
  98257. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  98258. impostor.physicsBody[param].copy(oldBody[param]);
  98259. });
  98260. }
  98261. this._processChildMeshes(impostor);
  98262. }
  98263. //now update the body's transformation
  98264. this._updatePhysicsBodyTransformation(impostor);
  98265. };
  98266. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  98267. var _this = this;
  98268. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  98269. var currentRotation = mainImpostor.object.rotationQuaternion;
  98270. if (meshChildren.length) {
  98271. var processMesh = function (localPosition, mesh) {
  98272. if (!currentRotation || !mesh.rotationQuaternion) {
  98273. return;
  98274. }
  98275. var childImpostor = mesh.getPhysicsImpostor();
  98276. if (childImpostor) {
  98277. var parent = childImpostor.parent;
  98278. if (parent !== mainImpostor) {
  98279. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  98280. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  98281. if (childImpostor.physicsBody) {
  98282. _this.removePhysicsBody(childImpostor);
  98283. childImpostor.physicsBody = null;
  98284. }
  98285. childImpostor.parent = mainImpostor;
  98286. childImpostor.resetUpdateFlags();
  98287. 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));
  98288. //Add the mass of the children.
  98289. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  98290. }
  98291. }
  98292. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  98293. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  98294. };
  98295. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  98296. }
  98297. };
  98298. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  98299. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  98300. this.world.removeEventListener("preStep", impostor.beforeStep);
  98301. this.world.removeEventListener("postStep", impostor.afterStep);
  98302. this.world.remove(impostor.physicsBody);
  98303. };
  98304. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  98305. var mainBody = impostorJoint.mainImpostor.physicsBody;
  98306. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  98307. if (!mainBody || !connectedBody) {
  98308. return;
  98309. }
  98310. var constraint;
  98311. var jointData = impostorJoint.joint.jointData;
  98312. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  98313. var constraintData = {
  98314. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  98315. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  98316. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  98317. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  98318. maxForce: jointData.nativeParams.maxForce,
  98319. collideConnected: !!jointData.collision
  98320. };
  98321. switch (impostorJoint.joint.type) {
  98322. case BABYLON.PhysicsJoint.HingeJoint:
  98323. case BABYLON.PhysicsJoint.Hinge2Joint:
  98324. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  98325. break;
  98326. case BABYLON.PhysicsJoint.DistanceJoint:
  98327. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  98328. break;
  98329. case BABYLON.PhysicsJoint.SpringJoint:
  98330. var springData = jointData;
  98331. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  98332. restLength: springData.length,
  98333. stiffness: springData.stiffness,
  98334. damping: springData.damping,
  98335. localAnchorA: constraintData.pivotA,
  98336. localAnchorB: constraintData.pivotB
  98337. });
  98338. break;
  98339. case BABYLON.PhysicsJoint.LockJoint:
  98340. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  98341. break;
  98342. case BABYLON.PhysicsJoint.PointToPointJoint:
  98343. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  98344. default:
  98345. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  98346. break;
  98347. }
  98348. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  98349. constraint.collideConnected = !!jointData.collision;
  98350. impostorJoint.joint.physicsJoint = constraint;
  98351. //don't add spring as constraint, as it is not one.
  98352. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  98353. this.world.addConstraint(constraint);
  98354. }
  98355. else {
  98356. impostorJoint.joint.jointData.forceApplicationCallback = impostorJoint.joint.jointData.forceApplicationCallback || function () {
  98357. constraint.applyForce();
  98358. };
  98359. impostorJoint.mainImpostor.registerAfterPhysicsStep(impostorJoint.joint.jointData.forceApplicationCallback);
  98360. }
  98361. };
  98362. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  98363. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  98364. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  98365. }
  98366. else {
  98367. impostorJoint.mainImpostor.unregisterAfterPhysicsStep(impostorJoint.joint.jointData.forceApplicationCallback);
  98368. }
  98369. };
  98370. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  98371. var index;
  98372. var mat;
  98373. for (index = 0; index < this._physicsMaterials.length; index++) {
  98374. mat = this._physicsMaterials[index];
  98375. if (mat.friction === friction && mat.restitution === restitution) {
  98376. return mat;
  98377. }
  98378. }
  98379. var currentMat = new this.BJSCANNON.Material(name);
  98380. currentMat.friction = friction;
  98381. currentMat.restitution = restitution;
  98382. this._physicsMaterials.push(currentMat);
  98383. return currentMat;
  98384. };
  98385. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  98386. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  98387. };
  98388. CannonJSPlugin.prototype._createShape = function (impostor) {
  98389. var object = impostor.object;
  98390. var returnValue;
  98391. var extendSize = impostor.getObjectExtendSize();
  98392. switch (impostor.type) {
  98393. case BABYLON.PhysicsImpostor.SphereImpostor:
  98394. var radiusX = extendSize.x;
  98395. var radiusY = extendSize.y;
  98396. var radiusZ = extendSize.z;
  98397. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  98398. break;
  98399. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  98400. case BABYLON.PhysicsImpostor.CylinderImpostor:
  98401. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  98402. break;
  98403. case BABYLON.PhysicsImpostor.BoxImpostor:
  98404. var box = extendSize.scale(0.5);
  98405. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  98406. break;
  98407. case BABYLON.PhysicsImpostor.PlaneImpostor:
  98408. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  98409. returnValue = new this.BJSCANNON.Plane();
  98410. break;
  98411. case BABYLON.PhysicsImpostor.MeshImpostor:
  98412. // should transform the vertex data to world coordinates!!
  98413. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  98414. var rawFaces = object.getIndices ? object.getIndices() : [];
  98415. if (!rawVerts) {
  98416. return;
  98417. }
  98418. // get only scale! so the object could transform correctly.
  98419. var oldPosition = object.position.clone();
  98420. var oldRotation = object.rotation && object.rotation.clone();
  98421. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  98422. object.position.copyFromFloats(0, 0, 0);
  98423. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  98424. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  98425. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  98426. var transform = object.computeWorldMatrix(true);
  98427. // convert rawVerts to object space
  98428. var temp = new Array();
  98429. var index;
  98430. for (index = 0; index < rawVerts.length; index += 3) {
  98431. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  98432. }
  98433. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  98434. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  98435. //now set back the transformation!
  98436. object.position.copyFrom(oldPosition);
  98437. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  98438. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  98439. break;
  98440. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  98441. var oldPosition2 = object.position.clone();
  98442. var oldRotation2 = object.rotation && object.rotation.clone();
  98443. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  98444. object.position.copyFromFloats(0, 0, 0);
  98445. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  98446. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  98447. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  98448. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  98449. returnValue = this._createHeightmap(object);
  98450. object.position.copyFrom(oldPosition2);
  98451. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  98452. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  98453. object.computeWorldMatrix(true);
  98454. break;
  98455. case BABYLON.PhysicsImpostor.ParticleImpostor:
  98456. returnValue = new this.BJSCANNON.Particle();
  98457. break;
  98458. }
  98459. return returnValue;
  98460. };
  98461. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  98462. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  98463. var transform = object.computeWorldMatrix(true);
  98464. // convert rawVerts to object space
  98465. var temp = new Array();
  98466. var index;
  98467. for (index = 0; index < pos.length; index += 3) {
  98468. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  98469. }
  98470. pos = temp;
  98471. var matrix = new Array();
  98472. //For now pointDepth will not be used and will be automatically calculated.
  98473. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  98474. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  98475. var boundingInfo = object.getBoundingInfo();
  98476. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  98477. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  98478. var elementSize = dim * 2 / arraySize;
  98479. for (var i = 0; i < pos.length; i = i + 3) {
  98480. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  98481. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  98482. var y = -pos[i + 2] + minY;
  98483. if (!matrix[x]) {
  98484. matrix[x] = [];
  98485. }
  98486. if (!matrix[x][z]) {
  98487. matrix[x][z] = y;
  98488. }
  98489. matrix[x][z] = Math.max(y, matrix[x][z]);
  98490. }
  98491. for (var x = 0; x <= arraySize; ++x) {
  98492. if (!matrix[x]) {
  98493. var loc = 1;
  98494. while (!matrix[(x + loc) % arraySize]) {
  98495. loc++;
  98496. }
  98497. matrix[x] = matrix[(x + loc) % arraySize].slice();
  98498. //console.log("missing x", x);
  98499. }
  98500. for (var z = 0; z <= arraySize; ++z) {
  98501. if (!matrix[x][z]) {
  98502. var loc = 1;
  98503. var newValue;
  98504. while (newValue === undefined) {
  98505. newValue = matrix[x][(z + loc++) % arraySize];
  98506. }
  98507. matrix[x][z] = newValue;
  98508. }
  98509. }
  98510. }
  98511. var shape = new this.BJSCANNON.Heightfield(matrix, {
  98512. elementSize: elementSize
  98513. });
  98514. //For future reference, needed for body transformation
  98515. shape.minY = minY;
  98516. return shape;
  98517. };
  98518. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  98519. var object = impostor.object;
  98520. //make sure it is updated...
  98521. object.computeWorldMatrix && object.computeWorldMatrix(true);
  98522. // The delta between the mesh position and the mesh bounding box center
  98523. var bInfo = object.getBoundingInfo();
  98524. if (!bInfo) {
  98525. return;
  98526. }
  98527. var center = impostor.getObjectCenter();
  98528. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  98529. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  98530. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  98531. this._tmpPosition.copyFrom(center);
  98532. var quaternion = object.rotationQuaternion;
  98533. if (!quaternion) {
  98534. return;
  98535. }
  98536. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  98537. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  98538. //-90 DEG in X, precalculated
  98539. quaternion = quaternion.multiply(this._minus90X);
  98540. //Invert! (Precalculated, 90 deg in X)
  98541. //No need to clone. this will never change.
  98542. impostor.setDeltaRotation(this._plus90X);
  98543. }
  98544. //If it is a heightfield, if should be centered.
  98545. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  98546. var mesh = object;
  98547. var boundingInfo = mesh.getBoundingInfo();
  98548. //calculate the correct body position:
  98549. var rotationQuaternion = mesh.rotationQuaternion;
  98550. mesh.rotationQuaternion = this._tmpUnityRotation;
  98551. mesh.computeWorldMatrix(true);
  98552. //get original center with no rotation
  98553. var c = center.clone();
  98554. var oldPivot = mesh.getPivotMatrix();
  98555. if (oldPivot) {
  98556. // create a copy the pivot Matrix as it is modified in place
  98557. oldPivot = oldPivot.clone();
  98558. }
  98559. else {
  98560. oldPivot = BABYLON.Matrix.Identity();
  98561. }
  98562. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  98563. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  98564. mesh.setPreTransformMatrix(p);
  98565. mesh.computeWorldMatrix(true);
  98566. //calculate the translation
  98567. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  98568. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  98569. //add it inverted to the delta
  98570. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  98571. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  98572. //rotation is back
  98573. mesh.rotationQuaternion = rotationQuaternion;
  98574. mesh.setPreTransformMatrix(oldPivot);
  98575. mesh.computeWorldMatrix(true);
  98576. }
  98577. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  98578. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  98579. //this._tmpPosition.copyFrom(object.position);
  98580. }
  98581. impostor.setDeltaPosition(this._tmpDeltaPosition);
  98582. //Now update the impostor object
  98583. impostor.physicsBody.position.copy(this._tmpPosition);
  98584. impostor.physicsBody.quaternion.copy(quaternion);
  98585. };
  98586. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  98587. impostor.object.position.copyFrom(impostor.physicsBody.position);
  98588. if (impostor.object.rotationQuaternion) {
  98589. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  98590. }
  98591. };
  98592. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  98593. impostor.physicsBody.position.copy(newPosition);
  98594. impostor.physicsBody.quaternion.copy(newRotation);
  98595. };
  98596. CannonJSPlugin.prototype.isSupported = function () {
  98597. return this.BJSCANNON !== undefined;
  98598. };
  98599. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  98600. impostor.physicsBody.velocity.copy(velocity);
  98601. };
  98602. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  98603. impostor.physicsBody.angularVelocity.copy(velocity);
  98604. };
  98605. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  98606. var v = impostor.physicsBody.velocity;
  98607. if (!v) {
  98608. return null;
  98609. }
  98610. return new BABYLON.Vector3(v.x, v.y, v.z);
  98611. };
  98612. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  98613. var v = impostor.physicsBody.angularVelocity;
  98614. if (!v) {
  98615. return null;
  98616. }
  98617. return new BABYLON.Vector3(v.x, v.y, v.z);
  98618. };
  98619. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  98620. impostor.physicsBody.mass = mass;
  98621. impostor.physicsBody.updateMassProperties();
  98622. };
  98623. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  98624. return impostor.physicsBody.mass;
  98625. };
  98626. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  98627. return impostor.physicsBody.material.friction;
  98628. };
  98629. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  98630. impostor.physicsBody.material.friction = friction;
  98631. };
  98632. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  98633. return impostor.physicsBody.material.restitution;
  98634. };
  98635. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  98636. impostor.physicsBody.material.restitution = restitution;
  98637. };
  98638. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  98639. impostor.physicsBody.sleep();
  98640. };
  98641. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  98642. impostor.physicsBody.wakeUp();
  98643. };
  98644. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  98645. joint.physicsJoint.distance = maxDistance;
  98646. };
  98647. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  98648. // if (!motorIndex) {
  98649. // joint.physicsJoint.enableMotor();
  98650. // }
  98651. // }
  98652. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  98653. // if (!motorIndex) {
  98654. // joint.physicsJoint.disableMotor();
  98655. // }
  98656. // }
  98657. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  98658. if (!motorIndex) {
  98659. joint.physicsJoint.enableMotor();
  98660. joint.physicsJoint.setMotorSpeed(speed);
  98661. if (maxForce) {
  98662. this.setLimit(joint, maxForce);
  98663. }
  98664. }
  98665. };
  98666. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  98667. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  98668. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  98669. };
  98670. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  98671. var body = impostor.physicsBody;
  98672. mesh.position.x = body.position.x;
  98673. mesh.position.y = body.position.y;
  98674. mesh.position.z = body.position.z;
  98675. if (mesh.rotationQuaternion) {
  98676. mesh.rotationQuaternion.x = body.quaternion.x;
  98677. mesh.rotationQuaternion.y = body.quaternion.y;
  98678. mesh.rotationQuaternion.z = body.quaternion.z;
  98679. mesh.rotationQuaternion.w = body.quaternion.w;
  98680. }
  98681. };
  98682. CannonJSPlugin.prototype.getRadius = function (impostor) {
  98683. var shape = impostor.physicsBody.shapes[0];
  98684. return shape.boundingSphereRadius;
  98685. };
  98686. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  98687. var shape = impostor.physicsBody.shapes[0];
  98688. result.x = shape.halfExtents.x * 2;
  98689. result.y = shape.halfExtents.y * 2;
  98690. result.z = shape.halfExtents.z * 2;
  98691. };
  98692. CannonJSPlugin.prototype.dispose = function () {
  98693. };
  98694. CannonJSPlugin.prototype._extendNamespace = function () {
  98695. //this will force cannon to execute at least one step when using interpolation
  98696. var step_tmp1 = new this.BJSCANNON.Vec3();
  98697. var Engine = this.BJSCANNON;
  98698. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  98699. maxSubSteps = maxSubSteps || 10;
  98700. timeSinceLastCalled = timeSinceLastCalled || 0;
  98701. if (timeSinceLastCalled === 0) {
  98702. this.internalStep(dt);
  98703. this.time += dt;
  98704. }
  98705. else {
  98706. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  98707. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  98708. var t0 = performance.now();
  98709. for (var i = 0; i !== internalSteps; i++) {
  98710. this.internalStep(dt);
  98711. if (performance.now() - t0 > dt * 1000) {
  98712. break;
  98713. }
  98714. }
  98715. this.time += timeSinceLastCalled;
  98716. var h = this.time % dt;
  98717. var h_div_dt = h / dt;
  98718. var interpvelo = step_tmp1;
  98719. var bodies = this.bodies;
  98720. for (var j = 0; j !== bodies.length; j++) {
  98721. var b = bodies[j];
  98722. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  98723. b.position.vsub(b.previousPosition, interpvelo);
  98724. interpvelo.scale(h_div_dt, interpvelo);
  98725. b.position.vadd(interpvelo, b.interpolatedPosition);
  98726. }
  98727. else {
  98728. b.interpolatedPosition.copy(b.position);
  98729. b.interpolatedQuaternion.copy(b.quaternion);
  98730. }
  98731. }
  98732. }
  98733. };
  98734. };
  98735. return CannonJSPlugin;
  98736. }());
  98737. BABYLON.CannonJSPlugin = CannonJSPlugin;
  98738. })(BABYLON || (BABYLON = {}));
  98739. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  98740. var BABYLON;
  98741. (function (BABYLON) {
  98742. /** @hidden */
  98743. var OimoJSPlugin = /** @class */ (function () {
  98744. function OimoJSPlugin(iterations) {
  98745. this.name = "OimoJSPlugin";
  98746. this._tmpImpostorsArray = [];
  98747. this._tmpPositionVector = BABYLON.Vector3.Zero();
  98748. this.BJSOIMO = OIMO;
  98749. this.world = new this.BJSOIMO.World({
  98750. iterations: iterations
  98751. });
  98752. this.world.clear();
  98753. }
  98754. OimoJSPlugin.prototype.setGravity = function (gravity) {
  98755. this.world.gravity.copy(gravity);
  98756. };
  98757. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  98758. this.world.timeStep = timeStep;
  98759. };
  98760. OimoJSPlugin.prototype.getTimeStep = function () {
  98761. return this.world.timeStep;
  98762. };
  98763. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  98764. var _this = this;
  98765. impostors.forEach(function (impostor) {
  98766. impostor.beforeStep();
  98767. });
  98768. this.world.step();
  98769. impostors.forEach(function (impostor) {
  98770. impostor.afterStep();
  98771. //update the ordered impostors array
  98772. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  98773. });
  98774. //check for collisions
  98775. var contact = this.world.contacts;
  98776. while (contact !== null) {
  98777. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  98778. contact = contact.next;
  98779. continue;
  98780. }
  98781. //is this body colliding with any other? get the impostor
  98782. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  98783. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  98784. if (!mainImpostor || !collidingImpostor) {
  98785. contact = contact.next;
  98786. continue;
  98787. }
  98788. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  98789. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  98790. contact = contact.next;
  98791. }
  98792. };
  98793. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  98794. var mass = impostor.physicsBody.mass;
  98795. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  98796. };
  98797. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  98798. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  98799. this.applyImpulse(impostor, force, contactPoint);
  98800. };
  98801. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  98802. var _this = this;
  98803. //parent-child relationship. Does this impostor has a parent impostor?
  98804. if (impostor.parent) {
  98805. if (impostor.physicsBody) {
  98806. this.removePhysicsBody(impostor);
  98807. //TODO is that needed?
  98808. impostor.forceUpdate();
  98809. }
  98810. return;
  98811. }
  98812. if (impostor.isBodyInitRequired()) {
  98813. var bodyConfig = {
  98814. name: impostor.uniqueId,
  98815. //Oimo must have mass, also for static objects.
  98816. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  98817. size: [],
  98818. type: [],
  98819. pos: [],
  98820. posShape: [],
  98821. rot: [],
  98822. rotShape: [],
  98823. move: impostor.getParam("mass") !== 0,
  98824. density: impostor.getParam("mass"),
  98825. friction: impostor.getParam("friction"),
  98826. restitution: impostor.getParam("restitution"),
  98827. //Supporting older versions of Oimo
  98828. world: this.world
  98829. };
  98830. var impostors = [impostor];
  98831. var addToArray = function (parent) {
  98832. if (!parent.getChildMeshes) {
  98833. return;
  98834. }
  98835. parent.getChildMeshes().forEach(function (m) {
  98836. if (m.physicsImpostor) {
  98837. impostors.push(m.physicsImpostor);
  98838. //m.physicsImpostor._init();
  98839. }
  98840. });
  98841. };
  98842. addToArray(impostor.object);
  98843. var checkWithEpsilon_1 = function (value) {
  98844. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  98845. };
  98846. var globalQuaternion_1 = new BABYLON.Quaternion();
  98847. impostors.forEach(function (i) {
  98848. if (!i.object.rotationQuaternion) {
  98849. return;
  98850. }
  98851. //get the correct bounding box
  98852. var oldQuaternion = i.object.rotationQuaternion;
  98853. globalQuaternion_1 = oldQuaternion.clone();
  98854. var rot = oldQuaternion.toEulerAngles();
  98855. var extendSize = i.getObjectExtendSize();
  98856. var radToDeg = 57.295779513082320876;
  98857. if (i === impostor) {
  98858. var center = impostor.getObjectCenter();
  98859. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  98860. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  98861. //Can also use Array.prototype.push.apply
  98862. bodyConfig.pos.push(center.x);
  98863. bodyConfig.pos.push(center.y);
  98864. bodyConfig.pos.push(center.z);
  98865. bodyConfig.posShape.push(0, 0, 0);
  98866. bodyConfig.rotShape.push(0, 0, 0);
  98867. }
  98868. else {
  98869. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  98870. bodyConfig.posShape.push(localPosition.x);
  98871. bodyConfig.posShape.push(localPosition.y);
  98872. bodyConfig.posShape.push(localPosition.z);
  98873. bodyConfig.pos.push(0, 0, 0);
  98874. bodyConfig.rotShape.push(rot.x * radToDeg);
  98875. bodyConfig.rotShape.push(rot.y * radToDeg);
  98876. bodyConfig.rotShape.push(rot.z * radToDeg);
  98877. }
  98878. // register mesh
  98879. switch (i.type) {
  98880. case BABYLON.PhysicsImpostor.ParticleImpostor:
  98881. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  98882. case BABYLON.PhysicsImpostor.SphereImpostor:
  98883. var radiusX = extendSize.x;
  98884. var radiusY = extendSize.y;
  98885. var radiusZ = extendSize.z;
  98886. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  98887. bodyConfig.type.push('sphere');
  98888. //due to the way oimo works with compounds, add 3 times
  98889. bodyConfig.size.push(size);
  98890. bodyConfig.size.push(size);
  98891. bodyConfig.size.push(size);
  98892. break;
  98893. case BABYLON.PhysicsImpostor.CylinderImpostor:
  98894. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  98895. var sizeY = checkWithEpsilon_1(extendSize.y);
  98896. bodyConfig.type.push('cylinder');
  98897. bodyConfig.size.push(sizeX);
  98898. bodyConfig.size.push(sizeY);
  98899. //due to the way oimo works with compounds, add one more value.
  98900. bodyConfig.size.push(sizeY);
  98901. break;
  98902. case BABYLON.PhysicsImpostor.PlaneImpostor:
  98903. case BABYLON.PhysicsImpostor.BoxImpostor:
  98904. default:
  98905. var sizeX = checkWithEpsilon_1(extendSize.x);
  98906. var sizeY = checkWithEpsilon_1(extendSize.y);
  98907. var sizeZ = checkWithEpsilon_1(extendSize.z);
  98908. bodyConfig.type.push('box');
  98909. //if (i === impostor) {
  98910. bodyConfig.size.push(sizeX);
  98911. bodyConfig.size.push(sizeY);
  98912. bodyConfig.size.push(sizeZ);
  98913. //} else {
  98914. // bodyConfig.size.push(0,0,0);
  98915. //}
  98916. break;
  98917. }
  98918. //actually not needed, but hey...
  98919. i.object.rotationQuaternion = oldQuaternion;
  98920. });
  98921. impostor.physicsBody = this.world.add(bodyConfig);
  98922. // set the quaternion, ignoring the previously defined (euler) rotation
  98923. impostor.physicsBody.resetQuaternion(globalQuaternion_1);
  98924. // update with delta 0, so the body will reveive the new rotation.
  98925. impostor.physicsBody.updatePosition(0);
  98926. }
  98927. else {
  98928. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  98929. }
  98930. impostor.setDeltaPosition(this._tmpPositionVector);
  98931. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  98932. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  98933. };
  98934. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  98935. //impostor.physicsBody.dispose();
  98936. //Same as : (older oimo versions)
  98937. this.world.removeRigidBody(impostor.physicsBody);
  98938. };
  98939. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  98940. var mainBody = impostorJoint.mainImpostor.physicsBody;
  98941. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  98942. if (!mainBody || !connectedBody) {
  98943. return;
  98944. }
  98945. var jointData = impostorJoint.joint.jointData;
  98946. var options = jointData.nativeParams || {};
  98947. var type;
  98948. var nativeJointData = {
  98949. body1: mainBody,
  98950. body2: connectedBody,
  98951. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  98952. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  98953. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  98954. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  98955. min: options.min,
  98956. max: options.max,
  98957. collision: options.collision || jointData.collision,
  98958. spring: options.spring,
  98959. //supporting older version of Oimo
  98960. world: this.world
  98961. };
  98962. switch (impostorJoint.joint.type) {
  98963. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  98964. type = "jointBall";
  98965. break;
  98966. case BABYLON.PhysicsJoint.SpringJoint:
  98967. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  98968. var springData = jointData;
  98969. nativeJointData.min = springData.length || nativeJointData.min;
  98970. //Max should also be set, just make sure it is at least min
  98971. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  98972. case BABYLON.PhysicsJoint.DistanceJoint:
  98973. type = "jointDistance";
  98974. nativeJointData.max = jointData.maxDistance;
  98975. break;
  98976. case BABYLON.PhysicsJoint.PrismaticJoint:
  98977. type = "jointPrisme";
  98978. break;
  98979. case BABYLON.PhysicsJoint.SliderJoint:
  98980. type = "jointSlide";
  98981. break;
  98982. case BABYLON.PhysicsJoint.WheelJoint:
  98983. type = "jointWheel";
  98984. break;
  98985. case BABYLON.PhysicsJoint.HingeJoint:
  98986. default:
  98987. type = "jointHinge";
  98988. break;
  98989. }
  98990. nativeJointData.type = type;
  98991. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  98992. };
  98993. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  98994. //Bug in Oimo prevents us from disposing a joint in the playground
  98995. //joint.joint.physicsJoint.dispose();
  98996. //So we will bruteforce it!
  98997. try {
  98998. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  98999. }
  99000. catch (e) {
  99001. BABYLON.Tools.Warn(e);
  99002. }
  99003. };
  99004. OimoJSPlugin.prototype.isSupported = function () {
  99005. return this.BJSOIMO !== undefined;
  99006. };
  99007. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  99008. if (!impostor.physicsBody.sleeping) {
  99009. //TODO check that
  99010. /*if (impostor.physicsBody.shapes.next) {
  99011. var parentShape = this._getLastShape(impostor.physicsBody);
  99012. impostor.object.position.copyFrom(parentShape.position);
  99013. console.log(parentShape.position);
  99014. } else {*/
  99015. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  99016. //}
  99017. if (impostor.object.rotationQuaternion) {
  99018. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  99019. }
  99020. }
  99021. };
  99022. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  99023. var body = impostor.physicsBody;
  99024. body.position.copy(newPosition);
  99025. body.orientation.copy(newRotation);
  99026. body.syncShapes();
  99027. body.awake();
  99028. };
  99029. /*private _getLastShape(body: any): any {
  99030. var lastShape = body.shapes;
  99031. while (lastShape.next) {
  99032. lastShape = lastShape.next;
  99033. }
  99034. return lastShape;
  99035. }*/
  99036. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  99037. impostor.physicsBody.linearVelocity.copy(velocity);
  99038. };
  99039. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  99040. impostor.physicsBody.angularVelocity.copy(velocity);
  99041. };
  99042. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  99043. var v = impostor.physicsBody.linearVelocity;
  99044. if (!v) {
  99045. return null;
  99046. }
  99047. return new BABYLON.Vector3(v.x, v.y, v.z);
  99048. };
  99049. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  99050. var v = impostor.physicsBody.angularVelocity;
  99051. if (!v) {
  99052. return null;
  99053. }
  99054. return new BABYLON.Vector3(v.x, v.y, v.z);
  99055. };
  99056. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  99057. var staticBody = mass === 0;
  99058. //this will actually set the body's density and not its mass.
  99059. //But this is how oimo treats the mass variable.
  99060. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  99061. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  99062. };
  99063. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  99064. return impostor.physicsBody.shapes.density;
  99065. };
  99066. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  99067. return impostor.physicsBody.shapes.friction;
  99068. };
  99069. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  99070. impostor.physicsBody.shapes.friction = friction;
  99071. };
  99072. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  99073. return impostor.physicsBody.shapes.restitution;
  99074. };
  99075. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  99076. impostor.physicsBody.shapes.restitution = restitution;
  99077. };
  99078. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  99079. impostor.physicsBody.sleep();
  99080. };
  99081. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  99082. impostor.physicsBody.awake();
  99083. };
  99084. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  99085. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  99086. if (minDistance !== void 0) {
  99087. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  99088. }
  99089. };
  99090. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  99091. //TODO separate rotational and transational motors.
  99092. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  99093. if (motor) {
  99094. motor.setMotor(speed, maxForce);
  99095. }
  99096. };
  99097. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  99098. //TODO separate rotational and transational motors.
  99099. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  99100. if (motor) {
  99101. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  99102. }
  99103. };
  99104. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  99105. var body = impostor.physicsBody;
  99106. mesh.position.x = body.position.x;
  99107. mesh.position.y = body.position.y;
  99108. mesh.position.z = body.position.z;
  99109. if (mesh.rotationQuaternion) {
  99110. mesh.rotationQuaternion.x = body.orientation.x;
  99111. mesh.rotationQuaternion.y = body.orientation.y;
  99112. mesh.rotationQuaternion.z = body.orientation.z;
  99113. mesh.rotationQuaternion.w = body.orientation.s;
  99114. }
  99115. };
  99116. OimoJSPlugin.prototype.getRadius = function (impostor) {
  99117. return impostor.physicsBody.shapes.radius;
  99118. };
  99119. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  99120. var shape = impostor.physicsBody.shapes;
  99121. result.x = shape.halfWidth * 2;
  99122. result.y = shape.halfHeight * 2;
  99123. result.z = shape.halfDepth * 2;
  99124. };
  99125. OimoJSPlugin.prototype.dispose = function () {
  99126. this.world.clear();
  99127. };
  99128. return OimoJSPlugin;
  99129. }());
  99130. BABYLON.OimoJSPlugin = OimoJSPlugin;
  99131. })(BABYLON || (BABYLON = {}));
  99132. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  99133. var BABYLON;
  99134. (function (BABYLON) {
  99135. /**
  99136. * Gets the current physics engine
  99137. * @returns a IPhysicsEngine or null if none attached
  99138. */
  99139. BABYLON.Scene.prototype.getPhysicsEngine = function () {
  99140. return this._physicsEngine;
  99141. };
  99142. /**
  99143. * Enables physics to the current scene
  99144. * @param gravity defines the scene's gravity for the physics engine
  99145. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  99146. * @return a boolean indicating if the physics engine was initialized
  99147. */
  99148. BABYLON.Scene.prototype.enablePhysics = function (gravity, plugin) {
  99149. if (gravity === void 0) { gravity = null; }
  99150. if (this._physicsEngine) {
  99151. return true;
  99152. }
  99153. // Register the component to the scene
  99154. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_PHYSICSENGINE);
  99155. if (!component) {
  99156. component = new PhysicsEngineSceneComponent(this);
  99157. this._addComponent(component);
  99158. }
  99159. try {
  99160. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  99161. return true;
  99162. }
  99163. catch (e) {
  99164. BABYLON.Tools.Error(e.message);
  99165. return false;
  99166. }
  99167. };
  99168. /**
  99169. * Disables and disposes the physics engine associated with the scene
  99170. */
  99171. BABYLON.Scene.prototype.disablePhysicsEngine = function () {
  99172. if (!this._physicsEngine) {
  99173. return;
  99174. }
  99175. this._physicsEngine.dispose();
  99176. this._physicsEngine = null;
  99177. };
  99178. /**
  99179. * Gets a boolean indicating if there is an active physics engine
  99180. * @returns a boolean indicating if there is an active physics engine
  99181. */
  99182. BABYLON.Scene.prototype.isPhysicsEnabled = function () {
  99183. return this._physicsEngine !== undefined;
  99184. };
  99185. /**
  99186. * Deletes a physics compound impostor
  99187. * @param compound defines the compound to delete
  99188. */
  99189. BABYLON.Scene.prototype.deleteCompoundImpostor = function (compound) {
  99190. var mesh = compound.parts[0].mesh;
  99191. if (mesh.physicsImpostor) {
  99192. mesh.physicsImpostor.dispose( /*true*/);
  99193. mesh.physicsImpostor = null;
  99194. }
  99195. };
  99196. /** @hidden */
  99197. BABYLON.Scene.prototype._advancePhysicsEngineStep = function (step) {
  99198. if (this._physicsEngine) {
  99199. this.onBeforePhysicsObservable.notifyObservers(this);
  99200. this._physicsEngine._step(step / 1000);
  99201. this.onAfterPhysicsObservable.notifyObservers(this);
  99202. }
  99203. };
  99204. Object.defineProperty(BABYLON.AbstractMesh.prototype, "physicsImpostor", {
  99205. get: function () {
  99206. return this._physicsImpostor;
  99207. },
  99208. set: function (value) {
  99209. var _this = this;
  99210. if (this._physicsImpostor === value) {
  99211. return;
  99212. }
  99213. if (this._disposePhysicsObserver) {
  99214. this.onDisposeObservable.remove(this._disposePhysicsObserver);
  99215. }
  99216. this._physicsImpostor = value;
  99217. if (value) {
  99218. this._disposePhysicsObserver = this.onDisposeObservable.add(function () {
  99219. // Physics
  99220. if (_this.physicsImpostor) {
  99221. _this.physicsImpostor.dispose( /*!doNotRecurse*/);
  99222. _this.physicsImpostor = null;
  99223. }
  99224. });
  99225. }
  99226. },
  99227. enumerable: true,
  99228. configurable: true
  99229. });
  99230. /**
  99231. * Gets the current physics impostor
  99232. * @see http://doc.babylonjs.com/features/physics_engine
  99233. * @returns a physics impostor or null
  99234. */
  99235. BABYLON.AbstractMesh.prototype.getPhysicsImpostor = function () {
  99236. return this.physicsImpostor;
  99237. };
  99238. /**
  99239. * Apply a physic impulse to the mesh
  99240. * @param force defines the force to apply
  99241. * @param contactPoint defines where to apply the force
  99242. * @returns the current mesh
  99243. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  99244. */
  99245. BABYLON.AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  99246. if (!this.physicsImpostor) {
  99247. return this;
  99248. }
  99249. this.physicsImpostor.applyImpulse(force, contactPoint);
  99250. return this;
  99251. };
  99252. /**
  99253. * Creates a physic joint between two meshes
  99254. * @param otherMesh defines the other mesh to use
  99255. * @param pivot1 defines the pivot to use on this mesh
  99256. * @param pivot2 defines the pivot to use on the other mesh
  99257. * @param options defines additional options (can be plugin dependent)
  99258. * @returns the current mesh
  99259. * @see https://www.babylonjs-playground.com/#0BS5U0#0
  99260. */
  99261. BABYLON.AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  99262. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  99263. return this;
  99264. }
  99265. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  99266. mainPivot: pivot1,
  99267. connectedPivot: pivot2,
  99268. nativeParams: options
  99269. });
  99270. return this;
  99271. };
  99272. /**
  99273. * Defines the physics engine scene component responsible to manage a physics engine
  99274. */
  99275. var PhysicsEngineSceneComponent = /** @class */ (function () {
  99276. /**
  99277. * Creates a new instance of the component for the given scene
  99278. * @param scene Defines the scene to register the component in
  99279. */
  99280. function PhysicsEngineSceneComponent(scene) {
  99281. var _this = this;
  99282. /**
  99283. * The component name helpful to identify the component in the list of scene components.
  99284. */
  99285. this.name = BABYLON.SceneComponentConstants.NAME_PHYSICSENGINE;
  99286. this.scene = scene;
  99287. this.scene.onBeforePhysicsObservable = new BABYLON.Observable();
  99288. this.scene.onAfterPhysicsObservable = new BABYLON.Observable();
  99289. // Replace the function used to get the deterministic frame time
  99290. this.scene.getDeterministicFrameTime = function () {
  99291. if (_this.scene._physicsEngine) {
  99292. return _this.scene._physicsEngine.getTimeStep() * 1000;
  99293. }
  99294. return 1000.0 / 60.0;
  99295. };
  99296. }
  99297. /**
  99298. * Registers the component in a given scene
  99299. */
  99300. PhysicsEngineSceneComponent.prototype.register = function () {
  99301. };
  99302. /**
  99303. * Rebuilds the elements related to this component in case of
  99304. * context lost for instance.
  99305. */
  99306. PhysicsEngineSceneComponent.prototype.rebuild = function () {
  99307. // Nothing to do for this component
  99308. };
  99309. /**
  99310. * Disposes the component and the associated ressources
  99311. */
  99312. PhysicsEngineSceneComponent.prototype.dispose = function () {
  99313. this.scene.onBeforePhysicsObservable.clear();
  99314. this.scene.onAfterPhysicsObservable.clear();
  99315. if (this.scene._physicsEngine) {
  99316. this.scene.disablePhysicsEngine();
  99317. }
  99318. };
  99319. return PhysicsEngineSceneComponent;
  99320. }());
  99321. BABYLON.PhysicsEngineSceneComponent = PhysicsEngineSceneComponent;
  99322. })(BABYLON || (BABYLON = {}));
  99323. //# sourceMappingURL=babylon.physicsEngineComponent.js.map
  99324. var BABYLON;
  99325. (function (BABYLON) {
  99326. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  99327. // All values and structures referenced from:
  99328. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  99329. var DDS_MAGIC = 0x20534444;
  99330. var
  99331. //DDSD_CAPS = 0x1,
  99332. //DDSD_HEIGHT = 0x2,
  99333. //DDSD_WIDTH = 0x4,
  99334. //DDSD_PITCH = 0x8,
  99335. //DDSD_PIXELFORMAT = 0x1000,
  99336. DDSD_MIPMAPCOUNT = 0x20000;
  99337. //DDSD_LINEARSIZE = 0x80000,
  99338. //DDSD_DEPTH = 0x800000;
  99339. // var DDSCAPS_COMPLEX = 0x8,
  99340. // DDSCAPS_MIPMAP = 0x400000,
  99341. // DDSCAPS_TEXTURE = 0x1000;
  99342. var DDSCAPS2_CUBEMAP = 0x200;
  99343. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  99344. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  99345. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  99346. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  99347. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  99348. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  99349. // DDSCAPS2_VOLUME = 0x200000;
  99350. var
  99351. //DDPF_ALPHAPIXELS = 0x1,
  99352. //DDPF_ALPHA = 0x2,
  99353. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  99354. //DDPF_YUV = 0x200,
  99355. DDPF_LUMINANCE = 0x20000;
  99356. function FourCCToInt32(value) {
  99357. return value.charCodeAt(0) +
  99358. (value.charCodeAt(1) << 8) +
  99359. (value.charCodeAt(2) << 16) +
  99360. (value.charCodeAt(3) << 24);
  99361. }
  99362. function Int32ToFourCC(value) {
  99363. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  99364. }
  99365. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  99366. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  99367. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  99368. var FOURCC_DX10 = FourCCToInt32("DX10");
  99369. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  99370. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  99371. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  99372. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  99373. var headerLengthInt = 31; // The header length in 32 bit ints
  99374. // Offsets into the header array
  99375. var off_magic = 0;
  99376. var off_size = 1;
  99377. var off_flags = 2;
  99378. var off_height = 3;
  99379. var off_width = 4;
  99380. var off_mipmapCount = 7;
  99381. var off_pfFlags = 20;
  99382. var off_pfFourCC = 21;
  99383. var off_RGBbpp = 22;
  99384. var off_RMask = 23;
  99385. var off_GMask = 24;
  99386. var off_BMask = 25;
  99387. var off_AMask = 26;
  99388. // var off_caps1 = 27;
  99389. var off_caps2 = 28;
  99390. // var off_caps3 = 29;
  99391. // var off_caps4 = 30;
  99392. var off_dxgiFormat = 32;
  99393. /**
  99394. * Class used to provide DDS decompression tools
  99395. */
  99396. var DDSTools = /** @class */ (function () {
  99397. function DDSTools() {
  99398. }
  99399. /**
  99400. * Gets DDS information from an array buffer
  99401. * @param arrayBuffer defines the array buffer to read data from
  99402. * @returns the DDS information
  99403. */
  99404. DDSTools.GetDDSInfo = function (arrayBuffer) {
  99405. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  99406. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  99407. var mipmapCount = 1;
  99408. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  99409. mipmapCount = Math.max(1, header[off_mipmapCount]);
  99410. }
  99411. var fourCC = header[off_pfFourCC];
  99412. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  99413. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  99414. switch (fourCC) {
  99415. case FOURCC_D3DFMT_R16G16B16A16F:
  99416. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  99417. break;
  99418. case FOURCC_D3DFMT_R32G32B32A32F:
  99419. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  99420. break;
  99421. case FOURCC_DX10:
  99422. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  99423. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  99424. break;
  99425. }
  99426. }
  99427. return {
  99428. width: header[off_width],
  99429. height: header[off_height],
  99430. mipmapCount: mipmapCount,
  99431. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  99432. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  99433. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  99434. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  99435. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  99436. dxgiFormat: dxgiFormat,
  99437. textureType: textureType
  99438. };
  99439. };
  99440. DDSTools._ToHalfFloat = function (value) {
  99441. if (!DDSTools._FloatView) {
  99442. DDSTools._FloatView = new Float32Array(1);
  99443. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  99444. }
  99445. DDSTools._FloatView[0] = value;
  99446. var x = DDSTools._Int32View[0];
  99447. var bits = (x >> 16) & 0x8000; /* Get the sign */
  99448. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  99449. var e = (x >> 23) & 0xff; /* Using int is faster here */
  99450. /* If zero, or denormal, or exponent underflows too much for a denormal
  99451. * half, return signed zero. */
  99452. if (e < 103) {
  99453. return bits;
  99454. }
  99455. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  99456. if (e > 142) {
  99457. bits |= 0x7c00;
  99458. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  99459. * not Inf, so make sure we set one mantissa bit too. */
  99460. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  99461. return bits;
  99462. }
  99463. /* If exponent underflows but not too much, return a denormal */
  99464. if (e < 113) {
  99465. m |= 0x0800;
  99466. /* Extra rounding may overflow and set mantissa to 0 and exponent
  99467. * to 1, which is OK. */
  99468. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  99469. return bits;
  99470. }
  99471. bits |= ((e - 112) << 10) | (m >> 1);
  99472. bits += m & 1;
  99473. return bits;
  99474. };
  99475. DDSTools._FromHalfFloat = function (value) {
  99476. var s = (value & 0x8000) >> 15;
  99477. var e = (value & 0x7C00) >> 10;
  99478. var f = value & 0x03FF;
  99479. if (e === 0) {
  99480. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  99481. }
  99482. else if (e == 0x1F) {
  99483. return f ? NaN : ((s ? -1 : 1) * Infinity);
  99484. }
  99485. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  99486. };
  99487. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  99488. var destArray = new Float32Array(dataLength);
  99489. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  99490. var index = 0;
  99491. for (var y = 0; y < height; y++) {
  99492. for (var x = 0; x < width; x++) {
  99493. var srcPos = (x + y * width) * 4;
  99494. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  99495. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  99496. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  99497. if (DDSTools.StoreLODInAlphaChannel) {
  99498. destArray[index + 3] = lod;
  99499. }
  99500. else {
  99501. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  99502. }
  99503. index += 4;
  99504. }
  99505. }
  99506. return destArray;
  99507. };
  99508. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  99509. if (DDSTools.StoreLODInAlphaChannel) {
  99510. var destArray = new Uint16Array(dataLength);
  99511. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  99512. var index = 0;
  99513. for (var y = 0; y < height; y++) {
  99514. for (var x = 0; x < width; x++) {
  99515. var srcPos = (x + y * width) * 4;
  99516. destArray[index] = srcData[srcPos];
  99517. destArray[index + 1] = srcData[srcPos + 1];
  99518. destArray[index + 2] = srcData[srcPos + 2];
  99519. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  99520. index += 4;
  99521. }
  99522. }
  99523. return destArray;
  99524. }
  99525. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  99526. };
  99527. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  99528. if (DDSTools.StoreLODInAlphaChannel) {
  99529. var destArray = new Float32Array(dataLength);
  99530. var srcData = new Float32Array(arrayBuffer, dataOffset);
  99531. var index = 0;
  99532. for (var y = 0; y < height; y++) {
  99533. for (var x = 0; x < width; x++) {
  99534. var srcPos = (x + y * width) * 4;
  99535. destArray[index] = srcData[srcPos];
  99536. destArray[index + 1] = srcData[srcPos + 1];
  99537. destArray[index + 2] = srcData[srcPos + 2];
  99538. destArray[index + 3] = lod;
  99539. index += 4;
  99540. }
  99541. }
  99542. return destArray;
  99543. }
  99544. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  99545. };
  99546. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  99547. var destArray = new Uint8Array(dataLength);
  99548. var srcData = new Float32Array(arrayBuffer, dataOffset);
  99549. var index = 0;
  99550. for (var y = 0; y < height; y++) {
  99551. for (var x = 0; x < width; x++) {
  99552. var srcPos = (x + y * width) * 4;
  99553. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  99554. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  99555. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  99556. if (DDSTools.StoreLODInAlphaChannel) {
  99557. destArray[index + 3] = lod;
  99558. }
  99559. else {
  99560. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  99561. }
  99562. index += 4;
  99563. }
  99564. }
  99565. return destArray;
  99566. };
  99567. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  99568. var destArray = new Uint8Array(dataLength);
  99569. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  99570. var index = 0;
  99571. for (var y = 0; y < height; y++) {
  99572. for (var x = 0; x < width; x++) {
  99573. var srcPos = (x + y * width) * 4;
  99574. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  99575. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  99576. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  99577. if (DDSTools.StoreLODInAlphaChannel) {
  99578. destArray[index + 3] = lod;
  99579. }
  99580. else {
  99581. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  99582. }
  99583. index += 4;
  99584. }
  99585. }
  99586. return destArray;
  99587. };
  99588. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  99589. var byteArray = new Uint8Array(dataLength);
  99590. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  99591. var index = 0;
  99592. for (var y = 0; y < height; y++) {
  99593. for (var x = 0; x < width; x++) {
  99594. var srcPos = (x + y * width) * 4;
  99595. byteArray[index] = srcData[srcPos + rOffset];
  99596. byteArray[index + 1] = srcData[srcPos + gOffset];
  99597. byteArray[index + 2] = srcData[srcPos + bOffset];
  99598. byteArray[index + 3] = srcData[srcPos + aOffset];
  99599. index += 4;
  99600. }
  99601. }
  99602. return byteArray;
  99603. };
  99604. DDSTools._ExtractLongWordOrder = function (value) {
  99605. if (value === 0 || value === 255 || value === -16777216) {
  99606. return 0;
  99607. }
  99608. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  99609. };
  99610. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  99611. var byteArray = new Uint8Array(dataLength);
  99612. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  99613. var index = 0;
  99614. for (var y = 0; y < height; y++) {
  99615. for (var x = 0; x < width; x++) {
  99616. var srcPos = (x + y * width) * 3;
  99617. byteArray[index] = srcData[srcPos + rOffset];
  99618. byteArray[index + 1] = srcData[srcPos + gOffset];
  99619. byteArray[index + 2] = srcData[srcPos + bOffset];
  99620. index += 3;
  99621. }
  99622. }
  99623. return byteArray;
  99624. };
  99625. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  99626. var byteArray = new Uint8Array(dataLength);
  99627. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  99628. var index = 0;
  99629. for (var y = 0; y < height; y++) {
  99630. for (var x = 0; x < width; x++) {
  99631. var srcPos = (x + y * width);
  99632. byteArray[index] = srcData[srcPos];
  99633. index++;
  99634. }
  99635. }
  99636. return byteArray;
  99637. };
  99638. /**
  99639. * Uploads DDS Levels to a Babylon Texture
  99640. * @hidden
  99641. */
  99642. DDSTools.UploadDDSLevels = function (engine, texture, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  99643. if (lodIndex === void 0) { lodIndex = -1; }
  99644. var sphericalPolynomialFaces = null;
  99645. if (info.sphericalPolynomial) {
  99646. sphericalPolynomialFaces = new Array();
  99647. }
  99648. var ext = engine.getCaps().s3tc;
  99649. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  99650. var fourCC, width, height, dataLength = 0, dataOffset;
  99651. var byteArray, mipmapCount, mip;
  99652. var internalCompressedFormat = 0;
  99653. var blockBytes = 1;
  99654. if (header[off_magic] !== DDS_MAGIC) {
  99655. BABYLON.Tools.Error("Invalid magic number in DDS header");
  99656. return;
  99657. }
  99658. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  99659. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  99660. return;
  99661. }
  99662. if (info.isCompressed && !ext) {
  99663. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  99664. return;
  99665. }
  99666. var bpp = header[off_RGBbpp];
  99667. dataOffset = header[off_size] + 4;
  99668. var computeFormats = false;
  99669. if (info.isFourCC) {
  99670. fourCC = header[off_pfFourCC];
  99671. switch (fourCC) {
  99672. case FOURCC_DXT1:
  99673. blockBytes = 8;
  99674. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  99675. break;
  99676. case FOURCC_DXT3:
  99677. blockBytes = 16;
  99678. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  99679. break;
  99680. case FOURCC_DXT5:
  99681. blockBytes = 16;
  99682. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  99683. break;
  99684. case FOURCC_D3DFMT_R16G16B16A16F:
  99685. computeFormats = true;
  99686. break;
  99687. case FOURCC_D3DFMT_R32G32B32A32F:
  99688. computeFormats = true;
  99689. break;
  99690. case FOURCC_DX10:
  99691. // There is an additionnal header so dataOffset need to be changed
  99692. dataOffset += 5 * 4; // 5 uints
  99693. var supported = false;
  99694. switch (info.dxgiFormat) {
  99695. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  99696. computeFormats = true;
  99697. supported = true;
  99698. break;
  99699. case DXGI_FORMAT_B8G8R8X8_UNORM:
  99700. info.isRGB = true;
  99701. info.isFourCC = false;
  99702. bpp = 32;
  99703. supported = true;
  99704. break;
  99705. }
  99706. if (supported) {
  99707. break;
  99708. }
  99709. default:
  99710. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  99711. return;
  99712. }
  99713. }
  99714. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  99715. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  99716. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  99717. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  99718. if (computeFormats) {
  99719. internalCompressedFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  99720. }
  99721. mipmapCount = 1;
  99722. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  99723. mipmapCount = Math.max(1, header[off_mipmapCount]);
  99724. }
  99725. for (var face = 0; face < faces; face++) {
  99726. width = header[off_width];
  99727. height = header[off_height];
  99728. for (mip = 0; mip < mipmapCount; ++mip) {
  99729. if (lodIndex === -1 || lodIndex === mip) {
  99730. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  99731. var i = (lodIndex === -1) ? mip : 0;
  99732. if (!info.isCompressed && info.isFourCC) {
  99733. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  99734. dataLength = width * height * 4;
  99735. var floatArray = null;
  99736. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) { // Required because iOS has many issues with float and half float generation
  99737. if (bpp === 128) {
  99738. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  99739. if (sphericalPolynomialFaces && i == 0) {
  99740. sphericalPolynomialFaces.push(DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  99741. }
  99742. }
  99743. else if (bpp === 64) {
  99744. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  99745. if (sphericalPolynomialFaces && i == 0) {
  99746. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  99747. }
  99748. }
  99749. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  99750. }
  99751. else {
  99752. if (bpp === 128) {
  99753. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  99754. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  99755. if (sphericalPolynomialFaces && i == 0) {
  99756. sphericalPolynomialFaces.push(floatArray);
  99757. }
  99758. }
  99759. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  99760. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  99761. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  99762. if (sphericalPolynomialFaces && i == 0) {
  99763. sphericalPolynomialFaces.push(floatArray);
  99764. }
  99765. }
  99766. else { // 64
  99767. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  99768. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  99769. if (sphericalPolynomialFaces && i == 0) {
  99770. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  99771. }
  99772. }
  99773. }
  99774. if (floatArray) {
  99775. engine._uploadDataToTextureDirectly(texture, floatArray, face, i);
  99776. }
  99777. }
  99778. else if (info.isRGB) {
  99779. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  99780. if (bpp === 24) {
  99781. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGB;
  99782. dataLength = width * height * 3;
  99783. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  99784. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  99785. }
  99786. else { // 32
  99787. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  99788. dataLength = width * height * 4;
  99789. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  99790. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  99791. }
  99792. }
  99793. else if (info.isLuminance) {
  99794. var unpackAlignment = engine._getUnpackAlignement();
  99795. var unpaddedRowSize = width;
  99796. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  99797. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  99798. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  99799. texture.format = BABYLON.Engine.TEXTUREFORMAT_LUMINANCE;
  99800. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  99801. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  99802. }
  99803. else {
  99804. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  99805. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  99806. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  99807. engine._uploadCompressedDataToTextureDirectly(texture, internalCompressedFormat, width, height, byteArray, face, i);
  99808. }
  99809. }
  99810. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  99811. width *= 0.5;
  99812. height *= 0.5;
  99813. width = Math.max(1.0, width);
  99814. height = Math.max(1.0, height);
  99815. }
  99816. if (currentFace !== undefined) {
  99817. // Loading a single face
  99818. break;
  99819. }
  99820. }
  99821. if (sphericalPolynomialFaces && sphericalPolynomialFaces.length > 0) {
  99822. info.sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({
  99823. size: header[off_width],
  99824. right: sphericalPolynomialFaces[0],
  99825. left: sphericalPolynomialFaces[1],
  99826. up: sphericalPolynomialFaces[2],
  99827. down: sphericalPolynomialFaces[3],
  99828. front: sphericalPolynomialFaces[4],
  99829. back: sphericalPolynomialFaces[5],
  99830. format: BABYLON.Engine.TEXTUREFORMAT_RGBA,
  99831. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  99832. gammaSpace: false,
  99833. });
  99834. }
  99835. else {
  99836. info.sphericalPolynomial = undefined;
  99837. }
  99838. };
  99839. /**
  99840. * Gets or sets a boolean indicating that LOD info is stored in alpha channel (false by default)
  99841. */
  99842. DDSTools.StoreLODInAlphaChannel = false;
  99843. return DDSTools;
  99844. }());
  99845. BABYLON.DDSTools = DDSTools;
  99846. })(BABYLON || (BABYLON = {}));
  99847. //# sourceMappingURL=babylon.dds.js.map
  99848. var BABYLON;
  99849. (function (BABYLON) {
  99850. /**
  99851. * Implementation of the DDS Texture Loader.
  99852. */
  99853. var DDSTextureLoader = /** @class */ (function () {
  99854. function DDSTextureLoader() {
  99855. /**
  99856. * Defines wether the loader supports cascade loading the different faces.
  99857. */
  99858. this.supportCascades = true;
  99859. }
  99860. /**
  99861. * This returns if the loader support the current file information.
  99862. * @param extension defines the file extension of the file being loaded
  99863. * @param textureFormatInUse defines the current compressed format in use iun the engine
  99864. * @param fallback defines the fallback internal texture if any
  99865. * @param isBase64 defines whether the texture is encoded as a base64
  99866. * @param isBuffer defines whether the texture data are stored as a buffer
  99867. * @returns true if the loader can load the specified file
  99868. */
  99869. DDSTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  99870. return extension.indexOf(".dds") === 0;
  99871. };
  99872. /**
  99873. * Transform the url before loading if required.
  99874. * @param rootUrl the url of the texture
  99875. * @param textureFormatInUse defines the current compressed format in use iun the engine
  99876. * @returns the transformed texture
  99877. */
  99878. DDSTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  99879. return rootUrl;
  99880. };
  99881. /**
  99882. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  99883. * @param rootUrl the url of the texture
  99884. * @param textureFormatInUse defines the current compressed format in use iun the engine
  99885. * @returns the fallback texture
  99886. */
  99887. DDSTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  99888. return null;
  99889. };
  99890. /**
  99891. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  99892. * @param data contains the texture data
  99893. * @param texture defines the BabylonJS internal texture
  99894. * @param createPolynomials will be true if polynomials have been requested
  99895. * @param onLoad defines the callback to trigger once the texture is ready
  99896. * @param onError defines the callback to trigger in case of error
  99897. */
  99898. DDSTextureLoader.prototype.loadCubeData = function (imgs, texture, createPolynomials, onLoad, onError) {
  99899. var engine = texture.getEngine();
  99900. var info;
  99901. var loadMipmap = false;
  99902. if (Array.isArray(imgs)) {
  99903. for (var index = 0; index < imgs.length; index++) {
  99904. var data_1 = imgs[index];
  99905. info = BABYLON.DDSTools.GetDDSInfo(data_1);
  99906. texture.width = info.width;
  99907. texture.height = info.height;
  99908. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;
  99909. engine._unpackFlipY(info.isCompressed);
  99910. BABYLON.DDSTools.UploadDDSLevels(engine, texture, data_1, info, loadMipmap, 6, -1, index);
  99911. if (!info.isFourCC && info.mipmapCount === 1) {
  99912. engine.generateMipMapsForCubemap(texture);
  99913. }
  99914. }
  99915. }
  99916. else {
  99917. var data = imgs;
  99918. info = BABYLON.DDSTools.GetDDSInfo(data);
  99919. texture.width = info.width;
  99920. texture.height = info.height;
  99921. if (createPolynomials) {
  99922. info.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  99923. }
  99924. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;
  99925. engine._unpackFlipY(info.isCompressed);
  99926. BABYLON.DDSTools.UploadDDSLevels(engine, texture, data, info, loadMipmap, 6);
  99927. if (!info.isFourCC && info.mipmapCount === 1) {
  99928. engine.generateMipMapsForCubemap(texture);
  99929. }
  99930. }
  99931. engine._setCubeMapTextureParams(loadMipmap);
  99932. texture.isReady = true;
  99933. if (onLoad) {
  99934. onLoad({ isDDS: true, width: texture.width, info: info, data: imgs, texture: texture });
  99935. }
  99936. };
  99937. /**
  99938. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  99939. * @param data contains the texture data
  99940. * @param texture defines the BabylonJS internal texture
  99941. * @param callback defines the method to call once ready to upload
  99942. */
  99943. DDSTextureLoader.prototype.loadData = function (data, texture, callback) {
  99944. var info = BABYLON.DDSTools.GetDDSInfo(data);
  99945. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps && ((info.width >> (info.mipmapCount - 1)) === 1);
  99946. callback(info.width, info.height, loadMipmap, info.isFourCC, function () {
  99947. BABYLON.DDSTools.UploadDDSLevels(texture.getEngine(), texture, data, info, loadMipmap, 1);
  99948. });
  99949. };
  99950. return DDSTextureLoader;
  99951. }());
  99952. // Register the loader.
  99953. BABYLON.Engine._TextureLoaders.push(new DDSTextureLoader());
  99954. })(BABYLON || (BABYLON = {}));
  99955. //# sourceMappingURL=babylon.ddsTextureLoader.js.map
  99956. var BABYLON;
  99957. (function (BABYLON) {
  99958. /**
  99959. * Based on jsTGALoader - Javascript loader for TGA file
  99960. * By Vincent Thibault
  99961. * @see http://blog.robrowser.com/javascript-tga-loader.html
  99962. */
  99963. var TGATools = /** @class */ (function () {
  99964. function TGATools() {
  99965. }
  99966. /**
  99967. * Gets the header of a TGA file
  99968. * @param data defines the TGA data
  99969. * @returns the header
  99970. */
  99971. TGATools.GetTGAHeader = function (data) {
  99972. var offset = 0;
  99973. var header = {
  99974. id_length: data[offset++],
  99975. colormap_type: data[offset++],
  99976. image_type: data[offset++],
  99977. colormap_index: data[offset++] | data[offset++] << 8,
  99978. colormap_length: data[offset++] | data[offset++] << 8,
  99979. colormap_size: data[offset++],
  99980. origin: [
  99981. data[offset++] | data[offset++] << 8,
  99982. data[offset++] | data[offset++] << 8
  99983. ],
  99984. width: data[offset++] | data[offset++] << 8,
  99985. height: data[offset++] | data[offset++] << 8,
  99986. pixel_size: data[offset++],
  99987. flags: data[offset++]
  99988. };
  99989. return header;
  99990. };
  99991. /**
  99992. * Uploads TGA content to a Babylon Texture
  99993. * @hidden
  99994. */
  99995. TGATools.UploadContent = function (texture, data) {
  99996. // Not enough data to contain header ?
  99997. if (data.length < 19) {
  99998. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  99999. return;
  100000. }
  100001. // Read Header
  100002. var offset = 18;
  100003. var header = TGATools.GetTGAHeader(data);
  100004. // Assume it's a valid Targa file.
  100005. if (header.id_length + offset > data.length) {
  100006. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  100007. return;
  100008. }
  100009. // Skip not needed data
  100010. offset += header.id_length;
  100011. var use_rle = false;
  100012. var use_pal = false;
  100013. var use_grey = false;
  100014. // Get some informations.
  100015. switch (header.image_type) {
  100016. case TGATools._TYPE_RLE_INDEXED:
  100017. use_rle = true;
  100018. case TGATools._TYPE_INDEXED:
  100019. use_pal = true;
  100020. break;
  100021. case TGATools._TYPE_RLE_RGB:
  100022. use_rle = true;
  100023. case TGATools._TYPE_RGB:
  100024. // use_rgb = true;
  100025. break;
  100026. case TGATools._TYPE_RLE_GREY:
  100027. use_rle = true;
  100028. case TGATools._TYPE_GREY:
  100029. use_grey = true;
  100030. break;
  100031. }
  100032. var pixel_data;
  100033. // var numAlphaBits = header.flags & 0xf;
  100034. var pixel_size = header.pixel_size >> 3;
  100035. var pixel_total = header.width * header.height * pixel_size;
  100036. // Read palettes
  100037. var palettes;
  100038. if (use_pal) {
  100039. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  100040. }
  100041. // Read LRE
  100042. if (use_rle) {
  100043. pixel_data = new Uint8Array(pixel_total);
  100044. var c, count, i;
  100045. var localOffset = 0;
  100046. var pixels = new Uint8Array(pixel_size);
  100047. while (offset < pixel_total && localOffset < pixel_total) {
  100048. c = data[offset++];
  100049. count = (c & 0x7f) + 1;
  100050. // RLE pixels
  100051. if (c & 0x80) {
  100052. // Bind pixel tmp array
  100053. for (i = 0; i < pixel_size; ++i) {
  100054. pixels[i] = data[offset++];
  100055. }
  100056. // Copy pixel array
  100057. for (i = 0; i < count; ++i) {
  100058. pixel_data.set(pixels, localOffset + i * pixel_size);
  100059. }
  100060. localOffset += pixel_size * count;
  100061. }
  100062. // Raw pixels
  100063. else {
  100064. count *= pixel_size;
  100065. for (i = 0; i < count; ++i) {
  100066. pixel_data[localOffset + i] = data[offset++];
  100067. }
  100068. localOffset += count;
  100069. }
  100070. }
  100071. }
  100072. // RAW Pixels
  100073. else {
  100074. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  100075. }
  100076. // Load to texture
  100077. var x_start, y_start, x_step, y_step, y_end, x_end;
  100078. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  100079. default:
  100080. case TGATools._ORIGIN_UL:
  100081. x_start = 0;
  100082. x_step = 1;
  100083. x_end = header.width;
  100084. y_start = 0;
  100085. y_step = 1;
  100086. y_end = header.height;
  100087. break;
  100088. case TGATools._ORIGIN_BL:
  100089. x_start = 0;
  100090. x_step = 1;
  100091. x_end = header.width;
  100092. y_start = header.height - 1;
  100093. y_step = -1;
  100094. y_end = -1;
  100095. break;
  100096. case TGATools._ORIGIN_UR:
  100097. x_start = header.width - 1;
  100098. x_step = -1;
  100099. x_end = -1;
  100100. y_start = 0;
  100101. y_step = 1;
  100102. y_end = header.height;
  100103. break;
  100104. case TGATools._ORIGIN_BR:
  100105. x_start = header.width - 1;
  100106. x_step = -1;
  100107. x_end = -1;
  100108. y_start = header.height - 1;
  100109. y_step = -1;
  100110. y_end = -1;
  100111. break;
  100112. }
  100113. // Load the specify method
  100114. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  100115. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  100116. var engine = texture.getEngine();
  100117. engine._uploadDataToTextureDirectly(texture, imageData);
  100118. };
  100119. /** @hidden */
  100120. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  100121. var image = pixel_data, colormap = palettes;
  100122. var width = header.width, height = header.height;
  100123. var color, i = 0, x, y;
  100124. var imageData = new Uint8Array(width * height * 4);
  100125. for (y = y_start; y !== y_end; y += y_step) {
  100126. for (x = x_start; x !== x_end; x += x_step, i++) {
  100127. color = image[i];
  100128. imageData[(x + width * y) * 4 + 3] = 255;
  100129. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  100130. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  100131. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  100132. }
  100133. }
  100134. return imageData;
  100135. };
  100136. /** @hidden */
  100137. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  100138. var image = pixel_data;
  100139. var width = header.width, height = header.height;
  100140. var color, i = 0, x, y;
  100141. var imageData = new Uint8Array(width * height * 4);
  100142. for (y = y_start; y !== y_end; y += y_step) {
  100143. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  100144. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  100145. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  100146. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  100147. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  100148. imageData[(x + width * y) * 4 + 0] = r;
  100149. imageData[(x + width * y) * 4 + 1] = g;
  100150. imageData[(x + width * y) * 4 + 2] = b;
  100151. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  100152. }
  100153. }
  100154. return imageData;
  100155. };
  100156. /** @hidden */
  100157. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  100158. var image = pixel_data;
  100159. var width = header.width, height = header.height;
  100160. var i = 0, x, y;
  100161. var imageData = new Uint8Array(width * height * 4);
  100162. for (y = y_start; y !== y_end; y += y_step) {
  100163. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  100164. imageData[(x + width * y) * 4 + 3] = 255;
  100165. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  100166. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  100167. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  100168. }
  100169. }
  100170. return imageData;
  100171. };
  100172. /** @hidden */
  100173. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  100174. var image = pixel_data;
  100175. var width = header.width, height = header.height;
  100176. var i = 0, x, y;
  100177. var imageData = new Uint8Array(width * height * 4);
  100178. for (y = y_start; y !== y_end; y += y_step) {
  100179. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  100180. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  100181. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  100182. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  100183. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  100184. }
  100185. }
  100186. return imageData;
  100187. };
  100188. /** @hidden */
  100189. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  100190. var image = pixel_data;
  100191. var width = header.width, height = header.height;
  100192. var color, i = 0, x, y;
  100193. var imageData = new Uint8Array(width * height * 4);
  100194. for (y = y_start; y !== y_end; y += y_step) {
  100195. for (x = x_start; x !== x_end; x += x_step, i++) {
  100196. color = image[i];
  100197. imageData[(x + width * y) * 4 + 0] = color;
  100198. imageData[(x + width * y) * 4 + 1] = color;
  100199. imageData[(x + width * y) * 4 + 2] = color;
  100200. imageData[(x + width * y) * 4 + 3] = 255;
  100201. }
  100202. }
  100203. return imageData;
  100204. };
  100205. /** @hidden */
  100206. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  100207. var image = pixel_data;
  100208. var width = header.width, height = header.height;
  100209. var i = 0, x, y;
  100210. var imageData = new Uint8Array(width * height * 4);
  100211. for (y = y_start; y !== y_end; y += y_step) {
  100212. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  100213. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  100214. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  100215. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  100216. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  100217. }
  100218. }
  100219. return imageData;
  100220. };
  100221. //private static _TYPE_NO_DATA = 0;
  100222. TGATools._TYPE_INDEXED = 1;
  100223. TGATools._TYPE_RGB = 2;
  100224. TGATools._TYPE_GREY = 3;
  100225. TGATools._TYPE_RLE_INDEXED = 9;
  100226. TGATools._TYPE_RLE_RGB = 10;
  100227. TGATools._TYPE_RLE_GREY = 11;
  100228. TGATools._ORIGIN_MASK = 0x30;
  100229. TGATools._ORIGIN_SHIFT = 0x04;
  100230. TGATools._ORIGIN_BL = 0x00;
  100231. TGATools._ORIGIN_BR = 0x01;
  100232. TGATools._ORIGIN_UL = 0x02;
  100233. TGATools._ORIGIN_UR = 0x03;
  100234. return TGATools;
  100235. }());
  100236. BABYLON.TGATools = TGATools;
  100237. })(BABYLON || (BABYLON = {}));
  100238. //# sourceMappingURL=babylon.tga.js.map
  100239. var BABYLON;
  100240. (function (BABYLON) {
  100241. /**
  100242. * Implementation of the TGA Texture Loader.
  100243. */
  100244. var TGATextureLoader = /** @class */ (function () {
  100245. function TGATextureLoader() {
  100246. /**
  100247. * Defines wether the loader supports cascade loading the different faces.
  100248. */
  100249. this.supportCascades = false;
  100250. }
  100251. /**
  100252. * This returns if the loader support the current file information.
  100253. * @param extension defines the file extension of the file being loaded
  100254. * @param textureFormatInUse defines the current compressed format in use iun the engine
  100255. * @param fallback defines the fallback internal texture if any
  100256. * @param isBase64 defines whether the texture is encoded as a base64
  100257. * @param isBuffer defines whether the texture data are stored as a buffer
  100258. * @returns true if the loader can load the specified file
  100259. */
  100260. TGATextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  100261. return extension.indexOf(".tga") === 0;
  100262. };
  100263. /**
  100264. * Transform the url before loading if required.
  100265. * @param rootUrl the url of the texture
  100266. * @param textureFormatInUse defines the current compressed format in use iun the engine
  100267. * @returns the transformed texture
  100268. */
  100269. TGATextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  100270. return rootUrl;
  100271. };
  100272. /**
  100273. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  100274. * @param rootUrl the url of the texture
  100275. * @param textureFormatInUse defines the current compressed format in use iun the engine
  100276. * @returns the fallback texture
  100277. */
  100278. TGATextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  100279. return null;
  100280. };
  100281. /**
  100282. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  100283. * @param data contains the texture data
  100284. * @param texture defines the BabylonJS internal texture
  100285. * @param createPolynomials will be true if polynomials have been requested
  100286. * @param onLoad defines the callback to trigger once the texture is ready
  100287. * @param onError defines the callback to trigger in case of error
  100288. */
  100289. TGATextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  100290. throw ".env not supported in Cube.";
  100291. };
  100292. /**
  100293. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  100294. * @param data contains the texture data
  100295. * @param texture defines the BabylonJS internal texture
  100296. * @param callback defines the method to call once ready to upload
  100297. */
  100298. TGATextureLoader.prototype.loadData = function (data, texture, callback) {
  100299. var uintData = new Uint8Array(data);
  100300. var header = BABYLON.TGATools.GetTGAHeader(uintData);
  100301. callback(header.width, header.height, texture.generateMipMaps, false, function () {
  100302. BABYLON.TGATools.UploadContent(texture, uintData);
  100303. });
  100304. };
  100305. return TGATextureLoader;
  100306. }());
  100307. // Register the loader.
  100308. BABYLON.Engine._TextureLoaders.push(new TGATextureLoader());
  100309. })(BABYLON || (BABYLON = {}));
  100310. //# sourceMappingURL=babylon.tgaTextureLoader.js.map
  100311. var BABYLON;
  100312. (function (BABYLON) {
  100313. /**
  100314. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  100315. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  100316. */
  100317. var KhronosTextureContainer = /** @class */ (function () {
  100318. /**
  100319. * Creates a new KhronosTextureContainer
  100320. * @param arrayBuffer contents of the KTX container file
  100321. * @param facesExpected should be either 1 or 6, based whether a cube texture or or
  100322. * @param threeDExpected provision for indicating that data should be a 3D texture, not implemented
  100323. * @param textureArrayExpected provision for indicating that data should be a texture array, not implemented
  100324. */
  100325. function KhronosTextureContainer(
  100326. /** contents of the KTX container file */
  100327. arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  100328. this.arrayBuffer = arrayBuffer;
  100329. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  100330. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  100331. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  100332. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  100333. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  100334. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  100335. BABYLON.Tools.Error("texture missing KTX identifier");
  100336. return;
  100337. }
  100338. // load the reset of the header in native 32 bit int
  100339. var header = new Int32Array(this.arrayBuffer, 12, 13);
  100340. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  100341. var oppositeEndianess = header[0] === 0x01020304;
  100342. // read all the header elements in order they exist in the file, without modification (sans endainness)
  100343. this.glType = oppositeEndianess ? this.switchEndianness(header[1]) : header[1]; // must be 0 for compressed textures
  100344. this.glTypeSize = oppositeEndianess ? this.switchEndianness(header[2]) : header[2]; // must be 1 for compressed textures
  100345. this.glFormat = oppositeEndianess ? this.switchEndianness(header[3]) : header[3]; // must be 0 for compressed textures
  100346. this.glInternalFormat = oppositeEndianess ? this.switchEndianness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  100347. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndianness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  100348. this.pixelWidth = oppositeEndianess ? this.switchEndianness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  100349. this.pixelHeight = oppositeEndianess ? this.switchEndianness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  100350. this.pixelDepth = oppositeEndianess ? this.switchEndianness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  100351. this.numberOfArrayElements = oppositeEndianess ? this.switchEndianness(header[9]) : header[9]; // used for texture arrays
  100352. this.numberOfFaces = oppositeEndianess ? this.switchEndianness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  100353. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndianness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  100354. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndianness(header[12]) : header[12]; // the amount of space after the header for meta-data
  100355. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  100356. if (this.glType !== 0) {
  100357. BABYLON.Tools.Error("only compressed formats currently supported");
  100358. return;
  100359. }
  100360. else {
  100361. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  100362. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  100363. }
  100364. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  100365. BABYLON.Tools.Error("only 2D textures currently supported");
  100366. return;
  100367. }
  100368. if (this.numberOfArrayElements !== 0) {
  100369. BABYLON.Tools.Error("texture arrays not currently supported");
  100370. return;
  100371. }
  100372. if (this.numberOfFaces !== facesExpected) {
  100373. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  100374. return;
  100375. }
  100376. // we now have a completely validated file, so could use existence of loadType as success
  100377. // would need to make this more elaborate & adjust checks above to support more than one load type
  100378. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  100379. }
  100380. //
  100381. /**
  100382. * Revert the endianness of a value.
  100383. * Not as fast hardware based, but will probably never need to use
  100384. * @param val defines the value to convert
  100385. * @returns the new value
  100386. */
  100387. KhronosTextureContainer.prototype.switchEndianness = function (val) {
  100388. return ((val & 0xFF) << 24)
  100389. | ((val & 0xFF00) << 8)
  100390. | ((val >> 8) & 0xFF00)
  100391. | ((val >> 24) & 0xFF);
  100392. };
  100393. /**
  100394. * Uploads KTX content to a Babylon Texture.
  100395. * It is assumed that the texture has already been created & is currently bound
  100396. * @hidden
  100397. */
  100398. KhronosTextureContainer.prototype.uploadLevels = function (texture, loadMipmaps) {
  100399. switch (this.loadType) {
  100400. case KhronosTextureContainer.COMPRESSED_2D:
  100401. this._upload2DCompressedLevels(texture, loadMipmaps);
  100402. break;
  100403. case KhronosTextureContainer.TEX_2D:
  100404. case KhronosTextureContainer.COMPRESSED_3D:
  100405. case KhronosTextureContainer.TEX_3D:
  100406. }
  100407. };
  100408. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (texture, loadMipmaps) {
  100409. // initialize width & height for level 1
  100410. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  100411. var width = this.pixelWidth;
  100412. var height = this.pixelHeight;
  100413. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  100414. for (var level = 0; level < mipmapCount; level++) {
  100415. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  100416. dataOffset += 4; //image data starts from next multiple of 4 offset. Each face refers to same imagesize field above.
  100417. for (var face = 0; face < this.numberOfFaces; face++) {
  100418. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset, imageSize);
  100419. var engine = texture.getEngine();
  100420. engine._uploadCompressedDataToTextureDirectly(texture, this.glInternalFormat, width, height, byteArray, face, level);
  100421. dataOffset += imageSize; // add size of the image for the next face/mipmap
  100422. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  100423. }
  100424. width = Math.max(1.0, width * 0.5);
  100425. height = Math.max(1.0, height * 0.5);
  100426. }
  100427. };
  100428. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  100429. // load types
  100430. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  100431. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  100432. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  100433. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  100434. return KhronosTextureContainer;
  100435. }());
  100436. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  100437. })(BABYLON || (BABYLON = {}));
  100438. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  100439. var BABYLON;
  100440. (function (BABYLON) {
  100441. /**
  100442. * Implementation of the KTX Texture Loader.
  100443. */
  100444. var KTXTextureLoader = /** @class */ (function () {
  100445. function KTXTextureLoader() {
  100446. /**
  100447. * Defines wether the loader supports cascade loading the different faces.
  100448. */
  100449. this.supportCascades = false;
  100450. }
  100451. /**
  100452. * This returns if the loader support the current file information.
  100453. * @param extension defines the file extension of the file being loaded
  100454. * @param textureFormatInUse defines the current compressed format in use iun the engine
  100455. * @param fallback defines the fallback internal texture if any
  100456. * @param isBase64 defines whether the texture is encoded as a base64
  100457. * @param isBuffer defines whether the texture data are stored as a buffer
  100458. * @returns true if the loader can load the specified file
  100459. */
  100460. KTXTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  100461. if (textureFormatInUse && !isBase64 && !fallback && !isBuffer) {
  100462. return true;
  100463. }
  100464. return false;
  100465. };
  100466. /**
  100467. * Transform the url before loading if required.
  100468. * @param rootUrl the url of the texture
  100469. * @param textureFormatInUse defines the current compressed format in use iun the engine
  100470. * @returns the transformed texture
  100471. */
  100472. KTXTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  100473. var lastDot = rootUrl.lastIndexOf('.');
  100474. return (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + textureFormatInUse;
  100475. };
  100476. /**
  100477. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  100478. * @param rootUrl the url of the texture
  100479. * @param textureFormatInUse defines the current compressed format in use iun the engine
  100480. * @returns the fallback texture
  100481. */
  100482. KTXTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  100483. // remove the format appended to the rootUrl in the original createCubeTexture call.
  100484. var exp = new RegExp("" + textureFormatInUse + "$");
  100485. return rootUrl.replace(exp, "");
  100486. };
  100487. /**
  100488. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  100489. * @param data contains the texture data
  100490. * @param texture defines the BabylonJS internal texture
  100491. * @param createPolynomials will be true if polynomials have been requested
  100492. * @param onLoad defines the callback to trigger once the texture is ready
  100493. * @param onError defines the callback to trigger in case of error
  100494. */
  100495. KTXTextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  100496. if (Array.isArray(data)) {
  100497. return;
  100498. }
  100499. var engine = texture.getEngine();
  100500. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  100501. var loadMipmap = ktx.numberOfMipmapLevels > 1 && texture.generateMipMaps;
  100502. engine._unpackFlipY(true);
  100503. ktx.uploadLevels(texture, texture.generateMipMaps);
  100504. texture.width = ktx.pixelWidth;
  100505. texture.height = ktx.pixelHeight;
  100506. engine._setCubeMapTextureParams(loadMipmap);
  100507. texture.isReady = true;
  100508. };
  100509. /**
  100510. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  100511. * @param data contains the texture data
  100512. * @param texture defines the BabylonJS internal texture
  100513. * @param callback defines the method to call once ready to upload
  100514. */
  100515. KTXTextureLoader.prototype.loadData = function (data, texture, callback) {
  100516. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  100517. callback(ktx.pixelWidth, ktx.pixelHeight, false, true, function () {
  100518. ktx.uploadLevels(texture, texture.generateMipMaps);
  100519. });
  100520. };
  100521. return KTXTextureLoader;
  100522. }());
  100523. // Register the loader.
  100524. BABYLON.Engine._TextureLoaders.unshift(new KTXTextureLoader());
  100525. })(BABYLON || (BABYLON = {}));
  100526. //# sourceMappingURL=babylon.ktxTextureLoader.js.map
  100527. var BABYLON;
  100528. (function (BABYLON) {
  100529. /**
  100530. * Sets of helpers addressing the serialization and deserialization of environment texture
  100531. * stored in a BabylonJS env file.
  100532. * Those files are usually stored as .env files.
  100533. */
  100534. var EnvironmentTextureTools = /** @class */ (function () {
  100535. function EnvironmentTextureTools() {
  100536. }
  100537. /**
  100538. * Gets the environment info from an env file.
  100539. * @param data The array buffer containing the .env bytes.
  100540. * @returns the environment file info (the json header) if successfully parsed.
  100541. */
  100542. EnvironmentTextureTools.GetEnvInfo = function (data) {
  100543. var dataView = new DataView(data);
  100544. var pos = 0;
  100545. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  100546. if (dataView.getUint8(pos++) !== EnvironmentTextureTools._MagicBytes[i]) {
  100547. BABYLON.Tools.Error('Not a babylon environment map');
  100548. return null;
  100549. }
  100550. }
  100551. // Read json manifest - collect characters up to null terminator
  100552. var manifestString = '';
  100553. var charCode = 0x00;
  100554. while ((charCode = dataView.getUint8(pos++))) {
  100555. manifestString += String.fromCharCode(charCode);
  100556. }
  100557. var manifest = JSON.parse(manifestString);
  100558. if (manifest.specular) {
  100559. // Extend the header with the position of the payload.
  100560. manifest.specular.specularDataPosition = pos;
  100561. // Fallback to 0.8 exactly if lodGenerationScale is not defined for backward compatibility.
  100562. manifest.specular.lodGenerationScale = manifest.specular.lodGenerationScale || 0.8;
  100563. }
  100564. return manifest;
  100565. };
  100566. /**
  100567. * Creates an environment texture from a loaded cube texture.
  100568. * @param texture defines the cube texture to convert in env file
  100569. * @return a promise containing the environment data if succesfull.
  100570. */
  100571. EnvironmentTextureTools.CreateEnvTextureAsync = function (texture) {
  100572. var _this = this;
  100573. var internalTexture = texture.getInternalTexture();
  100574. if (!internalTexture) {
  100575. return Promise.reject("The cube texture is invalid.");
  100576. }
  100577. if (!texture._prefiltered) {
  100578. return Promise.reject("The cube texture is invalid (not prefiltered).");
  100579. }
  100580. var engine = internalTexture.getEngine();
  100581. if (engine && engine.premultipliedAlpha) {
  100582. return Promise.reject("Env texture can only be created when the engine is created with the premultipliedAlpha option set to false.");
  100583. }
  100584. if (texture.textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  100585. return Promise.reject("The cube texture should allow HDR (Full Float or Half Float).");
  100586. }
  100587. var canvas = engine.getRenderingCanvas();
  100588. if (!canvas) {
  100589. return Promise.reject("Env texture can only be created when the engine is associated to a canvas.");
  100590. }
  100591. var textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  100592. if (!engine.getCaps().textureFloatRender) {
  100593. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  100594. if (!engine.getCaps().textureHalfFloatRender) {
  100595. return Promise.reject("Env texture can only be created when the browser supports half float or full float rendering.");
  100596. }
  100597. }
  100598. var cubeWidth = internalTexture.width;
  100599. var hostingScene = new BABYLON.Scene(engine);
  100600. var specularTextures = {};
  100601. var promises = [];
  100602. // Read and collect all mipmaps data from the cube.
  100603. var mipmapsCount = BABYLON.Scalar.Log2(internalTexture.width);
  100604. mipmapsCount = Math.round(mipmapsCount);
  100605. var _loop_1 = function (i) {
  100606. var faceWidth = Math.pow(2, mipmapsCount - i);
  100607. var _loop_2 = function (face) {
  100608. var data = texture.readPixels(face, i);
  100609. // Creates a temp texture with the face data.
  100610. var tempTexture = engine.createRawTexture(data, faceWidth, faceWidth, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, textureType);
  100611. // And rgbdEncode them.
  100612. var promise = new Promise(function (resolve, reject) {
  100613. 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);
  100614. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  100615. rgbdPostProcess.onApply = function (effect) {
  100616. effect._bindTexture("textureSampler", tempTexture);
  100617. };
  100618. // As the process needs to happen on the main canvas, keep track of the current size
  100619. var currentW = engine.getRenderWidth();
  100620. var currentH = engine.getRenderHeight();
  100621. // Set the desired size for the texture
  100622. engine.setSize(faceWidth, faceWidth);
  100623. hostingScene.postProcessManager.directRender([rgbdPostProcess], null);
  100624. // Reading datas from WebGL
  100625. BABYLON.Tools.ToBlob(canvas, function (blob) {
  100626. var fileReader = new FileReader();
  100627. fileReader.onload = function (event) {
  100628. var arrayBuffer = event.target.result;
  100629. specularTextures[i * 6 + face] = arrayBuffer;
  100630. resolve();
  100631. };
  100632. fileReader.readAsArrayBuffer(blob);
  100633. });
  100634. // Reapply the previous canvas size
  100635. engine.setSize(currentW, currentH);
  100636. });
  100637. });
  100638. promises.push(promise);
  100639. };
  100640. // All faces of the cube.
  100641. for (var face = 0; face < 6; face++) {
  100642. _loop_2(face);
  100643. }
  100644. };
  100645. for (var i = 0; i <= mipmapsCount; i++) {
  100646. _loop_1(i);
  100647. }
  100648. // Once all the textures haves been collected as RGBD stored in PNGs
  100649. return Promise.all(promises).then(function () {
  100650. // We can delete the hosting scene keeping track of all the creation objects
  100651. hostingScene.dispose();
  100652. // Creates the json header for the env texture
  100653. var info = {
  100654. version: 1,
  100655. width: cubeWidth,
  100656. irradiance: _this._CreateEnvTextureIrradiance(texture),
  100657. specular: {
  100658. mipmaps: [],
  100659. lodGenerationScale: texture.lodGenerationScale
  100660. }
  100661. };
  100662. // Sets the specular image data information
  100663. var position = 0;
  100664. for (var i = 0; i <= mipmapsCount; i++) {
  100665. for (var face = 0; face < 6; face++) {
  100666. var byteLength = specularTextures[i * 6 + face].byteLength;
  100667. info.specular.mipmaps.push({
  100668. length: byteLength,
  100669. position: position
  100670. });
  100671. position += byteLength;
  100672. }
  100673. }
  100674. // Encode the JSON as an array buffer
  100675. var infoString = JSON.stringify(info);
  100676. var infoBuffer = new ArrayBuffer(infoString.length + 1);
  100677. var infoView = new Uint8Array(infoBuffer); // Limited to ascii subset matching unicode.
  100678. for (var i = 0, strLen = infoString.length; i < strLen; i++) {
  100679. infoView[i] = infoString.charCodeAt(i);
  100680. }
  100681. // Ends up with a null terminator for easier parsing
  100682. infoView[infoString.length] = 0x00;
  100683. // Computes the final required size and creates the storage
  100684. var totalSize = EnvironmentTextureTools._MagicBytes.length + position + infoBuffer.byteLength;
  100685. var finalBuffer = new ArrayBuffer(totalSize);
  100686. var finalBufferView = new Uint8Array(finalBuffer);
  100687. var dataView = new DataView(finalBuffer);
  100688. // Copy the magic bytes identifying the file in
  100689. var pos = 0;
  100690. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  100691. dataView.setUint8(pos++, EnvironmentTextureTools._MagicBytes[i]);
  100692. }
  100693. // Add the json info
  100694. finalBufferView.set(new Uint8Array(infoBuffer), pos);
  100695. pos += infoBuffer.byteLength;
  100696. // Finally inserts the texture data
  100697. for (var i = 0; i <= mipmapsCount; i++) {
  100698. for (var face = 0; face < 6; face++) {
  100699. var dataBuffer = specularTextures[i * 6 + face];
  100700. finalBufferView.set(new Uint8Array(dataBuffer), pos);
  100701. pos += dataBuffer.byteLength;
  100702. }
  100703. }
  100704. // Voila
  100705. return finalBuffer;
  100706. });
  100707. };
  100708. /**
  100709. * Creates a JSON representation of the spherical data.
  100710. * @param texture defines the texture containing the polynomials
  100711. * @return the JSON representation of the spherical info
  100712. */
  100713. EnvironmentTextureTools._CreateEnvTextureIrradiance = function (texture) {
  100714. var polynmials = texture.sphericalPolynomial;
  100715. if (polynmials == null) {
  100716. return null;
  100717. }
  100718. return {
  100719. x: [polynmials.x.x, polynmials.x.y, polynmials.x.z],
  100720. y: [polynmials.y.x, polynmials.y.y, polynmials.y.z],
  100721. z: [polynmials.z.x, polynmials.z.y, polynmials.z.z],
  100722. xx: [polynmials.xx.x, polynmials.xx.y, polynmials.xx.z],
  100723. yy: [polynmials.yy.x, polynmials.yy.y, polynmials.yy.z],
  100724. zz: [polynmials.zz.x, polynmials.zz.y, polynmials.zz.z],
  100725. yz: [polynmials.yz.x, polynmials.yz.y, polynmials.yz.z],
  100726. zx: [polynmials.zx.x, polynmials.zx.y, polynmials.zx.z],
  100727. xy: [polynmials.xy.x, polynmials.xy.y, polynmials.xy.z]
  100728. };
  100729. };
  100730. /**
  100731. * Uploads the texture info contained in the env file to the GPU.
  100732. * @param texture defines the internal texture to upload to
  100733. * @param arrayBuffer defines the buffer cotaining the data to load
  100734. * @param info defines the texture info retrieved through the GetEnvInfo method
  100735. * @returns a promise
  100736. */
  100737. EnvironmentTextureTools.UploadEnvLevelsAsync = function (texture, arrayBuffer, info) {
  100738. if (info.version !== 1) {
  100739. throw new Error("Unsupported babylon environment map version \"" + info.version + "\"");
  100740. }
  100741. var specularInfo = info.specular;
  100742. if (!specularInfo) {
  100743. // Nothing else parsed so far
  100744. return Promise.resolve();
  100745. }
  100746. // Double checks the enclosed info
  100747. var mipmapsCount = BABYLON.Scalar.Log2(info.width);
  100748. mipmapsCount = Math.round(mipmapsCount) + 1;
  100749. if (specularInfo.mipmaps.length !== 6 * mipmapsCount) {
  100750. throw new Error("Unsupported specular mipmaps number \"" + specularInfo.mipmaps.length + "\"");
  100751. }
  100752. texture._lodGenerationScale = specularInfo.lodGenerationScale;
  100753. var imageData = new Array(mipmapsCount);
  100754. for (var i = 0; i < mipmapsCount; i++) {
  100755. imageData[i] = new Array(6);
  100756. for (var face = 0; face < 6; face++) {
  100757. var imageInfo = specularInfo.mipmaps[i * 6 + face];
  100758. imageData[i][face] = new Uint8Array(arrayBuffer, specularInfo.specularDataPosition + imageInfo.position, imageInfo.length);
  100759. }
  100760. }
  100761. return EnvironmentTextureTools.UploadLevelsAsync(texture, imageData);
  100762. };
  100763. /**
  100764. * Uploads the levels of image data to the GPU.
  100765. * @param texture defines the internal texture to upload to
  100766. * @param imageData defines the array buffer views of image data [mipmap][face]
  100767. * @returns a promise
  100768. */
  100769. EnvironmentTextureTools.UploadLevelsAsync = function (texture, imageData) {
  100770. if (!BABYLON.Tools.IsExponentOfTwo(texture.width)) {
  100771. throw new Error("Texture size must be a power of two");
  100772. }
  100773. var mipmapsCount = Math.round(BABYLON.Scalar.Log2(texture.width)) + 1;
  100774. // Gets everything ready.
  100775. var engine = texture.getEngine();
  100776. var expandTexture = false;
  100777. var generateNonLODTextures = false;
  100778. var rgbdPostProcess = null;
  100779. var cubeRtt = null;
  100780. var lodTextures = null;
  100781. var caps = engine.getCaps();
  100782. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  100783. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  100784. texture.generateMipMaps = true;
  100785. engine.updateTextureSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE, texture);
  100786. // Add extra process if texture lod is not supported
  100787. if (!caps.textureLOD) {
  100788. expandTexture = false;
  100789. generateNonLODTextures = true;
  100790. lodTextures = {};
  100791. }
  100792. // in webgl 1 there are no ways to either render or copy lod level information for float textures.
  100793. else if (engine.webGLVersion < 2) {
  100794. expandTexture = false;
  100795. }
  100796. // If half float available we can uncompress the texture
  100797. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  100798. expandTexture = true;
  100799. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  100800. }
  100801. // If full float available we can uncompress the texture
  100802. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  100803. expandTexture = true;
  100804. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  100805. }
  100806. // Expand the texture if possible
  100807. if (expandTexture) {
  100808. // Simply run through the decode PP
  100809. rgbdPostProcess = new BABYLON.PostProcess("rgbdDecode", "rgbdDecode", null, null, 1, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, engine, false, undefined, texture.type, undefined, null, false);
  100810. texture._isRGBD = false;
  100811. texture.invertY = false;
  100812. cubeRtt = engine.createRenderTargetCubeTexture(texture.width, {
  100813. generateDepthBuffer: false,
  100814. generateMipMaps: true,
  100815. generateStencilBuffer: false,
  100816. samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE,
  100817. type: texture.type,
  100818. format: BABYLON.Engine.TEXTUREFORMAT_RGBA
  100819. });
  100820. }
  100821. else {
  100822. texture._isRGBD = true;
  100823. texture.invertY = true;
  100824. // In case of missing support, applies the same patch than DDS files.
  100825. if (generateNonLODTextures) {
  100826. var mipSlices = 3;
  100827. var scale = texture._lodGenerationScale;
  100828. var offset = texture._lodGenerationOffset;
  100829. for (var i = 0; i < mipSlices; i++) {
  100830. //compute LOD from even spacing in smoothness (matching shader calculation)
  100831. var smoothness = i / (mipSlices - 1);
  100832. var roughness = 1 - smoothness;
  100833. var minLODIndex = offset; // roughness = 0
  100834. var maxLODIndex = (mipmapsCount - 1) * scale + offset; // roughness = 1 (mipmaps start from 0)
  100835. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  100836. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  100837. var glTextureFromLod = new BABYLON.InternalTexture(engine, BABYLON.InternalTexture.DATASOURCE_TEMP);
  100838. glTextureFromLod.isCube = true;
  100839. glTextureFromLod.invertY = true;
  100840. glTextureFromLod.generateMipMaps = false;
  100841. engine.updateTextureSamplingMode(BABYLON.Texture.LINEAR_LINEAR, glTextureFromLod);
  100842. // Wrap in a base texture for easy binding.
  100843. var lodTexture = new BABYLON.BaseTexture(null);
  100844. lodTexture.isCube = true;
  100845. lodTexture._texture = glTextureFromLod;
  100846. lodTextures[mipmapIndex] = lodTexture;
  100847. switch (i) {
  100848. case 0:
  100849. texture._lodTextureLow = lodTexture;
  100850. break;
  100851. case 1:
  100852. texture._lodTextureMid = lodTexture;
  100853. break;
  100854. case 2:
  100855. texture._lodTextureHigh = lodTexture;
  100856. break;
  100857. }
  100858. }
  100859. }
  100860. }
  100861. var promises = [];
  100862. var _loop_3 = function (i) {
  100863. var _loop_4 = function (face) {
  100864. // Constructs an image element from image data
  100865. var bytes = imageData[i][face];
  100866. var blob = new Blob([bytes], { type: 'image/png' });
  100867. var url = URL.createObjectURL(blob);
  100868. var image = new Image();
  100869. image.src = url;
  100870. // Enqueue promise to upload to the texture.
  100871. var promise = new Promise(function (resolve, reject) {
  100872. image.onload = function () {
  100873. if (expandTexture) {
  100874. var tempTexture_1 = engine.createTexture(null, true, true, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, function (message) {
  100875. reject(message);
  100876. }, image);
  100877. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  100878. // Uncompress the data to a RTT
  100879. rgbdPostProcess.onApply = function (effect) {
  100880. effect._bindTexture("textureSampler", tempTexture_1);
  100881. effect.setFloat2("scale", 1, 1);
  100882. };
  100883. engine.scenes[0].postProcessManager.directRender([rgbdPostProcess], cubeRtt, true, face, i);
  100884. // Cleanup
  100885. engine.restoreDefaultFramebuffer();
  100886. tempTexture_1.dispose();
  100887. window.URL.revokeObjectURL(url);
  100888. resolve();
  100889. });
  100890. }
  100891. else {
  100892. engine._uploadImageToTexture(texture, image, face, i);
  100893. // Upload the face to the non lod texture support
  100894. if (generateNonLODTextures) {
  100895. var lodTexture = lodTextures[i];
  100896. if (lodTexture) {
  100897. engine._uploadImageToTexture(lodTexture._texture, image, face, 0);
  100898. }
  100899. }
  100900. resolve();
  100901. }
  100902. };
  100903. image.onerror = function (error) {
  100904. reject(error);
  100905. };
  100906. });
  100907. promises.push(promise);
  100908. };
  100909. // All faces
  100910. for (var face = 0; face < 6; face++) {
  100911. _loop_4(face);
  100912. }
  100913. };
  100914. // All mipmaps up to provided number of images
  100915. for (var i = 0; i < imageData.length; i++) {
  100916. _loop_3(i);
  100917. }
  100918. // Fill remaining mipmaps with black textures.
  100919. if (imageData.length < mipmapsCount) {
  100920. var data = void 0;
  100921. var size = Math.pow(2, mipmapsCount - 1 - imageData.length);
  100922. var dataLength = size * size * 4;
  100923. switch (texture.type) {
  100924. case BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT: {
  100925. data = new Uint8Array(dataLength);
  100926. break;
  100927. }
  100928. case BABYLON.Engine.TEXTURETYPE_HALF_FLOAT: {
  100929. data = new Uint16Array(dataLength);
  100930. break;
  100931. }
  100932. case BABYLON.Engine.TEXTURETYPE_FLOAT: {
  100933. data = new Float32Array(dataLength);
  100934. break;
  100935. }
  100936. }
  100937. for (var i = imageData.length; i < mipmapsCount; i++) {
  100938. for (var face = 0; face < 6; face++) {
  100939. engine._uploadArrayBufferViewToTexture(texture, data, face, i);
  100940. }
  100941. }
  100942. }
  100943. // Once all done, finishes the cleanup and return
  100944. return Promise.all(promises).then(function () {
  100945. // Release temp RTT.
  100946. if (cubeRtt) {
  100947. engine._releaseFramebufferObjects(cubeRtt);
  100948. cubeRtt._swapAndDie(texture);
  100949. }
  100950. // Release temp Post Process.
  100951. if (rgbdPostProcess) {
  100952. rgbdPostProcess.dispose();
  100953. }
  100954. // Flag internal texture as ready in case they are in use.
  100955. if (generateNonLODTextures) {
  100956. if (texture._lodTextureHigh && texture._lodTextureHigh._texture) {
  100957. texture._lodTextureHigh._texture.isReady = true;
  100958. }
  100959. if (texture._lodTextureMid && texture._lodTextureMid._texture) {
  100960. texture._lodTextureMid._texture.isReady = true;
  100961. }
  100962. if (texture._lodTextureLow && texture._lodTextureLow._texture) {
  100963. texture._lodTextureLow._texture.isReady = true;
  100964. }
  100965. }
  100966. });
  100967. };
  100968. /**
  100969. * Uploads spherical polynomials information to the texture.
  100970. * @param texture defines the texture we are trying to upload the information to
  100971. * @param info defines the environment texture info retrieved through the GetEnvInfo method
  100972. */
  100973. EnvironmentTextureTools.UploadEnvSpherical = function (texture, info) {
  100974. if (info.version !== 1) {
  100975. BABYLON.Tools.Warn('Unsupported babylon environment map version "' + info.version + '"');
  100976. }
  100977. var irradianceInfo = info.irradiance;
  100978. if (!irradianceInfo) {
  100979. return;
  100980. }
  100981. var sp = new BABYLON.SphericalPolynomial();
  100982. BABYLON.Vector3.FromArrayToRef(irradianceInfo.x, 0, sp.x);
  100983. BABYLON.Vector3.FromArrayToRef(irradianceInfo.y, 0, sp.y);
  100984. BABYLON.Vector3.FromArrayToRef(irradianceInfo.z, 0, sp.z);
  100985. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xx, 0, sp.xx);
  100986. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yy, 0, sp.yy);
  100987. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zz, 0, sp.zz);
  100988. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yz, 0, sp.yz);
  100989. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zx, 0, sp.zx);
  100990. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xy, 0, sp.xy);
  100991. texture._sphericalPolynomial = sp;
  100992. };
  100993. /**
  100994. * Magic number identifying the env file.
  100995. */
  100996. EnvironmentTextureTools._MagicBytes = [0x86, 0x16, 0x87, 0x96, 0xf6, 0xd6, 0x96, 0x36];
  100997. return EnvironmentTextureTools;
  100998. }());
  100999. BABYLON.EnvironmentTextureTools = EnvironmentTextureTools;
  101000. })(BABYLON || (BABYLON = {}));
  101001. //# sourceMappingURL=babylon.environmentTextureTools.js.map
  101002. var BABYLON;
  101003. (function (BABYLON) {
  101004. /**
  101005. * Implementation of the ENV Texture Loader.
  101006. */
  101007. var ENVTextureLoader = /** @class */ (function () {
  101008. function ENVTextureLoader() {
  101009. /**
  101010. * Defines wether the loader supports cascade loading the different faces.
  101011. */
  101012. this.supportCascades = false;
  101013. }
  101014. /**
  101015. * This returns if the loader support the current file information.
  101016. * @param extension defines the file extension of the file being loaded
  101017. * @param textureFormatInUse defines the current compressed format in use iun the engine
  101018. * @param fallback defines the fallback internal texture if any
  101019. * @param isBase64 defines whether the texture is encoded as a base64
  101020. * @param isBuffer defines whether the texture data are stored as a buffer
  101021. * @returns true if the loader can load the specified file
  101022. */
  101023. ENVTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  101024. return extension.indexOf(".env") === 0;
  101025. };
  101026. /**
  101027. * Transform the url before loading if required.
  101028. * @param rootUrl the url of the texture
  101029. * @param textureFormatInUse defines the current compressed format in use iun the engine
  101030. * @returns the transformed texture
  101031. */
  101032. ENVTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  101033. return rootUrl;
  101034. };
  101035. /**
  101036. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  101037. * @param rootUrl the url of the texture
  101038. * @param textureFormatInUse defines the current compressed format in use iun the engine
  101039. * @returns the fallback texture
  101040. */
  101041. ENVTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  101042. return null;
  101043. };
  101044. /**
  101045. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  101046. * @param data contains the texture data
  101047. * @param texture defines the BabylonJS internal texture
  101048. * @param createPolynomials will be true if polynomials have been requested
  101049. * @param onLoad defines the callback to trigger once the texture is ready
  101050. * @param onError defines the callback to trigger in case of error
  101051. */
  101052. ENVTextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  101053. if (Array.isArray(data)) {
  101054. return;
  101055. }
  101056. data = data;
  101057. var info = BABYLON.EnvironmentTextureTools.GetEnvInfo(data);
  101058. if (info) {
  101059. texture.width = info.width;
  101060. texture.height = info.width;
  101061. BABYLON.EnvironmentTextureTools.UploadEnvSpherical(texture, info);
  101062. BABYLON.EnvironmentTextureTools.UploadEnvLevelsAsync(texture, data, info).then(function () {
  101063. texture.isReady = true;
  101064. if (onLoad) {
  101065. onLoad();
  101066. }
  101067. });
  101068. }
  101069. else if (onError) {
  101070. onError("Can not parse the environment file", null);
  101071. }
  101072. };
  101073. /**
  101074. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  101075. * @param data contains the texture data
  101076. * @param texture defines the BabylonJS internal texture
  101077. * @param callback defines the method to call once ready to upload
  101078. */
  101079. ENVTextureLoader.prototype.loadData = function (data, texture, callback) {
  101080. throw ".env not supported in 2d.";
  101081. };
  101082. return ENVTextureLoader;
  101083. }());
  101084. // Register the loader.
  101085. BABYLON.Engine._TextureLoaders.push(new ENVTextureLoader());
  101086. })(BABYLON || (BABYLON = {}));
  101087. //# sourceMappingURL=babylon.envTextureLoader.js.map
  101088. var BABYLON;
  101089. (function (BABYLON) {
  101090. /**
  101091. * Renders a layer on top of an existing scene
  101092. */
  101093. var UtilityLayerRenderer = /** @class */ (function () {
  101094. /**
  101095. * Instantiates a UtilityLayerRenderer
  101096. * @param originalScene the original scene that will be rendered on top of
  101097. */
  101098. function UtilityLayerRenderer(
  101099. /** the original scene that will be rendered on top of */
  101100. originalScene) {
  101101. var _this = this;
  101102. this.originalScene = originalScene;
  101103. this._pointerCaptures = {};
  101104. this._lastPointerEvents = {};
  101105. /**
  101106. * If the picking should be done on the utility layer prior to the actual scene (Default: true)
  101107. */
  101108. this.pickUtilitySceneFirst = true;
  101109. /**
  101110. * If the utility layer should automatically be rendered on top of existing scene
  101111. */
  101112. this.shouldRender = true;
  101113. /**
  101114. * If set to true, only pointer down onPointerObservable events will be blocked when picking is occluded by original scene
  101115. */
  101116. this.onlyCheckPointerDownEvents = true;
  101117. /**
  101118. * If set to false, only pointerUp, pointerDown and pointerMove will be sent to the utilityLayerScene (false by default)
  101119. */
  101120. this.processAllEvents = false;
  101121. /**
  101122. * Observable raised when the pointer move from the utility layer scene to the main scene
  101123. */
  101124. this.onPointerOutObservable = new BABYLON.Observable();
  101125. // Create scene which will be rendered in the foreground and remove it from being referenced by engine to avoid interfering with existing app
  101126. this.utilityLayerScene = new BABYLON.Scene(originalScene.getEngine());
  101127. this.utilityLayerScene.useRightHandedSystem = originalScene.useRightHandedSystem;
  101128. this.utilityLayerScene._allowPostProcessClearColor = false;
  101129. originalScene.getEngine().scenes.pop();
  101130. // Detach controls on utility scene, events will be fired by logic below to handle picking priority
  101131. this.utilityLayerScene.detachControl();
  101132. this._originalPointerObserver = originalScene.onPrePointerObservable.add(function (prePointerInfo, eventState) {
  101133. if (!_this.processAllEvents) {
  101134. if (prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERMOVE
  101135. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERUP
  101136. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERDOWN) {
  101137. return;
  101138. }
  101139. }
  101140. var pointerEvent = (prePointerInfo.event);
  101141. if (originalScene.isPointerCaptured(pointerEvent.pointerId)) {
  101142. _this._pointerCaptures[pointerEvent.pointerId] = false;
  101143. return;
  101144. }
  101145. var utilityScenePick = prePointerInfo.ray ? _this.utilityLayerScene.pickWithRay(prePointerInfo.ray) : _this.utilityLayerScene.pick(originalScene.pointerX, originalScene.pointerY);
  101146. if (!prePointerInfo.ray && utilityScenePick) {
  101147. prePointerInfo.ray = utilityScenePick.ray;
  101148. }
  101149. // always fire the prepointer oversvable
  101150. _this.utilityLayerScene.onPrePointerObservable.notifyObservers(prePointerInfo);
  101151. // allow every non pointer down event to flow to the utility layer
  101152. if (_this.onlyCheckPointerDownEvents && prePointerInfo.type != BABYLON.PointerEventTypes.POINTERDOWN) {
  101153. if (!prePointerInfo.skipOnPointerObservable) {
  101154. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  101155. }
  101156. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent.pointerId]) {
  101157. _this._pointerCaptures[pointerEvent.pointerId] = false;
  101158. }
  101159. return;
  101160. }
  101161. if (_this.utilityLayerScene.autoClearDepthAndStencil || _this.pickUtilitySceneFirst) {
  101162. // If this layer is an overlay, check if this layer was hit and if so, skip pointer events for the main scene
  101163. if (utilityScenePick && utilityScenePick.hit) {
  101164. if (!prePointerInfo.skipOnPointerObservable) {
  101165. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  101166. }
  101167. prePointerInfo.skipOnPointerObservable = true;
  101168. }
  101169. }
  101170. else {
  101171. var originalScenePick = prePointerInfo.ray ? originalScene.pickWithRay(prePointerInfo.ray) : originalScene.pick(originalScene.pointerX, originalScene.pointerY);
  101172. var pointerEvent_1 = (prePointerInfo.event);
  101173. // If the layer can be occluded by the original scene, only fire pointer events to the first layer that hit they ray
  101174. if (originalScenePick && utilityScenePick) {
  101175. // No pick in utility scene
  101176. if (utilityScenePick.distance === 0 && originalScenePick.pickedMesh) {
  101177. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  101178. // We touched an utility mesh present in the main scene
  101179. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  101180. prePointerInfo.skipOnPointerObservable = true;
  101181. }
  101182. else if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  101183. _this._pointerCaptures[pointerEvent_1.pointerId] = true;
  101184. }
  101185. else if (_this._lastPointerEvents[pointerEvent_1.pointerId]) {
  101186. // We need to send a last pointerup to the utilityLayerScene to make sure animations can complete
  101187. _this.onPointerOutObservable.notifyObservers(pointerEvent_1.pointerId);
  101188. delete _this._lastPointerEvents[pointerEvent_1.pointerId];
  101189. }
  101190. }
  101191. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance < originalScenePick.distance || originalScenePick.distance === 0)) {
  101192. // We pick something in utility scene or the pick in utility is closer than the one in main scene
  101193. _this._notifyObservers(prePointerInfo, utilityScenePick, pointerEvent_1);
  101194. // If a previous utility layer set this, do not unset this
  101195. if (!prePointerInfo.skipOnPointerObservable) {
  101196. prePointerInfo.skipOnPointerObservable = utilityScenePick.distance > 0;
  101197. }
  101198. }
  101199. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance > originalScenePick.distance)) {
  101200. // We have a pick in both scenes but main is closer than utility
  101201. // We touched an utility mesh present in the main scene
  101202. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  101203. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  101204. prePointerInfo.skipOnPointerObservable = true;
  101205. }
  101206. else if (_this._lastPointerEvents[pointerEvent_1.pointerId]) {
  101207. // We need to send a last pointerup to the utilityLayerScene to make sure animations can complete
  101208. _this.onPointerOutObservable.notifyObservers(pointerEvent_1.pointerId);
  101209. delete _this._lastPointerEvents[pointerEvent_1.pointerId];
  101210. }
  101211. }
  101212. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent_1.pointerId]) {
  101213. _this._pointerCaptures[pointerEvent_1.pointerId] = false;
  101214. }
  101215. }
  101216. }
  101217. });
  101218. // Render directly on top of existing scene without clearing
  101219. this.utilityLayerScene.autoClear = false;
  101220. this._afterRenderObserver = this.originalScene.onAfterRenderObservable.add(function () {
  101221. if (_this.shouldRender) {
  101222. _this.render();
  101223. }
  101224. });
  101225. this._sceneDisposeObserver = this.originalScene.onDisposeObservable.add(function () {
  101226. _this.dispose();
  101227. });
  101228. this._updateCamera();
  101229. }
  101230. Object.defineProperty(UtilityLayerRenderer, "DefaultUtilityLayer", {
  101231. /**
  101232. * 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)
  101233. */
  101234. get: function () {
  101235. if (UtilityLayerRenderer._DefaultUtilityLayer == null) {
  101236. UtilityLayerRenderer._DefaultUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
  101237. UtilityLayerRenderer._DefaultUtilityLayer.originalScene.onDisposeObservable.addOnce(function () {
  101238. UtilityLayerRenderer._DefaultUtilityLayer = null;
  101239. });
  101240. }
  101241. return UtilityLayerRenderer._DefaultUtilityLayer;
  101242. },
  101243. enumerable: true,
  101244. configurable: true
  101245. });
  101246. Object.defineProperty(UtilityLayerRenderer, "DefaultKeepDepthUtilityLayer", {
  101247. /**
  101248. * 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)
  101249. */
  101250. get: function () {
  101251. if (UtilityLayerRenderer._DefaultKeepDepthUtilityLayer == null) {
  101252. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
  101253. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil = false;
  101254. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.originalScene.onDisposeObservable.addOnce(function () {
  101255. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null;
  101256. });
  101257. }
  101258. return UtilityLayerRenderer._DefaultKeepDepthUtilityLayer;
  101259. },
  101260. enumerable: true,
  101261. configurable: true
  101262. });
  101263. UtilityLayerRenderer.prototype._notifyObservers = function (prePointerInfo, pickInfo, pointerEvent) {
  101264. if (!prePointerInfo.skipOnPointerObservable) {
  101265. this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, pickInfo));
  101266. this._lastPointerEvents[pointerEvent.pointerId] = true;
  101267. }
  101268. };
  101269. /**
  101270. * Renders the utility layers scene on top of the original scene
  101271. */
  101272. UtilityLayerRenderer.prototype.render = function () {
  101273. this._updateCamera();
  101274. if (this.utilityLayerScene.activeCamera) {
  101275. // Set the camera's scene to utility layers scene
  101276. var oldScene = this.utilityLayerScene.activeCamera.getScene();
  101277. var camera = this.utilityLayerScene.activeCamera;
  101278. camera._scene = this.utilityLayerScene;
  101279. if (camera.leftCamera) {
  101280. camera.leftCamera._scene = this.utilityLayerScene;
  101281. }
  101282. if (camera.rightCamera) {
  101283. camera.rightCamera._scene = this.utilityLayerScene;
  101284. }
  101285. this.utilityLayerScene.render(false);
  101286. // Reset camera's scene back to original
  101287. camera._scene = oldScene;
  101288. if (camera.leftCamera) {
  101289. camera.leftCamera._scene = oldScene;
  101290. }
  101291. if (camera.rightCamera) {
  101292. camera.rightCamera._scene = oldScene;
  101293. }
  101294. }
  101295. };
  101296. /**
  101297. * Disposes of the renderer
  101298. */
  101299. UtilityLayerRenderer.prototype.dispose = function () {
  101300. this.onPointerOutObservable.clear();
  101301. if (this._afterRenderObserver) {
  101302. this.originalScene.onAfterRenderObservable.remove(this._afterRenderObserver);
  101303. }
  101304. if (this._sceneDisposeObserver) {
  101305. this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver);
  101306. }
  101307. if (this._originalPointerObserver) {
  101308. this.originalScene.onPrePointerObservable.remove(this._originalPointerObserver);
  101309. }
  101310. this.utilityLayerScene.dispose();
  101311. };
  101312. UtilityLayerRenderer.prototype._updateCamera = function () {
  101313. this.utilityLayerScene.activeCamera = this.originalScene.activeCamera;
  101314. };
  101315. UtilityLayerRenderer._DefaultUtilityLayer = null;
  101316. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null;
  101317. return UtilityLayerRenderer;
  101318. }());
  101319. BABYLON.UtilityLayerRenderer = UtilityLayerRenderer;
  101320. })(BABYLON || (BABYLON = {}));
  101321. //# sourceMappingURL=babylon.utilityLayerRenderer.js.map
  101322. //# sourceMappingURL=babylon.behavior.js.map
  101323. var BABYLON;
  101324. (function (BABYLON) {
  101325. /**
  101326. * A behavior that when attached to a mesh will allow the mesh to be dragged around the screen based on pointer events
  101327. */
  101328. var PointerDragBehavior = /** @class */ (function () {
  101329. /**
  101330. * Creates a pointer drag behavior that can be attached to a mesh
  101331. * @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)
  101332. */
  101333. function PointerDragBehavior(options) {
  101334. /**
  101335. * 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)
  101336. */
  101337. this.maxDragAngle = 0;
  101338. /**
  101339. * @hidden
  101340. */
  101341. this._useAlternatePickedPointAboveMaxDragAngle = false;
  101342. /**
  101343. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  101344. */
  101345. this.currentDraggingPointerID = -1;
  101346. /**
  101347. * If the behavior is currently in a dragging state
  101348. */
  101349. this.dragging = false;
  101350. /**
  101351. * 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)
  101352. */
  101353. this.dragDeltaRatio = 0.2;
  101354. /**
  101355. * If the drag plane orientation should be updated during the dragging (Default: true)
  101356. */
  101357. this.updateDragPlane = true;
  101358. // Debug mode will display drag planes to help visualize behavior
  101359. this._debugMode = false;
  101360. this._moving = false;
  101361. /**
  101362. * Fires each time the attached mesh is dragged with the pointer
  101363. * * delta between last drag position and current drag position in world space
  101364. * * dragDistance along the drag axis
  101365. * * dragPlaneNormal normal of the current drag plane used during the drag
  101366. * * dragPlanePoint in world space where the drag intersects the drag plane
  101367. */
  101368. this.onDragObservable = new BABYLON.Observable();
  101369. /**
  101370. * Fires each time a drag begins (eg. mouse down on mesh)
  101371. */
  101372. this.onDragStartObservable = new BABYLON.Observable();
  101373. /**
  101374. * Fires each time a drag ends (eg. mouse release after drag)
  101375. */
  101376. this.onDragEndObservable = new BABYLON.Observable();
  101377. /**
  101378. * If the attached mesh should be moved when dragged
  101379. */
  101380. this.moveAttached = true;
  101381. /**
  101382. * If the drag behavior will react to drag events (Default: true)
  101383. */
  101384. this.enabled = true;
  101385. /**
  101386. * If camera controls should be detached during the drag
  101387. */
  101388. this.detachCameraControls = true;
  101389. /**
  101390. * If set, the drag plane/axis will be rotated based on the attached mesh's world rotation (Default: true)
  101391. */
  101392. this.useObjectOrienationForDragging = true;
  101393. this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  101394. this._alternatePickedPoint = new BABYLON.Vector3(0, 0, 0);
  101395. this._worldDragAxis = new BABYLON.Vector3(0, 0, 0);
  101396. this._targetPosition = new BABYLON.Vector3(0, 0, 0);
  101397. this._attachedElement = null;
  101398. this._startDragRay = new BABYLON.Ray(new BABYLON.Vector3(), new BABYLON.Vector3());
  101399. this._lastPointerRay = {};
  101400. this._dragDelta = new BABYLON.Vector3();
  101401. // Variables to avoid instantiation in the below method
  101402. this._pointA = new BABYLON.Vector3(0, 0, 0);
  101403. this._pointB = new BABYLON.Vector3(0, 0, 0);
  101404. this._pointC = new BABYLON.Vector3(0, 0, 0);
  101405. this._lineA = new BABYLON.Vector3(0, 0, 0);
  101406. this._lineB = new BABYLON.Vector3(0, 0, 0);
  101407. this._localAxis = new BABYLON.Vector3(0, 0, 0);
  101408. this._lookAt = new BABYLON.Vector3(0, 0, 0);
  101409. this._options = options ? options : {};
  101410. var optionCount = 0;
  101411. if (this._options.dragAxis) {
  101412. optionCount++;
  101413. }
  101414. if (this._options.dragPlaneNormal) {
  101415. optionCount++;
  101416. }
  101417. if (optionCount > 1) {
  101418. throw "Multiple drag modes specified in dragBehavior options. Only one expected";
  101419. }
  101420. }
  101421. Object.defineProperty(PointerDragBehavior.prototype, "name", {
  101422. /**
  101423. * The name of the behavior
  101424. */
  101425. get: function () {
  101426. return "PointerDrag";
  101427. },
  101428. enumerable: true,
  101429. configurable: true
  101430. });
  101431. /**
  101432. * Initializes the behavior
  101433. */
  101434. PointerDragBehavior.prototype.init = function () { };
  101435. /**
  101436. * Attaches the drag behavior the passed in mesh
  101437. * @param ownerNode The mesh that will be dragged around once attached
  101438. */
  101439. PointerDragBehavior.prototype.attach = function (ownerNode) {
  101440. var _this = this;
  101441. this._scene = ownerNode.getScene();
  101442. this._attachedNode = ownerNode;
  101443. // Initialize drag plane to not interfere with existing scene
  101444. if (!PointerDragBehavior._planeScene) {
  101445. if (this._debugMode) {
  101446. PointerDragBehavior._planeScene = this._scene;
  101447. }
  101448. else {
  101449. PointerDragBehavior._planeScene = new BABYLON.Scene(this._scene.getEngine());
  101450. PointerDragBehavior._planeScene.detachControl();
  101451. this._scene.getEngine().scenes.pop();
  101452. this._scene.onDisposeObservable.addOnce(function () {
  101453. PointerDragBehavior._planeScene.dispose();
  101454. PointerDragBehavior._planeScene = null;
  101455. });
  101456. }
  101457. }
  101458. this._dragPlane = BABYLON.Mesh.CreatePlane("pointerDragPlane", this._debugMode ? 1 : 10000, PointerDragBehavior._planeScene, false, BABYLON.Mesh.DOUBLESIDE);
  101459. // State of the drag
  101460. this.lastDragPosition = new BABYLON.Vector3(0, 0, 0);
  101461. var pickPredicate = function (m) {
  101462. return _this._attachedNode == m || m.isDescendantOf(_this._attachedNode);
  101463. };
  101464. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  101465. if (!_this.enabled) {
  101466. return;
  101467. }
  101468. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  101469. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.pickedPoint && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  101470. _this._startDrag(pointerInfo.event.pointerId, pointerInfo.pickInfo.ray, pointerInfo.pickInfo.pickedPoint);
  101471. }
  101472. }
  101473. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  101474. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  101475. _this.releaseDrag();
  101476. }
  101477. }
  101478. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  101479. var pointerId = pointerInfo.event.pointerId;
  101480. // If drag was started with anyMouseID specified, set pointerID to the next mouse that moved
  101481. if (_this.currentDraggingPointerID === PointerDragBehavior._AnyMouseID && pointerId !== PointerDragBehavior._AnyMouseID && pointerInfo.event.pointerType == "mouse") {
  101482. if (_this._lastPointerRay[_this.currentDraggingPointerID]) {
  101483. _this._lastPointerRay[pointerId] = _this._lastPointerRay[_this.currentDraggingPointerID];
  101484. delete _this._lastPointerRay[_this.currentDraggingPointerID];
  101485. }
  101486. _this.currentDraggingPointerID = pointerId;
  101487. }
  101488. // Keep track of last pointer ray, this is used simulating the start of a drag in startDrag()
  101489. if (!_this._lastPointerRay[pointerId]) {
  101490. _this._lastPointerRay[pointerId] = new BABYLON.Ray(new BABYLON.Vector3(), new BABYLON.Vector3());
  101491. }
  101492. if (pointerInfo.pickInfo && pointerInfo.pickInfo.ray) {
  101493. _this._lastPointerRay[pointerId].origin.copyFrom(pointerInfo.pickInfo.ray.origin);
  101494. _this._lastPointerRay[pointerId].direction.copyFrom(pointerInfo.pickInfo.ray.direction);
  101495. if (_this.currentDraggingPointerID == pointerId && _this.dragging) {
  101496. _this._moveDrag(pointerInfo.pickInfo.ray);
  101497. }
  101498. }
  101499. }
  101500. });
  101501. this._beforeRenderObserver = this._scene.onBeforeRenderObservable.add(function () {
  101502. if (_this._moving && _this.moveAttached) {
  101503. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(_this._attachedNode);
  101504. // Slowly move mesh to avoid jitter
  101505. _this._targetPosition.subtractToRef((_this._attachedNode).absolutePosition, _this._tmpVector);
  101506. _this._tmpVector.scaleInPlace(_this.dragDeltaRatio);
  101507. (_this._attachedNode).getAbsolutePosition().addToRef(_this._tmpVector, _this._tmpVector);
  101508. (_this._attachedNode).setAbsolutePosition(_this._tmpVector);
  101509. BABYLON.BoundingBoxGizmo._RestorePivotPoint(_this._attachedNode);
  101510. }
  101511. });
  101512. };
  101513. /**
  101514. * Force relase the drag action by code.
  101515. */
  101516. PointerDragBehavior.prototype.releaseDrag = function () {
  101517. this.dragging = false;
  101518. this.onDragEndObservable.notifyObservers({ dragPlanePoint: this.lastDragPosition, pointerId: this.currentDraggingPointerID });
  101519. this.currentDraggingPointerID = -1;
  101520. this._moving = false;
  101521. // Reattach camera controls
  101522. if (this.detachCameraControls && this._attachedElement && this._scene.activeCamera && !this._scene.activeCamera.leftCamera) {
  101523. this._scene.activeCamera.attachControl(this._attachedElement, true);
  101524. }
  101525. };
  101526. /**
  101527. * Simulates the start of a pointer drag event on the behavior
  101528. * @param pointerId pointerID of the pointer that should be simulated (Default: Any mouse pointer ID)
  101529. * @param fromRay initial ray of the pointer to be simulated (Default: Ray from camera to attached mesh)
  101530. * @param startPickedPoint picked point of the pointer to be simulated (Default: attached mesh position)
  101531. */
  101532. PointerDragBehavior.prototype.startDrag = function (pointerId, fromRay, startPickedPoint) {
  101533. if (pointerId === void 0) { pointerId = PointerDragBehavior._AnyMouseID; }
  101534. this._startDrag(pointerId, fromRay, startPickedPoint);
  101535. var lastRay = this._lastPointerRay[pointerId];
  101536. if (pointerId === PointerDragBehavior._AnyMouseID) {
  101537. lastRay = this._lastPointerRay[Object.keys(this._lastPointerRay)[0]];
  101538. }
  101539. if (lastRay) {
  101540. // if there was a last pointer ray drag the object there
  101541. this._moveDrag(lastRay);
  101542. }
  101543. };
  101544. PointerDragBehavior.prototype._startDrag = function (pointerId, fromRay, startPickedPoint) {
  101545. if (!this._scene.activeCamera || this.dragging || !this._attachedNode) {
  101546. return;
  101547. }
  101548. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(this._attachedNode);
  101549. // Create start ray from the camera to the object
  101550. if (fromRay) {
  101551. this._startDragRay.direction.copyFrom(fromRay.direction);
  101552. this._startDragRay.origin.copyFrom(fromRay.origin);
  101553. }
  101554. else {
  101555. this._startDragRay.origin.copyFrom(this._scene.activeCamera.position);
  101556. this._attachedNode.getWorldMatrix().getTranslationToRef(this._tmpVector);
  101557. this._tmpVector.subtractToRef(this._scene.activeCamera.position, this._startDragRay.direction);
  101558. }
  101559. this._updateDragPlanePosition(this._startDragRay, startPickedPoint ? startPickedPoint : this._tmpVector);
  101560. var pickedPoint = this._pickWithRayOnDragPlane(this._startDragRay);
  101561. if (pickedPoint) {
  101562. this.dragging = true;
  101563. this.currentDraggingPointerID = pointerId;
  101564. this.lastDragPosition.copyFrom(pickedPoint);
  101565. this.onDragStartObservable.notifyObservers({ dragPlanePoint: pickedPoint, pointerId: this.currentDraggingPointerID });
  101566. this._targetPosition.copyFrom((this._attachedNode).absolutePosition);
  101567. // Detatch camera controls
  101568. if (this.detachCameraControls && this._scene.activeCamera && !this._scene.activeCamera.leftCamera) {
  101569. if (this._scene.activeCamera.inputs.attachedElement) {
  101570. this._attachedElement = this._scene.activeCamera.inputs.attachedElement;
  101571. this._scene.activeCamera.detachControl(this._scene.activeCamera.inputs.attachedElement);
  101572. }
  101573. else {
  101574. this._attachedElement = null;
  101575. }
  101576. }
  101577. }
  101578. BABYLON.BoundingBoxGizmo._RestorePivotPoint(this._attachedNode);
  101579. };
  101580. PointerDragBehavior.prototype._moveDrag = function (ray) {
  101581. this._moving = true;
  101582. var pickedPoint = this._pickWithRayOnDragPlane(ray);
  101583. if (pickedPoint) {
  101584. if (this.updateDragPlane) {
  101585. this._updateDragPlanePosition(ray, pickedPoint);
  101586. }
  101587. var dragLength = 0;
  101588. // depending on the drag mode option drag accordingly
  101589. if (this._options.dragAxis) {
  101590. // Convert local drag axis to world
  101591. BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._worldDragAxis);
  101592. // Project delta drag from the drag plane onto the drag axis
  101593. pickedPoint.subtractToRef(this.lastDragPosition, this._tmpVector);
  101594. dragLength = BABYLON.Vector3.Dot(this._tmpVector, this._worldDragAxis);
  101595. this._worldDragAxis.scaleToRef(dragLength, this._dragDelta);
  101596. }
  101597. else {
  101598. dragLength = this._dragDelta.length();
  101599. pickedPoint.subtractToRef(this.lastDragPosition, this._dragDelta);
  101600. }
  101601. this._targetPosition.addInPlace(this._dragDelta);
  101602. this.onDragObservable.notifyObservers({ dragDistance: dragLength, delta: this._dragDelta, dragPlanePoint: pickedPoint, dragPlaneNormal: this._dragPlane.forward, pointerId: this.currentDraggingPointerID });
  101603. this.lastDragPosition.copyFrom(pickedPoint);
  101604. }
  101605. };
  101606. PointerDragBehavior.prototype._pickWithRayOnDragPlane = function (ray) {
  101607. var _this = this;
  101608. if (!ray) {
  101609. return null;
  101610. }
  101611. // Calculate angle between plane normal and ray
  101612. var angle = Math.acos(BABYLON.Vector3.Dot(this._dragPlane.forward, ray.direction));
  101613. // Correct if ray is casted from oposite side
  101614. if (angle > Math.PI / 2) {
  101615. angle = Math.PI - angle;
  101616. }
  101617. // If the angle is too perpendicular to the plane pick another point on the plane where it is looking
  101618. if (this.maxDragAngle > 0 && angle > this.maxDragAngle) {
  101619. if (this._useAlternatePickedPointAboveMaxDragAngle) {
  101620. // Invert ray direction along the towards object axis
  101621. this._tmpVector.copyFrom(ray.direction);
  101622. (this._attachedNode).absolutePosition.subtractToRef(ray.origin, this._alternatePickedPoint);
  101623. this._alternatePickedPoint.normalize();
  101624. this._alternatePickedPoint.scaleInPlace(-2 * BABYLON.Vector3.Dot(this._alternatePickedPoint, this._tmpVector));
  101625. this._tmpVector.addInPlace(this._alternatePickedPoint);
  101626. // Project resulting vector onto the drag plane and add it to the attached nodes absolute position to get a picked point
  101627. var dot = BABYLON.Vector3.Dot(this._dragPlane.forward, this._tmpVector);
  101628. this._dragPlane.forward.scaleToRef(-dot, this._alternatePickedPoint);
  101629. this._alternatePickedPoint.addInPlace(this._tmpVector);
  101630. this._alternatePickedPoint.addInPlace((this._attachedNode).absolutePosition);
  101631. return this._alternatePickedPoint;
  101632. }
  101633. else {
  101634. return null;
  101635. }
  101636. }
  101637. var pickResult = PointerDragBehavior._planeScene.pickWithRay(ray, function (m) { return m == _this._dragPlane; });
  101638. if (pickResult && pickResult.hit && pickResult.pickedMesh && pickResult.pickedPoint) {
  101639. return pickResult.pickedPoint;
  101640. }
  101641. else {
  101642. return null;
  101643. }
  101644. };
  101645. // Position the drag plane based on the attached mesh position, for single axis rotate the plane along the axis to face the camera
  101646. PointerDragBehavior.prototype._updateDragPlanePosition = function (ray, dragPlanePosition) {
  101647. this._pointA.copyFrom(dragPlanePosition);
  101648. if (this._options.dragAxis) {
  101649. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragAxis);
  101650. // Calculate plane normal in direction of camera but perpendicular to drag axis
  101651. this._pointA.addToRef(this._localAxis, this._pointB); // towards drag axis
  101652. ray.origin.subtractToRef(this._pointA, this._pointC);
  101653. this._pointA.addToRef(this._pointC.normalize(), this._pointC); // towards camera
  101654. // Get perpendicular line from direction to camera and drag axis
  101655. this._pointB.subtractToRef(this._pointA, this._lineA);
  101656. this._pointC.subtractToRef(this._pointA, this._lineB);
  101657. BABYLON.Vector3.CrossToRef(this._lineA, this._lineB, this._lookAt);
  101658. // Get perpendicular line from previous result and drag axis to adjust lineB to be perpendiculat to camera
  101659. BABYLON.Vector3.CrossToRef(this._lineA, this._lookAt, this._lookAt);
  101660. this._lookAt.normalize();
  101661. this._dragPlane.position.copyFrom(this._pointA);
  101662. this._pointA.subtractToRef(this._lookAt, this._lookAt);
  101663. this._dragPlane.lookAt(this._lookAt);
  101664. }
  101665. else if (this._options.dragPlaneNormal) {
  101666. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragPlaneNormal, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragPlaneNormal);
  101667. this._dragPlane.position.copyFrom(this._pointA);
  101668. this._pointA.subtractToRef(this._localAxis, this._lookAt);
  101669. this._dragPlane.lookAt(this._lookAt);
  101670. }
  101671. else {
  101672. this._dragPlane.position.copyFrom(this._pointA);
  101673. this._dragPlane.lookAt(ray.origin);
  101674. }
  101675. this._dragPlane.computeWorldMatrix(true);
  101676. };
  101677. /**
  101678. * Detaches the behavior from the mesh
  101679. */
  101680. PointerDragBehavior.prototype.detach = function () {
  101681. if (this._pointerObserver) {
  101682. this._scene.onPointerObservable.remove(this._pointerObserver);
  101683. }
  101684. if (this._beforeRenderObserver) {
  101685. this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  101686. }
  101687. };
  101688. PointerDragBehavior._AnyMouseID = -2;
  101689. return PointerDragBehavior;
  101690. }());
  101691. BABYLON.PointerDragBehavior = PointerDragBehavior;
  101692. })(BABYLON || (BABYLON = {}));
  101693. //# sourceMappingURL=babylon.pointerDragBehavior.js.map
  101694. var BABYLON;
  101695. (function (BABYLON) {
  101696. /**
  101697. * A behavior that when attached to a mesh will allow the mesh to be scaled
  101698. */
  101699. var MultiPointerScaleBehavior = /** @class */ (function () {
  101700. /**
  101701. * Instantiate a new behavior that when attached to a mesh will allow the mesh to be scaled
  101702. */
  101703. function MultiPointerScaleBehavior() {
  101704. this._startDistance = 0;
  101705. this._initialScale = new BABYLON.Vector3(0, 0, 0);
  101706. this._targetScale = new BABYLON.Vector3(0, 0, 0);
  101707. this._sceneRenderObserver = null;
  101708. this._dragBehaviorA = new BABYLON.PointerDragBehavior({});
  101709. this._dragBehaviorA.moveAttached = false;
  101710. this._dragBehaviorB = new BABYLON.PointerDragBehavior({});
  101711. this._dragBehaviorB.moveAttached = false;
  101712. }
  101713. Object.defineProperty(MultiPointerScaleBehavior.prototype, "name", {
  101714. /**
  101715. * The name of the behavior
  101716. */
  101717. get: function () {
  101718. return "MultiPointerScale";
  101719. },
  101720. enumerable: true,
  101721. configurable: true
  101722. });
  101723. /**
  101724. * Initializes the behavior
  101725. */
  101726. MultiPointerScaleBehavior.prototype.init = function () { };
  101727. MultiPointerScaleBehavior.prototype._getCurrentDistance = function () {
  101728. return this._dragBehaviorA.lastDragPosition.subtract(this._dragBehaviorB.lastDragPosition).length();
  101729. };
  101730. /**
  101731. * Attaches the scale behavior the passed in mesh
  101732. * @param ownerNode The mesh that will be scaled around once attached
  101733. */
  101734. MultiPointerScaleBehavior.prototype.attach = function (ownerNode) {
  101735. var _this = this;
  101736. this._ownerNode = ownerNode;
  101737. // Create 2 drag behaviors such that each will only be triggered by a separate pointer
  101738. this._dragBehaviorA.onDragStartObservable.add(function (e) {
  101739. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  101740. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  101741. _this._dragBehaviorA.releaseDrag();
  101742. }
  101743. else {
  101744. _this._initialScale.copyFrom(ownerNode.scaling);
  101745. _this._startDistance = _this._getCurrentDistance();
  101746. }
  101747. }
  101748. });
  101749. this._dragBehaviorB.onDragStartObservable.add(function (e) {
  101750. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  101751. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  101752. _this._dragBehaviorB.releaseDrag();
  101753. }
  101754. else {
  101755. _this._initialScale.copyFrom(ownerNode.scaling);
  101756. _this._startDistance = _this._getCurrentDistance();
  101757. }
  101758. }
  101759. });
  101760. // Once both drag behaviors are active scale based on the distance between the two pointers
  101761. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  101762. behavior.onDragObservable.add(function () {
  101763. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  101764. var ratio = _this._getCurrentDistance() / _this._startDistance;
  101765. _this._initialScale.scaleToRef(ratio, _this._targetScale);
  101766. }
  101767. });
  101768. });
  101769. ownerNode.addBehavior(this._dragBehaviorA);
  101770. ownerNode.addBehavior(this._dragBehaviorB);
  101771. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  101772. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  101773. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  101774. var change = _this._targetScale.subtract(ownerNode.scaling).scaleInPlace(0.1);
  101775. if (change.length() > 0.01) {
  101776. ownerNode.scaling.addInPlace(change);
  101777. }
  101778. }
  101779. });
  101780. };
  101781. /**
  101782. * Detaches the behavior from the mesh
  101783. */
  101784. MultiPointerScaleBehavior.prototype.detach = function () {
  101785. var _this = this;
  101786. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  101787. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  101788. behavior.onDragStartObservable.clear();
  101789. behavior.onDragObservable.clear();
  101790. _this._ownerNode.removeBehavior(behavior);
  101791. });
  101792. };
  101793. return MultiPointerScaleBehavior;
  101794. }());
  101795. BABYLON.MultiPointerScaleBehavior = MultiPointerScaleBehavior;
  101796. })(BABYLON || (BABYLON = {}));
  101797. //# sourceMappingURL=babylon.multiPointerScaleBehavior.js.map
  101798. var BABYLON;
  101799. (function (BABYLON) {
  101800. /**
  101801. * 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
  101802. */
  101803. var SixDofDragBehavior = /** @class */ (function () {
  101804. /**
  101805. * 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
  101806. */
  101807. function SixDofDragBehavior() {
  101808. this._sceneRenderObserver = null;
  101809. this._targetPosition = new BABYLON.Vector3(0, 0, 0);
  101810. this._moving = false;
  101811. this._startingOrientation = new BABYLON.Quaternion();
  101812. /**
  101813. * 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)
  101814. */
  101815. this.zDragFactor = 3;
  101816. /**
  101817. * If the behavior is currently in a dragging state
  101818. */
  101819. this.dragging = false;
  101820. /**
  101821. * 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)
  101822. */
  101823. this.dragDeltaRatio = 0.2;
  101824. /**
  101825. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  101826. */
  101827. this.currentDraggingPointerID = -1;
  101828. /**
  101829. * If camera controls should be detached during the drag
  101830. */
  101831. this.detachCameraControls = true;
  101832. /**
  101833. * Fires each time a drag starts
  101834. */
  101835. this.onDragStartObservable = new BABYLON.Observable();
  101836. /**
  101837. * Fires each time a drag ends (eg. mouse release after drag)
  101838. */
  101839. this.onDragEndObservable = new BABYLON.Observable();
  101840. }
  101841. Object.defineProperty(SixDofDragBehavior.prototype, "name", {
  101842. /**
  101843. * The name of the behavior
  101844. */
  101845. get: function () {
  101846. return "SixDofDrag";
  101847. },
  101848. enumerable: true,
  101849. configurable: true
  101850. });
  101851. /**
  101852. * Initializes the behavior
  101853. */
  101854. SixDofDragBehavior.prototype.init = function () { };
  101855. /**
  101856. * Attaches the scale behavior the passed in mesh
  101857. * @param ownerNode The mesh that will be scaled around once attached
  101858. */
  101859. SixDofDragBehavior.prototype.attach = function (ownerNode) {
  101860. var _this = this;
  101861. this._ownerNode = ownerNode;
  101862. this._scene = this._ownerNode.getScene();
  101863. if (!SixDofDragBehavior._virtualScene) {
  101864. SixDofDragBehavior._virtualScene = new BABYLON.Scene(this._scene.getEngine());
  101865. SixDofDragBehavior._virtualScene.detachControl();
  101866. this._scene.getEngine().scenes.pop();
  101867. }
  101868. var pickedMesh = null;
  101869. var lastSixDofOriginPosition = new BABYLON.Vector3(0, 0, 0);
  101870. // Setup virtual meshes to be used for dragging without dirtying the existing scene
  101871. this._virtualOriginMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  101872. this._virtualOriginMesh.rotationQuaternion = new BABYLON.Quaternion();
  101873. this._virtualDragMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  101874. this._virtualDragMesh.rotationQuaternion = new BABYLON.Quaternion();
  101875. var pickPredicate = function (m) {
  101876. return _this._ownerNode == m || m.isDescendantOf(_this._ownerNode);
  101877. };
  101878. var attachedElement = null;
  101879. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  101880. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  101881. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  101882. if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON.Camera.RIG_MODE_NONE) {
  101883. pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.position);
  101884. }
  101885. pickedMesh = _this._ownerNode;
  101886. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(pickedMesh);
  101887. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  101888. // Set position and orientation of the controller
  101889. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  101890. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  101891. // Attach the virtual drag mesh to the virtual origin mesh so it can be dragged
  101892. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  101893. pickedMesh.computeWorldMatrix();
  101894. _this._virtualDragMesh.position.copyFrom(pickedMesh.absolutePosition);
  101895. if (!pickedMesh.rotationQuaternion) {
  101896. pickedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(pickedMesh.rotation.y, pickedMesh.rotation.x, pickedMesh.rotation.z);
  101897. }
  101898. var oldParent = pickedMesh.parent;
  101899. pickedMesh.setParent(null);
  101900. _this._virtualDragMesh.rotationQuaternion.copyFrom(pickedMesh.rotationQuaternion);
  101901. pickedMesh.setParent(oldParent);
  101902. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  101903. // Update state
  101904. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  101905. _this.dragging = true;
  101906. _this.currentDraggingPointerID = pointerInfo.event.pointerId;
  101907. // Detatch camera controls
  101908. if (_this.detachCameraControls && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  101909. if (_this._scene.activeCamera.inputs.attachedElement) {
  101910. attachedElement = _this._scene.activeCamera.inputs.attachedElement;
  101911. _this._scene.activeCamera.detachControl(_this._scene.activeCamera.inputs.attachedElement);
  101912. }
  101913. else {
  101914. attachedElement = null;
  101915. }
  101916. }
  101917. BABYLON.BoundingBoxGizmo._RestorePivotPoint(pickedMesh);
  101918. _this.onDragStartObservable.notifyObservers({});
  101919. }
  101920. }
  101921. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  101922. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  101923. _this.dragging = false;
  101924. _this._moving = false;
  101925. _this.currentDraggingPointerID = -1;
  101926. pickedMesh = null;
  101927. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  101928. // Reattach camera controls
  101929. if (_this.detachCameraControls && attachedElement && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  101930. _this._scene.activeCamera.attachControl(attachedElement, true);
  101931. }
  101932. _this.onDragEndObservable.notifyObservers({});
  101933. }
  101934. }
  101935. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  101936. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId && _this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray && pickedMesh) {
  101937. var zDragFactor = _this.zDragFactor;
  101938. if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON.Camera.RIG_MODE_NONE) {
  101939. pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.position);
  101940. zDragFactor = 0;
  101941. }
  101942. // Calculate controller drag distance in controller space
  101943. var originDragDifference = pointerInfo.pickInfo.ray.origin.subtract(lastSixDofOriginPosition);
  101944. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  101945. var localOriginDragDifference = -BABYLON.Vector3.Dot(originDragDifference, pointerInfo.pickInfo.ray.direction);
  101946. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  101947. // Determine how much the controller moved to/away towards the dragged object and use this to move the object further when its further away
  101948. _this._virtualDragMesh.position.z -= _this._virtualDragMesh.position.z < 1 ? localOriginDragDifference * _this.zDragFactor : localOriginDragDifference * zDragFactor * _this._virtualDragMesh.position.z;
  101949. if (_this._virtualDragMesh.position.z < 0) {
  101950. _this._virtualDragMesh.position.z = 0;
  101951. }
  101952. // Update the controller position
  101953. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  101954. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  101955. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  101956. // Move the virtualObjectsPosition into the picked mesh's space if needed
  101957. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  101958. if (pickedMesh.parent) {
  101959. BABYLON.Vector3.TransformCoordinatesToRef(_this._targetPosition, BABYLON.Matrix.Invert(pickedMesh.parent.getWorldMatrix()), _this._targetPosition);
  101960. }
  101961. if (!_this._moving) {
  101962. _this._startingOrientation.copyFrom(_this._virtualDragMesh.rotationQuaternion);
  101963. }
  101964. _this._moving = true;
  101965. }
  101966. }
  101967. });
  101968. var tmpQuaternion = new BABYLON.Quaternion();
  101969. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  101970. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  101971. if (_this.dragging && _this._moving && pickedMesh) {
  101972. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(pickedMesh);
  101973. // Slowly move mesh to avoid jitter
  101974. pickedMesh.position.addInPlace(_this._targetPosition.subtract(pickedMesh.position).scale(_this.dragDeltaRatio));
  101975. // Get change in rotation
  101976. tmpQuaternion.copyFrom(_this._startingOrientation);
  101977. tmpQuaternion.x = -tmpQuaternion.x;
  101978. tmpQuaternion.y = -tmpQuaternion.y;
  101979. tmpQuaternion.z = -tmpQuaternion.z;
  101980. _this._virtualDragMesh.rotationQuaternion.multiplyToRef(tmpQuaternion, tmpQuaternion);
  101981. // Convert change in rotation to only y axis rotation
  101982. BABYLON.Quaternion.RotationYawPitchRollToRef(tmpQuaternion.toEulerAngles("xyz").y, 0, 0, tmpQuaternion);
  101983. tmpQuaternion.multiplyToRef(_this._startingOrientation, tmpQuaternion);
  101984. // Slowly move mesh to avoid jitter
  101985. var oldParent = pickedMesh.parent;
  101986. pickedMesh.setParent(null);
  101987. BABYLON.Quaternion.SlerpToRef(pickedMesh.rotationQuaternion, tmpQuaternion, _this.dragDeltaRatio, pickedMesh.rotationQuaternion);
  101988. pickedMesh.setParent(oldParent);
  101989. BABYLON.BoundingBoxGizmo._RestorePivotPoint(pickedMesh);
  101990. }
  101991. });
  101992. };
  101993. /**
  101994. * Detaches the behavior from the mesh
  101995. */
  101996. SixDofDragBehavior.prototype.detach = function () {
  101997. if (this._scene) {
  101998. this._scene.onPointerObservable.remove(this._pointerObserver);
  101999. }
  102000. if (this._ownerNode) {
  102001. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  102002. }
  102003. if (this._virtualOriginMesh) {
  102004. this._virtualOriginMesh.dispose();
  102005. }
  102006. if (this._virtualDragMesh) {
  102007. this._virtualDragMesh.dispose();
  102008. }
  102009. this.onDragEndObservable.clear();
  102010. this.onDragStartObservable.clear();
  102011. };
  102012. return SixDofDragBehavior;
  102013. }());
  102014. BABYLON.SixDofDragBehavior = SixDofDragBehavior;
  102015. })(BABYLON || (BABYLON = {}));
  102016. //# sourceMappingURL=babylon.sixDofDragBehavior.js.map
  102017. var BABYLON;
  102018. (function (BABYLON) {
  102019. /**
  102020. * @hidden
  102021. */
  102022. var FaceDirectionInfo = /** @class */ (function () {
  102023. function FaceDirectionInfo(direction, rotatedDirection, diff, ignore) {
  102024. if (rotatedDirection === void 0) { rotatedDirection = new BABYLON.Vector3(); }
  102025. if (diff === void 0) { diff = 0; }
  102026. if (ignore === void 0) { ignore = false; }
  102027. this.direction = direction;
  102028. this.rotatedDirection = rotatedDirection;
  102029. this.diff = diff;
  102030. this.ignore = ignore;
  102031. }
  102032. return FaceDirectionInfo;
  102033. }());
  102034. /**
  102035. * A behavior that when attached to a mesh will will place a specified node on the meshes face pointing towards the camera
  102036. */
  102037. var AttachToBoxBehavior = /** @class */ (function () {
  102038. /**
  102039. * Creates the AttachToBoxBehavior, used to attach UI to the closest face of the box to a camera
  102040. * @param ui The transform node that should be attched to the mesh
  102041. */
  102042. function AttachToBoxBehavior(ui) {
  102043. this.ui = ui;
  102044. /**
  102045. * The name of the behavior
  102046. */
  102047. this.name = "AttachToBoxBehavior";
  102048. /**
  102049. * The distance away from the face of the mesh that the UI should be attached to (default: 0.15)
  102050. */
  102051. this.distanceAwayFromFace = 0.15;
  102052. /**
  102053. * The distance from the bottom of the face that the UI should be attached to (default: 0.15)
  102054. */
  102055. this.distanceAwayFromBottomOfFace = 0.15;
  102056. 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))];
  102057. this._tmpMatrix = new BABYLON.Matrix();
  102058. this._tmpVector = new BABYLON.Vector3();
  102059. this._zeroVector = BABYLON.Vector3.Zero();
  102060. this._lookAtTmpMatrix = new BABYLON.Matrix();
  102061. /* Does nothing */
  102062. }
  102063. /**
  102064. * Initializes the behavior
  102065. */
  102066. AttachToBoxBehavior.prototype.init = function () {
  102067. /* Does nothing */
  102068. };
  102069. AttachToBoxBehavior.prototype._closestFace = function (targetDirection) {
  102070. var _this = this;
  102071. // Go over each face and calculate the angle between the face's normal and targetDirection
  102072. this._faceVectors.forEach(function (v) {
  102073. if (!_this._target.rotationQuaternion) {
  102074. _this._target.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._target.rotation.y, _this._target.rotation.x, _this._target.rotation.z);
  102075. }
  102076. _this._target.rotationQuaternion.toRotationMatrix(_this._tmpMatrix);
  102077. BABYLON.Vector3.TransformCoordinatesToRef(v.direction, _this._tmpMatrix, v.rotatedDirection);
  102078. v.diff = BABYLON.Vector3.GetAngleBetweenVectors(v.rotatedDirection, targetDirection, BABYLON.Vector3.Cross(v.rotatedDirection, targetDirection));
  102079. });
  102080. // Return the face information of the one with the normal closeset to target direction
  102081. return this._faceVectors.reduce(function (min, p) {
  102082. if (min.ignore) {
  102083. return p;
  102084. }
  102085. else if (p.ignore) {
  102086. return min;
  102087. }
  102088. else {
  102089. return min.diff < p.diff ? min : p;
  102090. }
  102091. }, this._faceVectors[0]);
  102092. };
  102093. AttachToBoxBehavior.prototype._lookAtToRef = function (pos, up, ref) {
  102094. if (up === void 0) { up = new BABYLON.Vector3(0, 1, 0); }
  102095. BABYLON.Matrix.LookAtLHToRef(this._zeroVector, pos, up, this._lookAtTmpMatrix);
  102096. this._lookAtTmpMatrix.invert();
  102097. BABYLON.Quaternion.FromRotationMatrixToRef(this._lookAtTmpMatrix, ref);
  102098. };
  102099. /**
  102100. * Attaches the AttachToBoxBehavior to the passed in mesh
  102101. * @param target The mesh that the specified node will be attached to
  102102. */
  102103. AttachToBoxBehavior.prototype.attach = function (target) {
  102104. var _this = this;
  102105. this._target = target;
  102106. this._scene = this._target.getScene();
  102107. // Every frame, update the app bars position
  102108. this._onRenderObserver = this._scene.onBeforeRenderObservable.add(function () {
  102109. if (!_this._scene.activeCamera) {
  102110. return;
  102111. }
  102112. // Find the face closest to the cameras position
  102113. var cameraPos = _this._scene.activeCamera.position;
  102114. if (_this._scene.activeCamera.devicePosition) {
  102115. cameraPos = _this._scene.activeCamera.devicePosition;
  102116. }
  102117. var facing = _this._closestFace(cameraPos.subtract(target.position));
  102118. if (_this._scene.activeCamera.leftCamera) {
  102119. _this._scene.activeCamera.leftCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
  102120. }
  102121. else {
  102122. _this._scene.activeCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
  102123. }
  102124. // Get camera up direction
  102125. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Vector3.Up(), _this._tmpMatrix, _this._tmpVector);
  102126. // Ignore faces to not select a parrelel face for the up vector of the UI
  102127. _this._faceVectors.forEach(function (v) {
  102128. if (facing.direction.x && v.direction.x) {
  102129. v.ignore = true;
  102130. }
  102131. if (facing.direction.y && v.direction.y) {
  102132. v.ignore = true;
  102133. }
  102134. if (facing.direction.z && v.direction.z) {
  102135. v.ignore = true;
  102136. }
  102137. });
  102138. var facingUp = _this._closestFace(_this._tmpVector);
  102139. // Unignore faces
  102140. _this._faceVectors.forEach(function (v) {
  102141. v.ignore = false;
  102142. });
  102143. // Position the app bar on that face
  102144. _this.ui.position.copyFrom(target.position);
  102145. if (facing.direction.x) {
  102146. facing.rotatedDirection.scaleToRef((target.scaling.x / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  102147. _this.ui.position.addInPlace(_this._tmpVector);
  102148. }
  102149. if (facing.direction.y) {
  102150. facing.rotatedDirection.scaleToRef((target.scaling.y / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  102151. _this.ui.position.addInPlace(_this._tmpVector);
  102152. }
  102153. if (facing.direction.z) {
  102154. facing.rotatedDirection.scaleToRef((target.scaling.z / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  102155. _this.ui.position.addInPlace(_this._tmpVector);
  102156. }
  102157. // Rotate to be oriented properly to the camera
  102158. if (!_this.ui.rotationQuaternion) {
  102159. _this.ui.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.ui.rotation.y, _this.ui.rotation.x, _this.ui.rotation.z);
  102160. }
  102161. facing.rotatedDirection.scaleToRef(-1, _this._tmpVector);
  102162. _this._lookAtToRef(_this._tmpVector, facingUp.rotatedDirection, _this.ui.rotationQuaternion);
  102163. // Place ui the correct distance from the bottom of the mesh
  102164. if (facingUp.direction.x) {
  102165. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.x / 2, _this._tmpVector);
  102166. }
  102167. if (facingUp.direction.y) {
  102168. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.y / 2, _this._tmpVector);
  102169. }
  102170. if (facingUp.direction.z) {
  102171. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.z / 2, _this._tmpVector);
  102172. }
  102173. _this.ui.position.addInPlace(_this._tmpVector);
  102174. });
  102175. };
  102176. /**
  102177. * Detaches the behavior from the mesh
  102178. */
  102179. AttachToBoxBehavior.prototype.detach = function () {
  102180. this._scene.onBeforeRenderObservable.remove(this._onRenderObserver);
  102181. };
  102182. return AttachToBoxBehavior;
  102183. }());
  102184. BABYLON.AttachToBoxBehavior = AttachToBoxBehavior;
  102185. })(BABYLON || (BABYLON = {}));
  102186. //# sourceMappingURL=babylon.attachToBoxBehavior.js.map
  102187. var BABYLON;
  102188. (function (BABYLON) {
  102189. /**
  102190. * A behavior that when attached to a mesh will allow the mesh to fade in and out
  102191. */
  102192. var FadeInOutBehavior = /** @class */ (function () {
  102193. /**
  102194. * Instatiates the FadeInOutBehavior
  102195. */
  102196. function FadeInOutBehavior() {
  102197. var _this = this;
  102198. /**
  102199. * Time in milliseconds to delay before fading in (Default: 0)
  102200. */
  102201. this.delay = 0;
  102202. /**
  102203. * Time in milliseconds for the mesh to fade in (Default: 300)
  102204. */
  102205. this.fadeInTime = 300;
  102206. this._millisecondsPerFrame = 1000 / 60;
  102207. this._hovered = false;
  102208. this._hoverValue = 0;
  102209. this._ownerNode = null;
  102210. this._update = function () {
  102211. if (_this._ownerNode) {
  102212. _this._hoverValue += _this._hovered ? _this._millisecondsPerFrame : -_this._millisecondsPerFrame;
  102213. _this._setAllVisibility(_this._ownerNode, (_this._hoverValue - _this.delay) / _this.fadeInTime);
  102214. if (_this._ownerNode.visibility > 1) {
  102215. _this._setAllVisibility(_this._ownerNode, 1);
  102216. _this._hoverValue = _this.fadeInTime + _this.delay;
  102217. return;
  102218. }
  102219. else if (_this._ownerNode.visibility < 0) {
  102220. _this._setAllVisibility(_this._ownerNode, 0);
  102221. if (_this._hoverValue < 0) {
  102222. _this._hoverValue = 0;
  102223. return;
  102224. }
  102225. }
  102226. setTimeout(_this._update, _this._millisecondsPerFrame);
  102227. }
  102228. };
  102229. }
  102230. Object.defineProperty(FadeInOutBehavior.prototype, "name", {
  102231. /**
  102232. * The name of the behavior
  102233. */
  102234. get: function () {
  102235. return "FadeInOut";
  102236. },
  102237. enumerable: true,
  102238. configurable: true
  102239. });
  102240. /**
  102241. * Initializes the behavior
  102242. */
  102243. FadeInOutBehavior.prototype.init = function () {
  102244. };
  102245. /**
  102246. * Attaches the fade behavior on the passed in mesh
  102247. * @param ownerNode The mesh that will be faded in/out once attached
  102248. */
  102249. FadeInOutBehavior.prototype.attach = function (ownerNode) {
  102250. this._ownerNode = ownerNode;
  102251. this._setAllVisibility(this._ownerNode, 0);
  102252. };
  102253. /**
  102254. * Detaches the behavior from the mesh
  102255. */
  102256. FadeInOutBehavior.prototype.detach = function () {
  102257. this._ownerNode = null;
  102258. };
  102259. /**
  102260. * Triggers the mesh to begin fading in or out
  102261. * @param value if the object should fade in or out (true to fade in)
  102262. */
  102263. FadeInOutBehavior.prototype.fadeIn = function (value) {
  102264. this._hovered = value;
  102265. this._update();
  102266. };
  102267. FadeInOutBehavior.prototype._setAllVisibility = function (mesh, value) {
  102268. var _this = this;
  102269. mesh.visibility = value;
  102270. mesh.getChildMeshes().forEach(function (c) {
  102271. _this._setAllVisibility(c, value);
  102272. });
  102273. };
  102274. return FadeInOutBehavior;
  102275. }());
  102276. BABYLON.FadeInOutBehavior = FadeInOutBehavior;
  102277. })(BABYLON || (BABYLON = {}));
  102278. //# sourceMappingURL=babylon.fadeInOutBehavior.js.map
  102279. var BABYLON;
  102280. (function (BABYLON) {
  102281. /**
  102282. * Renders gizmos on top of an existing scene which provide controls for position, rotation, etc.
  102283. */
  102284. var Gizmo = /** @class */ (function () {
  102285. /**
  102286. * Creates a gizmo
  102287. * @param gizmoLayer The utility layer the gizmo will be added to
  102288. */
  102289. function Gizmo(
  102290. /** The utility layer the gizmo will be added to */
  102291. gizmoLayer) {
  102292. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  102293. var _this = this;
  102294. this.gizmoLayer = gizmoLayer;
  102295. /**
  102296. * Ratio for the scale of the gizmo (Default: 1)
  102297. */
  102298. this.scaleRatio = 1;
  102299. this._tmpMatrix = new BABYLON.Matrix();
  102300. /**
  102301. * If a custom mesh has been set (Default: false)
  102302. */
  102303. this._customMeshSet = false;
  102304. /**
  102305. * If set the gizmo's rotation will be updated to match the attached mesh each frame (Default: true)
  102306. */
  102307. this.updateGizmoRotationToMatchAttachedMesh = true;
  102308. /**
  102309. * If set the gizmo's position will be updated to match the attached mesh each frame (Default: true)
  102310. */
  102311. this.updateGizmoPositionToMatchAttachedMesh = true;
  102312. /**
  102313. * When set, the gizmo will always appear the same size no matter where the camera is (default: false)
  102314. */
  102315. this._updateScale = true;
  102316. this._interactionsEnabled = true;
  102317. this._tempVector = new BABYLON.Vector3();
  102318. this._rootMesh = new BABYLON.Mesh("gizmoRootNode", gizmoLayer.utilityLayerScene);
  102319. this._beforeRenderObserver = this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.add(function () {
  102320. _this._update();
  102321. });
  102322. this.attachedMesh = null;
  102323. }
  102324. Object.defineProperty(Gizmo.prototype, "attachedMesh", {
  102325. /**
  102326. * Mesh that the gizmo will be attached to. (eg. on a drag gizmo the mesh that will be dragged)
  102327. * * When set, interactions will be enabled
  102328. */
  102329. get: function () {
  102330. return this._attachedMesh;
  102331. },
  102332. set: function (value) {
  102333. this._attachedMesh = value;
  102334. this._rootMesh.setEnabled(value ? true : false);
  102335. this._attachedMeshChanged(value);
  102336. },
  102337. enumerable: true,
  102338. configurable: true
  102339. });
  102340. /**
  102341. * Disposes and replaces the current meshes in the gizmo with the specified mesh
  102342. * @param mesh The mesh to replace the default mesh of the gizmo
  102343. */
  102344. Gizmo.prototype.setCustomMesh = function (mesh) {
  102345. if (mesh.getScene() != this.gizmoLayer.utilityLayerScene) {
  102346. throw "When setting a custom mesh on a gizmo, the custom meshes scene must be the same as the gizmos (eg. gizmo.gizmoLayer.utilityLayerScene)";
  102347. }
  102348. this._rootMesh.getChildMeshes().forEach(function (c) {
  102349. c.dispose();
  102350. });
  102351. mesh.parent = this._rootMesh;
  102352. this._customMeshSet = true;
  102353. };
  102354. Gizmo.prototype._attachedMeshChanged = function (value) {
  102355. };
  102356. /**
  102357. * @hidden
  102358. * Updates the gizmo to match the attached mesh's position/rotation
  102359. */
  102360. Gizmo.prototype._update = function () {
  102361. if (this.attachedMesh) {
  102362. if (this.updateGizmoRotationToMatchAttachedMesh) {
  102363. if (!this._rootMesh.rotationQuaternion) {
  102364. this._rootMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this._rootMesh.rotation.y, this._rootMesh.rotation.x, this._rootMesh.rotation.z);
  102365. }
  102366. // Remove scaling before getting rotation matrix to get rotation matrix unmodified by scale
  102367. this._tempVector.copyFrom(this.attachedMesh.scaling);
  102368. if (this.attachedMesh.scaling.x < 0) {
  102369. this.attachedMesh.scaling.x *= -1;
  102370. }
  102371. if (this.attachedMesh.scaling.y < 0) {
  102372. this.attachedMesh.scaling.y *= -1;
  102373. }
  102374. if (this.attachedMesh.scaling.z < 0) {
  102375. this.attachedMesh.scaling.z *= -1;
  102376. }
  102377. this.attachedMesh.computeWorldMatrix().getRotationMatrixToRef(this._tmpMatrix);
  102378. this.attachedMesh.scaling.copyFrom(this._tempVector);
  102379. this.attachedMesh.computeWorldMatrix();
  102380. BABYLON.Quaternion.FromRotationMatrixToRef(this._tmpMatrix, this._rootMesh.rotationQuaternion);
  102381. }
  102382. else if (this._rootMesh.rotationQuaternion) {
  102383. this._rootMesh.rotationQuaternion.set(0, 0, 0, 1);
  102384. }
  102385. if (this.updateGizmoPositionToMatchAttachedMesh) {
  102386. this._rootMesh.position.copyFrom(this.attachedMesh.absolutePosition);
  102387. }
  102388. if (this._updateScale && this.gizmoLayer.utilityLayerScene.activeCamera && this.attachedMesh) {
  102389. var cameraPosition = this.gizmoLayer.utilityLayerScene.activeCamera.globalPosition;
  102390. if (this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition) {
  102391. cameraPosition = this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition;
  102392. }
  102393. this._rootMesh.position.subtractToRef(cameraPosition, this._tempVector);
  102394. var dist = this._tempVector.length() * this.scaleRatio;
  102395. this._rootMesh.scaling.set(dist, dist, dist);
  102396. }
  102397. }
  102398. };
  102399. /**
  102400. * Disposes of the gizmo
  102401. */
  102402. Gizmo.prototype.dispose = function () {
  102403. this._rootMesh.dispose();
  102404. if (this._beforeRenderObserver) {
  102405. this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  102406. }
  102407. };
  102408. return Gizmo;
  102409. }());
  102410. BABYLON.Gizmo = Gizmo;
  102411. })(BABYLON || (BABYLON = {}));
  102412. //# sourceMappingURL=babylon.gizmo.js.map
  102413. var BABYLON;
  102414. (function (BABYLON) {
  102415. /**
  102416. * Single axis drag gizmo
  102417. */
  102418. var AxisDragGizmo = /** @class */ (function (_super) {
  102419. __extends(AxisDragGizmo, _super);
  102420. /**
  102421. * Creates an AxisDragGizmo
  102422. * @param gizmoLayer The utility layer the gizmo will be added to
  102423. * @param dragAxis The axis which the gizmo will be able to drag on
  102424. * @param color The color of the gizmo
  102425. */
  102426. function AxisDragGizmo(dragAxis, color, gizmoLayer) {
  102427. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  102428. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  102429. var _this = _super.call(this, gizmoLayer) || this;
  102430. _this._pointerObserver = null;
  102431. /**
  102432. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  102433. */
  102434. _this.snapDistance = 0;
  102435. /**
  102436. * Event that fires each time the gizmo snaps to a new location.
  102437. * * snapDistance is the the change in distance
  102438. */
  102439. _this.onSnapObservable = new BABYLON.Observable();
  102440. // Create Material
  102441. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  102442. coloredMaterial.disableLighting = true;
  102443. coloredMaterial.emissiveColor = color;
  102444. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  102445. hoverMaterial.disableLighting = true;
  102446. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  102447. // Build mesh on root node
  102448. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  102449. var arrowMesh = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameterTop: 0, height: 1.5, diameterBottom: 0.75, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  102450. var arrowTail = BABYLON.MeshBuilder.CreateLines("yPosMesh", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 1.1, 0)] }, gizmoLayer.utilityLayerScene);
  102451. arrowTail.color = coloredMaterial.emissiveColor;
  102452. arrow.addChild(arrowMesh);
  102453. arrow.addChild(arrowTail);
  102454. // Position arrow pointing in its drag axis
  102455. arrowMesh.scaling.scaleInPlace(0.05);
  102456. arrowMesh.material = coloredMaterial;
  102457. arrowMesh.rotation.x = Math.PI / 2;
  102458. arrowMesh.position.z += 0.3;
  102459. arrowTail.scaling.scaleInPlace(0.26);
  102460. arrowTail.rotation.x = Math.PI / 2;
  102461. arrowTail.material = coloredMaterial;
  102462. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  102463. arrow.scaling.scaleInPlace(1 / 3);
  102464. _this._rootMesh.addChild(arrow);
  102465. var currentSnapDragDistance = 0;
  102466. var tmpVector = new BABYLON.Vector3();
  102467. var tmpSnapEvent = { snapDistance: 0 };
  102468. // Add drag behavior to handle events when the gizmo is dragged
  102469. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  102470. _this.dragBehavior.moveAttached = false;
  102471. _this._rootMesh.addBehavior(_this.dragBehavior);
  102472. var localDelta = new BABYLON.Vector3();
  102473. var tmpMatrix = new BABYLON.Matrix();
  102474. _this.dragBehavior.onDragObservable.add(function (event) {
  102475. if (_this.attachedMesh) {
  102476. // Convert delta to local translation if it has a parent
  102477. if (_this.attachedMesh.parent) {
  102478. _this.attachedMesh.parent.computeWorldMatrix().invertToRef(tmpMatrix);
  102479. tmpMatrix.setTranslationFromFloats(0, 0, 0);
  102480. BABYLON.Vector3.TransformCoordinatesToRef(event.delta, tmpMatrix, localDelta);
  102481. }
  102482. else {
  102483. localDelta.copyFrom(event.delta);
  102484. }
  102485. // Snapping logic
  102486. if (_this.snapDistance == 0) {
  102487. _this.attachedMesh.position.addInPlace(localDelta);
  102488. }
  102489. else {
  102490. currentSnapDragDistance += event.dragDistance;
  102491. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  102492. var dragSteps = Math.floor(Math.abs(currentSnapDragDistance) / _this.snapDistance);
  102493. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  102494. localDelta.normalizeToRef(tmpVector);
  102495. tmpVector.scaleInPlace(_this.snapDistance * dragSteps);
  102496. _this.attachedMesh.position.addInPlace(tmpVector);
  102497. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  102498. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  102499. }
  102500. }
  102501. }
  102502. });
  102503. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  102504. if (_this._customMeshSet) {
  102505. return;
  102506. }
  102507. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  102508. var material = isHovered ? hoverMaterial : coloredMaterial;
  102509. _this._rootMesh.getChildMeshes().forEach(function (m) {
  102510. m.material = material;
  102511. if (m.color) {
  102512. m.color = material.emissiveColor;
  102513. }
  102514. });
  102515. });
  102516. return _this;
  102517. }
  102518. AxisDragGizmo.prototype._attachedMeshChanged = function (value) {
  102519. if (this.dragBehavior) {
  102520. this.dragBehavior.enabled = value ? true : false;
  102521. }
  102522. };
  102523. /**
  102524. * Disposes of the gizmo
  102525. */
  102526. AxisDragGizmo.prototype.dispose = function () {
  102527. this.onSnapObservable.clear();
  102528. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  102529. this.dragBehavior.detach();
  102530. _super.prototype.dispose.call(this);
  102531. };
  102532. return AxisDragGizmo;
  102533. }(BABYLON.Gizmo));
  102534. BABYLON.AxisDragGizmo = AxisDragGizmo;
  102535. })(BABYLON || (BABYLON = {}));
  102536. //# sourceMappingURL=babylon.axisDragGizmo.js.map
  102537. var BABYLON;
  102538. (function (BABYLON) {
  102539. /**
  102540. * Single axis scale gizmo
  102541. */
  102542. var AxisScaleGizmo = /** @class */ (function (_super) {
  102543. __extends(AxisScaleGizmo, _super);
  102544. /**
  102545. * Creates an AxisScaleGizmo
  102546. * @param gizmoLayer The utility layer the gizmo will be added to
  102547. * @param dragAxis The axis which the gizmo will be able to scale on
  102548. * @param color The color of the gizmo
  102549. */
  102550. function AxisScaleGizmo(dragAxis, color, gizmoLayer) {
  102551. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  102552. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  102553. var _this = _super.call(this, gizmoLayer) || this;
  102554. _this._pointerObserver = null;
  102555. /**
  102556. * Scale distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  102557. */
  102558. _this.snapDistance = 0;
  102559. /**
  102560. * Event that fires each time the gizmo snaps to a new location.
  102561. * * snapDistance is the the change in distance
  102562. */
  102563. _this.onSnapObservable = new BABYLON.Observable();
  102564. /**
  102565. * If the scaling operation should be done on all axis (default: false)
  102566. */
  102567. _this.uniformScaling = false;
  102568. // Create Material
  102569. _this._coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  102570. _this._coloredMaterial.disableLighting = true;
  102571. _this._coloredMaterial.emissiveColor = color;
  102572. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  102573. hoverMaterial.disableLighting = true;
  102574. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  102575. // Build mesh on root node
  102576. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  102577. var arrowMesh = BABYLON.MeshBuilder.CreateBox("yPosMesh", { size: 0.4 }, gizmoLayer.utilityLayerScene);
  102578. var arrowTail = BABYLON.MeshBuilder.CreateLines("yPosMesh", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 1.1, 0)] }, gizmoLayer.utilityLayerScene);
  102579. arrowTail.color = _this._coloredMaterial.emissiveColor;
  102580. arrow.addChild(arrowMesh);
  102581. arrow.addChild(arrowTail);
  102582. // Position arrow pointing in its drag axis
  102583. arrowMesh.scaling.scaleInPlace(0.1);
  102584. arrowMesh.material = _this._coloredMaterial;
  102585. arrowMesh.rotation.x = Math.PI / 2;
  102586. arrowMesh.position.z += 0.3;
  102587. arrowTail.scaling.scaleInPlace(0.26);
  102588. arrowTail.rotation.x = Math.PI / 2;
  102589. arrowTail.material = _this._coloredMaterial;
  102590. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  102591. _this._rootMesh.addChild(arrow);
  102592. arrow.scaling.scaleInPlace(1 / 3);
  102593. // Add drag behavior to handle events when the gizmo is dragged
  102594. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  102595. _this.dragBehavior.moveAttached = false;
  102596. _this._rootMesh.addBehavior(_this.dragBehavior);
  102597. var currentSnapDragDistance = 0;
  102598. var tmpVector = new BABYLON.Vector3();
  102599. var tmpSnapEvent = { snapDistance: 0 };
  102600. _this.dragBehavior.onDragObservable.add(function (event) {
  102601. if (_this.attachedMesh) {
  102602. // Snapping logic
  102603. var snapped = false;
  102604. var dragSteps = 0;
  102605. if (_this.uniformScaling) {
  102606. _this.attachedMesh.scaling.normalizeToRef(tmpVector);
  102607. if (tmpVector.y < 0) {
  102608. tmpVector.scaleInPlace(-1);
  102609. }
  102610. }
  102611. else {
  102612. tmpVector.copyFrom(dragAxis);
  102613. }
  102614. if (_this.snapDistance == 0) {
  102615. tmpVector.scaleToRef(event.dragDistance, tmpVector);
  102616. }
  102617. else {
  102618. currentSnapDragDistance += event.dragDistance;
  102619. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  102620. dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  102621. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  102622. tmpVector.scaleToRef(_this.snapDistance * dragSteps, tmpVector);
  102623. snapped = true;
  102624. }
  102625. else {
  102626. tmpVector.scaleInPlace(0);
  102627. }
  102628. }
  102629. _this.attachedMesh.scaling.addInPlace(tmpVector);
  102630. if (snapped) {
  102631. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  102632. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  102633. }
  102634. }
  102635. });
  102636. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  102637. if (_this._customMeshSet) {
  102638. return;
  102639. }
  102640. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  102641. var material = isHovered ? hoverMaterial : _this._coloredMaterial;
  102642. _this._rootMesh.getChildMeshes().forEach(function (m) {
  102643. m.material = material;
  102644. if (m.color) {
  102645. m.color = material.emissiveColor;
  102646. }
  102647. });
  102648. });
  102649. return _this;
  102650. }
  102651. AxisScaleGizmo.prototype._attachedMeshChanged = function (value) {
  102652. if (this.dragBehavior) {
  102653. this.dragBehavior.enabled = value ? true : false;
  102654. }
  102655. };
  102656. /**
  102657. * Disposes of the gizmo
  102658. */
  102659. AxisScaleGizmo.prototype.dispose = function () {
  102660. this.onSnapObservable.clear();
  102661. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  102662. this.dragBehavior.detach();
  102663. _super.prototype.dispose.call(this);
  102664. };
  102665. /**
  102666. * Disposes and replaces the current meshes in the gizmo with the specified mesh
  102667. * @param mesh The mesh to replace the default mesh of the gizmo
  102668. * @param useGizmoMaterial If the gizmo's default material should be used (default: false)
  102669. */
  102670. AxisScaleGizmo.prototype.setCustomMesh = function (mesh, useGizmoMaterial) {
  102671. var _this = this;
  102672. if (useGizmoMaterial === void 0) { useGizmoMaterial = false; }
  102673. _super.prototype.setCustomMesh.call(this, mesh);
  102674. if (useGizmoMaterial) {
  102675. this._rootMesh.getChildMeshes().forEach(function (m) {
  102676. m.material = _this._coloredMaterial;
  102677. if (m.color) {
  102678. m.color = _this._coloredMaterial.emissiveColor;
  102679. }
  102680. });
  102681. this._customMeshSet = false;
  102682. }
  102683. };
  102684. return AxisScaleGizmo;
  102685. }(BABYLON.Gizmo));
  102686. BABYLON.AxisScaleGizmo = AxisScaleGizmo;
  102687. })(BABYLON || (BABYLON = {}));
  102688. //# sourceMappingURL=babylon.axisScaleGizmo.js.map
  102689. var BABYLON;
  102690. (function (BABYLON) {
  102691. /**
  102692. * Single plane rotation gizmo
  102693. */
  102694. var PlaneRotationGizmo = /** @class */ (function (_super) {
  102695. __extends(PlaneRotationGizmo, _super);
  102696. /**
  102697. * Creates a PlaneRotationGizmo
  102698. * @param gizmoLayer The utility layer the gizmo will be added to
  102699. * @param planeNormal The normal of the plane which the gizmo will be able to rotate on
  102700. * @param color The color of the gizmo
  102701. * @param tessellation Amount of tessellation to be used when creating rotation circles
  102702. */
  102703. function PlaneRotationGizmo(planeNormal, color, gizmoLayer, tessellation) {
  102704. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  102705. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  102706. if (tessellation === void 0) { tessellation = 32; }
  102707. var _this = _super.call(this, gizmoLayer) || this;
  102708. _this._pointerObserver = null;
  102709. /**
  102710. * Rotation distance in radians that the gizmo will snap to (Default: 0)
  102711. */
  102712. _this.snapDistance = 0;
  102713. /**
  102714. * Event that fires each time the gizmo snaps to a new location.
  102715. * * snapDistance is the the change in distance
  102716. */
  102717. _this.onSnapObservable = new BABYLON.Observable();
  102718. // Create Material
  102719. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  102720. coloredMaterial.disableLighting = true;
  102721. coloredMaterial.emissiveColor = color;
  102722. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  102723. hoverMaterial.disableLighting = true;
  102724. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  102725. // Build mesh on root node
  102726. var parentMesh = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  102727. // Create circle out of lines
  102728. var radius = 0.8;
  102729. var points = new Array();
  102730. for (var i = 0; i < tessellation; i++) {
  102731. var radian = (2 * Math.PI) * (i / (tessellation - 1));
  102732. points.push(new BABYLON.Vector3(radius * Math.sin(radian), 0, radius * Math.cos(radian)));
  102733. }
  102734. var rotationMesh = BABYLON.Mesh.CreateLines("", points, gizmoLayer.utilityLayerScene);
  102735. rotationMesh.color = coloredMaterial.emissiveColor;
  102736. // Position arrow pointing in its drag axis
  102737. rotationMesh.scaling.scaleInPlace(0.26);
  102738. rotationMesh.material = coloredMaterial;
  102739. rotationMesh.rotation.x = Math.PI / 2;
  102740. parentMesh.addChild(rotationMesh);
  102741. parentMesh.lookAt(_this._rootMesh.position.subtract(planeNormal));
  102742. _this._rootMesh.addChild(parentMesh);
  102743. parentMesh.scaling.scaleInPlace(1 / 3);
  102744. // Add drag behavior to handle events when the gizmo is dragged
  102745. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragPlaneNormal: planeNormal });
  102746. _this.dragBehavior.moveAttached = false;
  102747. _this.dragBehavior.maxDragAngle = Math.PI * 9 / 20;
  102748. _this.dragBehavior._useAlternatePickedPointAboveMaxDragAngle = true;
  102749. _this._rootMesh.addBehavior(_this.dragBehavior);
  102750. var lastDragPosition = new BABYLON.Vector3();
  102751. _this.dragBehavior.onDragStartObservable.add(function (e) {
  102752. if (_this.attachedMesh) {
  102753. lastDragPosition.copyFrom(e.dragPlanePoint);
  102754. }
  102755. });
  102756. var rotationMatrix = new BABYLON.Matrix();
  102757. var planeNormalTowardsCamera = new BABYLON.Vector3();
  102758. var localPlaneNormalTowardsCamera = new BABYLON.Vector3();
  102759. var tmpSnapEvent = { snapDistance: 0 };
  102760. var currentSnapDragDistance = 0;
  102761. var tmpMatrix = new BABYLON.Matrix();
  102762. var tmpVector = new BABYLON.Vector3();
  102763. var amountToRotate = new BABYLON.Quaternion();
  102764. _this.dragBehavior.onDragObservable.add(function (event) {
  102765. if (_this.attachedMesh) {
  102766. if (!_this.attachedMesh.rotationQuaternion) {
  102767. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  102768. }
  102769. // Calc angle over full 360 degree (https://stackoverflow.com/questions/43493711/the-angle-between-two-3d-vectors-with-a-result-range-0-360)
  102770. var newVector = event.dragPlanePoint.subtract(_this.attachedMesh.absolutePosition).normalize();
  102771. var originalVector = lastDragPosition.subtract(_this.attachedMesh.absolutePosition).normalize();
  102772. var cross = BABYLON.Vector3.Cross(newVector, originalVector);
  102773. var dot = BABYLON.Vector3.Dot(newVector, originalVector);
  102774. var angle = Math.atan2(cross.length(), dot);
  102775. planeNormalTowardsCamera.copyFrom(planeNormal);
  102776. localPlaneNormalTowardsCamera.copyFrom(planeNormal);
  102777. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  102778. _this.attachedMesh.rotationQuaternion.toRotationMatrix(rotationMatrix);
  102779. localPlaneNormalTowardsCamera = BABYLON.Vector3.TransformCoordinates(planeNormalTowardsCamera, rotationMatrix);
  102780. }
  102781. // Flip up vector depending on which side the camera is on
  102782. if (gizmoLayer.utilityLayerScene.activeCamera) {
  102783. var camVec = gizmoLayer.utilityLayerScene.activeCamera.position.subtract(_this.attachedMesh.position);
  102784. if (BABYLON.Vector3.Dot(camVec, localPlaneNormalTowardsCamera) > 0) {
  102785. planeNormalTowardsCamera.scaleInPlace(-1);
  102786. localPlaneNormalTowardsCamera.scaleInPlace(-1);
  102787. }
  102788. }
  102789. var halfCircleSide = BABYLON.Vector3.Dot(localPlaneNormalTowardsCamera, cross) > 0.0;
  102790. if (halfCircleSide) {
  102791. angle = -angle;
  102792. }
  102793. // Snapping logic
  102794. var snapped = false;
  102795. if (_this.snapDistance != 0) {
  102796. currentSnapDragDistance += angle;
  102797. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  102798. var dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  102799. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  102800. angle = _this.snapDistance * dragSteps;
  102801. snapped = true;
  102802. }
  102803. else {
  102804. angle = 0;
  102805. }
  102806. }
  102807. // If the mesh has a parent, convert needed world rotation to local rotation
  102808. tmpMatrix.reset();
  102809. if (_this.attachedMesh.parent) {
  102810. _this.attachedMesh.parent.computeWorldMatrix().invertToRef(tmpMatrix);
  102811. tmpMatrix.getRotationMatrixToRef(tmpMatrix);
  102812. BABYLON.Vector3.TransformCoordinatesToRef(planeNormalTowardsCamera, tmpMatrix, planeNormalTowardsCamera);
  102813. }
  102814. // Convert angle and axis to quaternion (http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm)
  102815. var quaternionCoefficient = Math.sin(angle / 2);
  102816. amountToRotate.set(planeNormalTowardsCamera.x * quaternionCoefficient, planeNormalTowardsCamera.y * quaternionCoefficient, planeNormalTowardsCamera.z * quaternionCoefficient, Math.cos(angle / 2));
  102817. // 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
  102818. if (tmpMatrix.determinant() > 0) {
  102819. amountToRotate.toEulerAnglesToRef(tmpVector);
  102820. BABYLON.Quaternion.RotationYawPitchRollToRef(tmpVector.y, -tmpVector.x, -tmpVector.z, amountToRotate);
  102821. }
  102822. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  102823. // Rotate selected mesh quaternion over fixed axis
  102824. _this.attachedMesh.rotationQuaternion.multiplyToRef(amountToRotate, _this.attachedMesh.rotationQuaternion);
  102825. }
  102826. else {
  102827. // Rotate selected mesh quaternion over rotated axis
  102828. amountToRotate.multiplyToRef(_this.attachedMesh.rotationQuaternion, _this.attachedMesh.rotationQuaternion);
  102829. }
  102830. lastDragPosition.copyFrom(event.dragPlanePoint);
  102831. if (snapped) {
  102832. tmpSnapEvent.snapDistance = angle;
  102833. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  102834. }
  102835. }
  102836. });
  102837. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  102838. if (_this._customMeshSet) {
  102839. return;
  102840. }
  102841. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  102842. var material = isHovered ? hoverMaterial : coloredMaterial;
  102843. _this._rootMesh.getChildMeshes().forEach(function (m) {
  102844. m.material = material;
  102845. if (m.color) {
  102846. m.color = material.emissiveColor;
  102847. }
  102848. });
  102849. });
  102850. return _this;
  102851. }
  102852. PlaneRotationGizmo.prototype._attachedMeshChanged = function (value) {
  102853. if (this.dragBehavior) {
  102854. this.dragBehavior.enabled = value ? true : false;
  102855. }
  102856. };
  102857. /**
  102858. * Disposes of the gizmo
  102859. */
  102860. PlaneRotationGizmo.prototype.dispose = function () {
  102861. this.onSnapObservable.clear();
  102862. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  102863. this.dragBehavior.detach();
  102864. _super.prototype.dispose.call(this);
  102865. };
  102866. return PlaneRotationGizmo;
  102867. }(BABYLON.Gizmo));
  102868. BABYLON.PlaneRotationGizmo = PlaneRotationGizmo;
  102869. })(BABYLON || (BABYLON = {}));
  102870. //# sourceMappingURL=babylon.planeRotationGizmo.js.map
  102871. var BABYLON;
  102872. (function (BABYLON) {
  102873. /**
  102874. * Gizmo that enables dragging a mesh along 3 axis
  102875. */
  102876. var PositionGizmo = /** @class */ (function (_super) {
  102877. __extends(PositionGizmo, _super);
  102878. /**
  102879. * Creates a PositionGizmo
  102880. * @param gizmoLayer The utility layer the gizmo will be added to
  102881. */
  102882. function PositionGizmo(gizmoLayer) {
  102883. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  102884. var _this = _super.call(this, gizmoLayer) || this;
  102885. /** Fires an event when any of it's sub gizmos are dragged */
  102886. _this.onDragStartObservable = new BABYLON.Observable();
  102887. /** Fires an event when any of it's sub gizmos are released from dragging */
  102888. _this.onDragEndObservable = new BABYLON.Observable();
  102889. _this.xGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  102890. _this.yGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  102891. _this.zGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  102892. // Relay drag events
  102893. [_this.xGizmo, _this.yGizmo, _this.zGizmo].forEach(function (gizmo) {
  102894. gizmo.dragBehavior.onDragStartObservable.add(function () {
  102895. _this.onDragStartObservable.notifyObservers({});
  102896. });
  102897. gizmo.dragBehavior.onDragEndObservable.add(function () {
  102898. _this.onDragEndObservable.notifyObservers({});
  102899. });
  102900. });
  102901. _this.attachedMesh = null;
  102902. return _this;
  102903. }
  102904. Object.defineProperty(PositionGizmo.prototype, "attachedMesh", {
  102905. set: function (mesh) {
  102906. if (this.xGizmo) {
  102907. this.xGizmo.attachedMesh = mesh;
  102908. this.yGizmo.attachedMesh = mesh;
  102909. this.zGizmo.attachedMesh = mesh;
  102910. }
  102911. },
  102912. enumerable: true,
  102913. configurable: true
  102914. });
  102915. Object.defineProperty(PositionGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  102916. get: function () {
  102917. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  102918. },
  102919. set: function (value) {
  102920. if (this.xGizmo) {
  102921. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  102922. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  102923. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  102924. }
  102925. },
  102926. enumerable: true,
  102927. configurable: true
  102928. });
  102929. Object.defineProperty(PositionGizmo.prototype, "snapDistance", {
  102930. get: function () {
  102931. return this.xGizmo.snapDistance;
  102932. },
  102933. /**
  102934. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  102935. */
  102936. set: function (value) {
  102937. if (this.xGizmo) {
  102938. this.xGizmo.snapDistance = value;
  102939. this.yGizmo.snapDistance = value;
  102940. this.zGizmo.snapDistance = value;
  102941. }
  102942. },
  102943. enumerable: true,
  102944. configurable: true
  102945. });
  102946. Object.defineProperty(PositionGizmo.prototype, "scaleRatio", {
  102947. get: function () {
  102948. return this.xGizmo.scaleRatio;
  102949. },
  102950. /**
  102951. * Ratio for the scale of the gizmo (Default: 1)
  102952. */
  102953. set: function (value) {
  102954. if (this.xGizmo) {
  102955. this.xGizmo.scaleRatio = value;
  102956. this.yGizmo.scaleRatio = value;
  102957. this.zGizmo.scaleRatio = value;
  102958. }
  102959. },
  102960. enumerable: true,
  102961. configurable: true
  102962. });
  102963. /**
  102964. * Disposes of the gizmo
  102965. */
  102966. PositionGizmo.prototype.dispose = function () {
  102967. this.xGizmo.dispose();
  102968. this.yGizmo.dispose();
  102969. this.zGizmo.dispose();
  102970. this.onDragStartObservable.clear();
  102971. this.onDragEndObservable.clear();
  102972. };
  102973. /**
  102974. * CustomMeshes are not supported by this gizmo
  102975. * @param mesh The mesh to replace the default mesh of the gizmo
  102976. */
  102977. PositionGizmo.prototype.setCustomMesh = function (mesh) {
  102978. 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)");
  102979. };
  102980. return PositionGizmo;
  102981. }(BABYLON.Gizmo));
  102982. BABYLON.PositionGizmo = PositionGizmo;
  102983. })(BABYLON || (BABYLON = {}));
  102984. //# sourceMappingURL=babylon.positionGizmo.js.map
  102985. var BABYLON;
  102986. (function (BABYLON) {
  102987. /**
  102988. * Gizmo that enables rotating a mesh along 3 axis
  102989. */
  102990. var RotationGizmo = /** @class */ (function (_super) {
  102991. __extends(RotationGizmo, _super);
  102992. /**
  102993. * Creates a RotationGizmo
  102994. * @param gizmoLayer The utility layer the gizmo will be added to
  102995. * @param tessellation Amount of tessellation to be used when creating rotation circles
  102996. */
  102997. function RotationGizmo(gizmoLayer, tessellation) {
  102998. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  102999. if (tessellation === void 0) { tessellation = 32; }
  103000. var _this = _super.call(this, gizmoLayer) || this;
  103001. /** Fires an event when any of it's sub gizmos are dragged */
  103002. _this.onDragStartObservable = new BABYLON.Observable();
  103003. /** Fires an event when any of it's sub gizmos are released from dragging */
  103004. _this.onDragEndObservable = new BABYLON.Observable();
  103005. _this.xGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer, tessellation);
  103006. _this.yGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer, tessellation);
  103007. _this.zGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer, tessellation);
  103008. // Relay drag events
  103009. [_this.xGizmo, _this.yGizmo, _this.zGizmo].forEach(function (gizmo) {
  103010. gizmo.dragBehavior.onDragStartObservable.add(function () {
  103011. _this.onDragStartObservable.notifyObservers({});
  103012. });
  103013. gizmo.dragBehavior.onDragEndObservable.add(function () {
  103014. _this.onDragEndObservable.notifyObservers({});
  103015. });
  103016. });
  103017. _this.attachedMesh = null;
  103018. return _this;
  103019. }
  103020. Object.defineProperty(RotationGizmo.prototype, "attachedMesh", {
  103021. set: function (mesh) {
  103022. if (this.xGizmo) {
  103023. this.xGizmo.attachedMesh = mesh;
  103024. this.yGizmo.attachedMesh = mesh;
  103025. this.zGizmo.attachedMesh = mesh;
  103026. }
  103027. },
  103028. enumerable: true,
  103029. configurable: true
  103030. });
  103031. Object.defineProperty(RotationGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  103032. get: function () {
  103033. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  103034. },
  103035. set: function (value) {
  103036. if (this.xGizmo) {
  103037. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  103038. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  103039. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  103040. }
  103041. },
  103042. enumerable: true,
  103043. configurable: true
  103044. });
  103045. Object.defineProperty(RotationGizmo.prototype, "snapDistance", {
  103046. get: function () {
  103047. return this.xGizmo.snapDistance;
  103048. },
  103049. /**
  103050. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  103051. */
  103052. set: function (value) {
  103053. if (this.xGizmo) {
  103054. this.xGizmo.snapDistance = value;
  103055. this.yGizmo.snapDistance = value;
  103056. this.zGizmo.snapDistance = value;
  103057. }
  103058. },
  103059. enumerable: true,
  103060. configurable: true
  103061. });
  103062. Object.defineProperty(RotationGizmo.prototype, "scaleRatio", {
  103063. get: function () {
  103064. return this.xGizmo.scaleRatio;
  103065. },
  103066. /**
  103067. * Ratio for the scale of the gizmo (Default: 1)
  103068. */
  103069. set: function (value) {
  103070. if (this.xGizmo) {
  103071. this.xGizmo.scaleRatio = value;
  103072. this.yGizmo.scaleRatio = value;
  103073. this.zGizmo.scaleRatio = value;
  103074. }
  103075. },
  103076. enumerable: true,
  103077. configurable: true
  103078. });
  103079. /**
  103080. * Disposes of the gizmo
  103081. */
  103082. RotationGizmo.prototype.dispose = function () {
  103083. this.xGizmo.dispose();
  103084. this.yGizmo.dispose();
  103085. this.zGizmo.dispose();
  103086. this.onDragStartObservable.clear();
  103087. this.onDragEndObservable.clear();
  103088. };
  103089. /**
  103090. * CustomMeshes are not supported by this gizmo
  103091. * @param mesh The mesh to replace the default mesh of the gizmo
  103092. */
  103093. RotationGizmo.prototype.setCustomMesh = function (mesh) {
  103094. 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)");
  103095. };
  103096. return RotationGizmo;
  103097. }(BABYLON.Gizmo));
  103098. BABYLON.RotationGizmo = RotationGizmo;
  103099. })(BABYLON || (BABYLON = {}));
  103100. //# sourceMappingURL=babylon.rotationGizmo.js.map
  103101. var BABYLON;
  103102. (function (BABYLON) {
  103103. /**
  103104. * Gizmo that enables scaling a mesh along 3 axis
  103105. */
  103106. var ScaleGizmo = /** @class */ (function (_super) {
  103107. __extends(ScaleGizmo, _super);
  103108. /**
  103109. * Creates a ScaleGizmo
  103110. * @param gizmoLayer The utility layer the gizmo will be added to
  103111. */
  103112. function ScaleGizmo(gizmoLayer) {
  103113. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  103114. var _this = _super.call(this, gizmoLayer) || this;
  103115. /** Fires an event when any of it's sub gizmos are dragged */
  103116. _this.onDragStartObservable = new BABYLON.Observable();
  103117. /** Fires an event when any of it's sub gizmos are released from dragging */
  103118. _this.onDragEndObservable = new BABYLON.Observable();
  103119. _this.xGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  103120. _this.yGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  103121. _this.zGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  103122. // Create uniform scale gizmo
  103123. _this.uniformScaleGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Yellow().scale(0.5), gizmoLayer);
  103124. _this.uniformScaleGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  103125. _this.uniformScaleGizmo.uniformScaling = true;
  103126. var uniformScalingMesh = BABYLON.Mesh.CreatePolyhedron("", { type: 1 }, _this.uniformScaleGizmo.gizmoLayer.utilityLayerScene);
  103127. uniformScalingMesh.scaling.scaleInPlace(0.02);
  103128. uniformScalingMesh.visibility = 0;
  103129. var octahedron = BABYLON.Mesh.CreatePolyhedron("", { type: 1 }, _this.uniformScaleGizmo.gizmoLayer.utilityLayerScene);
  103130. octahedron.scaling.scaleInPlace(0.007);
  103131. uniformScalingMesh.addChild(octahedron);
  103132. _this.uniformScaleGizmo.setCustomMesh(uniformScalingMesh, true);
  103133. // Relay drag events
  103134. [_this.xGizmo, _this.yGizmo, _this.zGizmo, _this.uniformScaleGizmo].forEach(function (gizmo) {
  103135. gizmo.dragBehavior.onDragStartObservable.add(function () {
  103136. _this.onDragStartObservable.notifyObservers({});
  103137. });
  103138. gizmo.dragBehavior.onDragEndObservable.add(function () {
  103139. _this.onDragEndObservable.notifyObservers({});
  103140. });
  103141. });
  103142. _this.attachedMesh = null;
  103143. return _this;
  103144. }
  103145. Object.defineProperty(ScaleGizmo.prototype, "attachedMesh", {
  103146. set: function (mesh) {
  103147. if (this.xGizmo) {
  103148. this.xGizmo.attachedMesh = mesh;
  103149. this.yGizmo.attachedMesh = mesh;
  103150. this.zGizmo.attachedMesh = mesh;
  103151. this.uniformScaleGizmo.attachedMesh = mesh;
  103152. }
  103153. },
  103154. enumerable: true,
  103155. configurable: true
  103156. });
  103157. Object.defineProperty(ScaleGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  103158. get: function () {
  103159. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  103160. },
  103161. set: function (value) {
  103162. if (!value) {
  103163. BABYLON.Tools.Warn("Setting updateGizmoRotationToMatchAttachedMesh = false on scaling gizmo is not supported.");
  103164. }
  103165. if (this.xGizmo) {
  103166. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  103167. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  103168. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  103169. }
  103170. },
  103171. enumerable: true,
  103172. configurable: true
  103173. });
  103174. Object.defineProperty(ScaleGizmo.prototype, "snapDistance", {
  103175. get: function () {
  103176. return this.xGizmo.snapDistance;
  103177. },
  103178. /**
  103179. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  103180. */
  103181. set: function (value) {
  103182. if (this.xGizmo) {
  103183. this.xGizmo.snapDistance = value;
  103184. this.yGizmo.snapDistance = value;
  103185. this.zGizmo.snapDistance = value;
  103186. this.uniformScaleGizmo.snapDistance = value;
  103187. }
  103188. },
  103189. enumerable: true,
  103190. configurable: true
  103191. });
  103192. Object.defineProperty(ScaleGizmo.prototype, "scaleRatio", {
  103193. get: function () {
  103194. return this.xGizmo.scaleRatio;
  103195. },
  103196. /**
  103197. * Ratio for the scale of the gizmo (Default: 1)
  103198. */
  103199. set: function (value) {
  103200. if (this.xGizmo) {
  103201. this.xGizmo.scaleRatio = value;
  103202. this.yGizmo.scaleRatio = value;
  103203. this.zGizmo.scaleRatio = value;
  103204. this.uniformScaleGizmo.scaleRatio = value;
  103205. }
  103206. },
  103207. enumerable: true,
  103208. configurable: true
  103209. });
  103210. /**
  103211. * Disposes of the gizmo
  103212. */
  103213. ScaleGizmo.prototype.dispose = function () {
  103214. this.xGizmo.dispose();
  103215. this.yGizmo.dispose();
  103216. this.zGizmo.dispose();
  103217. this.uniformScaleGizmo.dispose();
  103218. this.onDragStartObservable.clear();
  103219. this.onDragEndObservable.clear();
  103220. };
  103221. return ScaleGizmo;
  103222. }(BABYLON.Gizmo));
  103223. BABYLON.ScaleGizmo = ScaleGizmo;
  103224. })(BABYLON || (BABYLON = {}));
  103225. //# sourceMappingURL=babylon.scaleGizmo.js.map
  103226. var BABYLON;
  103227. (function (BABYLON) {
  103228. /**
  103229. * Bounding box gizmo
  103230. */
  103231. var BoundingBoxGizmo = /** @class */ (function (_super) {
  103232. __extends(BoundingBoxGizmo, _super);
  103233. /**
  103234. * Creates an BoundingBoxGizmo
  103235. * @param gizmoLayer The utility layer the gizmo will be added to
  103236. * @param color The color of the gizmo
  103237. */
  103238. function BoundingBoxGizmo(color, gizmoLayer) {
  103239. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  103240. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultKeepDepthUtilityLayer; }
  103241. var _this = _super.call(this, gizmoLayer) || this;
  103242. _this._boundingDimensions = new BABYLON.Vector3(1, 1, 1);
  103243. _this._renderObserver = null;
  103244. _this._pointerObserver = null;
  103245. _this._scaleDragSpeed = 0.2;
  103246. _this._tmpQuaternion = new BABYLON.Quaternion();
  103247. _this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  103248. _this._tmpRotationMatrix = new BABYLON.Matrix();
  103249. /**
  103250. * 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)
  103251. */
  103252. _this.ignoreChildren = false;
  103253. /**
  103254. * 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)
  103255. */
  103256. _this.includeChildPredicate = null;
  103257. /**
  103258. * The size of the rotation spheres attached to the bounding box (Default: 0.1)
  103259. */
  103260. _this.rotationSphereSize = 0.1;
  103261. /**
  103262. * The size of the scale boxes attached to the bounding box (Default: 0.1)
  103263. */
  103264. _this.scaleBoxSize = 0.1;
  103265. /**
  103266. * 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)
  103267. */
  103268. _this.fixedDragMeshScreenSize = false;
  103269. /**
  103270. * The distance away from the object which the draggable meshes should appear world sized when fixedDragMeshScreenSize is set to true (default: 10)
  103271. */
  103272. _this.fixedDragMeshScreenSizeDistanceFactor = 10;
  103273. /**
  103274. * Fired when a rotation sphere or scale box is dragged
  103275. */
  103276. _this.onDragStartObservable = new BABYLON.Observable();
  103277. /**
  103278. * Fired when a scale box is dragged
  103279. */
  103280. _this.onScaleBoxDragObservable = new BABYLON.Observable();
  103281. /**
  103282. * Fired when a scale box drag is ended
  103283. */
  103284. _this.onScaleBoxDragEndObservable = new BABYLON.Observable();
  103285. /**
  103286. * Fired when a rotation sphere is dragged
  103287. */
  103288. _this.onRotationSphereDragObservable = new BABYLON.Observable();
  103289. /**
  103290. * Fired when a rotation sphere drag is ended
  103291. */
  103292. _this.onRotationSphereDragEndObservable = new BABYLON.Observable();
  103293. /**
  103294. * 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)
  103295. */
  103296. _this.scalePivot = null;
  103297. _this._existingMeshScale = new BABYLON.Vector3();
  103298. // Do not update the gizmo's scale so it has a fixed size to the object its attached to
  103299. _this._updateScale = false;
  103300. _this._anchorMesh = new BABYLON.AbstractMesh("anchor", gizmoLayer.utilityLayerScene);
  103301. // Create Materials
  103302. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  103303. coloredMaterial.disableLighting = true;
  103304. coloredMaterial.emissiveColor = color;
  103305. var hoverColoredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  103306. hoverColoredMaterial.disableLighting = true;
  103307. hoverColoredMaterial.emissiveColor = color.clone().add(new BABYLON.Color3(0.3, 0.3, 0.3));
  103308. // Build bounding box out of lines
  103309. _this._lineBoundingBox = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  103310. _this._lineBoundingBox.rotationQuaternion = new BABYLON.Quaternion();
  103311. var lines = [];
  103312. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0)] }, gizmoLayer.utilityLayerScene));
  103313. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  103314. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  103315. 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));
  103316. 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));
  103317. 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));
  103318. 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));
  103319. 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));
  103320. 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));
  103321. 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));
  103322. 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));
  103323. 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));
  103324. lines.forEach(function (l) {
  103325. l.color = color;
  103326. l.position.addInPlace(new BABYLON.Vector3(-_this._boundingDimensions.x / 2, -_this._boundingDimensions.y / 2, -_this._boundingDimensions.z / 2));
  103327. l.isPickable = false;
  103328. _this._lineBoundingBox.addChild(l);
  103329. });
  103330. _this._rootMesh.addChild(_this._lineBoundingBox);
  103331. // Create rotation spheres
  103332. _this._rotateSpheresParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  103333. _this._rotateSpheresParent.rotationQuaternion = new BABYLON.Quaternion();
  103334. var _loop_1 = function (i_1) {
  103335. var sphere = BABYLON.MeshBuilder.CreateSphere("", { diameter: 1 }, gizmoLayer.utilityLayerScene);
  103336. sphere.rotationQuaternion = new BABYLON.Quaternion();
  103337. sphere.material = coloredMaterial;
  103338. // Drag behavior
  103339. _dragBehavior = new BABYLON.PointerDragBehavior({});
  103340. _dragBehavior.moveAttached = false;
  103341. _dragBehavior.updateDragPlane = false;
  103342. sphere.addBehavior(_dragBehavior);
  103343. var startingTurnDirection = new BABYLON.Vector3(1, 0, 0);
  103344. var totalTurnAmountOfDrag = 0;
  103345. _dragBehavior.onDragStartObservable.add(function (event) {
  103346. startingTurnDirection.copyFrom(sphere.forward);
  103347. totalTurnAmountOfDrag = 0;
  103348. });
  103349. _dragBehavior.onDragObservable.add(function (event) {
  103350. _this.onRotationSphereDragObservable.notifyObservers({});
  103351. if (_this.attachedMesh) {
  103352. BoundingBoxGizmo._RemoveAndStorePivotPoint(_this.attachedMesh);
  103353. var worldDragDirection = startingTurnDirection;
  103354. // Project the world right on to the drag plane
  103355. var toSub = event.dragPlaneNormal.scale(BABYLON.Vector3.Dot(event.dragPlaneNormal, worldDragDirection));
  103356. var dragAxis = worldDragDirection.subtract(toSub).normalizeToNew();
  103357. // project drag delta on to the resulting drag axis and rotate based on that
  103358. var projectDist = BABYLON.Vector3.Dot(dragAxis, event.delta) < 0 ? Math.abs(event.delta.length()) : -Math.abs(event.delta.length());
  103359. // Make rotation relative to size of mesh.
  103360. projectDist = (projectDist / _this._boundingDimensions.length()) * _this._anchorMesh.scaling.length();
  103361. // Rotate based on axis
  103362. if (!_this.attachedMesh.rotationQuaternion) {
  103363. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  103364. }
  103365. if (!_this._anchorMesh.rotationQuaternion) {
  103366. _this._anchorMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._anchorMesh.rotation.y, _this._anchorMesh.rotation.x, _this._anchorMesh.rotation.z);
  103367. }
  103368. // Do not allow the object to turn more than a full circle
  103369. totalTurnAmountOfDrag += projectDist;
  103370. if (Math.abs(totalTurnAmountOfDrag) <= 2 * Math.PI) {
  103371. if (i_1 >= 8) {
  103372. BABYLON.Quaternion.RotationYawPitchRollToRef(0, 0, projectDist, _this._tmpQuaternion);
  103373. }
  103374. else if (i_1 >= 4) {
  103375. BABYLON.Quaternion.RotationYawPitchRollToRef(projectDist, 0, 0, _this._tmpQuaternion);
  103376. }
  103377. else {
  103378. BABYLON.Quaternion.RotationYawPitchRollToRef(0, projectDist, 0, _this._tmpQuaternion);
  103379. }
  103380. // Rotate around center of bounding box
  103381. _this._anchorMesh.addChild(_this.attachedMesh);
  103382. _this._anchorMesh.rotationQuaternion.multiplyToRef(_this._tmpQuaternion, _this._anchorMesh.rotationQuaternion);
  103383. _this._anchorMesh.removeChild(_this.attachedMesh);
  103384. }
  103385. _this.updateBoundingBox();
  103386. BoundingBoxGizmo._RestorePivotPoint(_this.attachedMesh);
  103387. }
  103388. });
  103389. // Selection/deselection
  103390. _dragBehavior.onDragStartObservable.add(function () {
  103391. _this.onDragStartObservable.notifyObservers({});
  103392. _this._selectNode(sphere);
  103393. });
  103394. _dragBehavior.onDragEndObservable.add(function () {
  103395. _this.onRotationSphereDragEndObservable.notifyObservers({});
  103396. _this._selectNode(null);
  103397. });
  103398. this_1._rotateSpheresParent.addChild(sphere);
  103399. };
  103400. var this_1 = this, _dragBehavior;
  103401. for (var i_1 = 0; i_1 < 12; i_1++) {
  103402. _loop_1(i_1);
  103403. }
  103404. _this._rootMesh.addChild(_this._rotateSpheresParent);
  103405. // Create scale cubes
  103406. _this._scaleBoxesParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  103407. _this._scaleBoxesParent.rotationQuaternion = new BABYLON.Quaternion();
  103408. for (var i = 0; i < 2; i++) {
  103409. for (var j = 0; j < 2; j++) {
  103410. var _loop_2 = function () {
  103411. var box = BABYLON.MeshBuilder.CreateBox("", { size: 1 }, gizmoLayer.utilityLayerScene);
  103412. box.material = coloredMaterial;
  103413. // Dragging logic
  103414. var dragAxis = new BABYLON.Vector3(i == 0 ? -1 : 1, j == 0 ? -1 : 1, k == 0 ? -1 : 1);
  103415. _dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  103416. _dragBehavior.moveAttached = false;
  103417. box.addBehavior(_dragBehavior);
  103418. _dragBehavior.onDragObservable.add(function (event) {
  103419. _this.onScaleBoxDragObservable.notifyObservers({});
  103420. if (_this.attachedMesh) {
  103421. BoundingBoxGizmo._RemoveAndStorePivotPoint(_this.attachedMesh);
  103422. var relativeDragDistance = (event.dragDistance / _this._boundingDimensions.length()) * _this._anchorMesh.scaling.length();
  103423. var deltaScale = new BABYLON.Vector3(relativeDragDistance, relativeDragDistance, relativeDragDistance);
  103424. deltaScale.scaleInPlace(_this._scaleDragSpeed);
  103425. _this.updateBoundingBox();
  103426. if (_this.scalePivot) {
  103427. _this.attachedMesh.getWorldMatrix().getRotationMatrixToRef(_this._tmpRotationMatrix);
  103428. // Move anchor to desired pivot point (Bottom left corner + dimension/2)
  103429. _this._boundingDimensions.scaleToRef(0.5, _this._tmpVector);
  103430. BABYLON.Vector3.TransformCoordinatesToRef(_this._tmpVector, _this._tmpRotationMatrix, _this._tmpVector);
  103431. _this._anchorMesh.position.subtractInPlace(_this._tmpVector);
  103432. _this._boundingDimensions.multiplyToRef(_this.scalePivot, _this._tmpVector);
  103433. BABYLON.Vector3.TransformCoordinatesToRef(_this._tmpVector, _this._tmpRotationMatrix, _this._tmpVector);
  103434. _this._anchorMesh.position.addInPlace(_this._tmpVector);
  103435. }
  103436. else {
  103437. // Scale from the position of the opposite corner
  103438. box.absolutePosition.subtractToRef(_this._anchorMesh.position, _this._tmpVector);
  103439. _this._anchorMesh.position.subtractInPlace(_this._tmpVector);
  103440. }
  103441. _this._anchorMesh.addChild(_this.attachedMesh);
  103442. _this._anchorMesh.scaling.addInPlace(deltaScale);
  103443. if (_this._anchorMesh.scaling.x < 0 || _this._anchorMesh.scaling.y < 0 || _this._anchorMesh.scaling.z < 0) {
  103444. _this._anchorMesh.scaling.subtractInPlace(deltaScale);
  103445. }
  103446. _this._anchorMesh.removeChild(_this.attachedMesh);
  103447. BoundingBoxGizmo._RestorePivotPoint(_this.attachedMesh);
  103448. }
  103449. });
  103450. // Selection/deselection
  103451. _dragBehavior.onDragStartObservable.add(function () {
  103452. _this.onDragStartObservable.notifyObservers({});
  103453. _this._selectNode(box);
  103454. });
  103455. _dragBehavior.onDragEndObservable.add(function () {
  103456. _this.onScaleBoxDragEndObservable.notifyObservers({});
  103457. _this._selectNode(null);
  103458. });
  103459. this_2._scaleBoxesParent.addChild(box);
  103460. };
  103461. var this_2 = this, _dragBehavior;
  103462. for (var k = 0; k < 2; k++) {
  103463. _loop_2();
  103464. }
  103465. }
  103466. }
  103467. _this._rootMesh.addChild(_this._scaleBoxesParent);
  103468. // Hover color change
  103469. var pointerIds = new Array();
  103470. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  103471. if (!pointerIds[pointerInfo.event.pointerId]) {
  103472. _this._rotateSpheresParent.getChildMeshes().concat(_this._scaleBoxesParent.getChildMeshes()).forEach(function (mesh) {
  103473. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh == mesh) {
  103474. pointerIds[pointerInfo.event.pointerId] = mesh;
  103475. mesh.material = hoverColoredMaterial;
  103476. }
  103477. });
  103478. }
  103479. else {
  103480. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh != pointerIds[pointerInfo.event.pointerId]) {
  103481. pointerIds[pointerInfo.event.pointerId].material = coloredMaterial;
  103482. delete pointerIds[pointerInfo.event.pointerId];
  103483. }
  103484. }
  103485. });
  103486. // Update bounding box positions
  103487. _this._renderObserver = _this.gizmoLayer.originalScene.onBeforeRenderObservable.add(function () {
  103488. // Only update the bouding box if scaling has changed
  103489. if (_this.attachedMesh && !_this._existingMeshScale.equals(_this.attachedMesh.scaling)) {
  103490. _this.updateBoundingBox();
  103491. }
  103492. else if (_this.fixedDragMeshScreenSize) {
  103493. _this._updateRotationSpheres();
  103494. _this._updateScaleBoxes();
  103495. }
  103496. });
  103497. _this.updateBoundingBox();
  103498. return _this;
  103499. }
  103500. /** @hidden */
  103501. BoundingBoxGizmo._RemoveAndStorePivotPoint = function (mesh) {
  103502. if (mesh && BoundingBoxGizmo._PivotCached === 0) {
  103503. // Save old pivot and set pivot to 0,0,0
  103504. mesh.getPivotPointToRef(BoundingBoxGizmo._OldPivotPoint);
  103505. if (!BoundingBoxGizmo._OldPivotPoint.equalsToFloats(0, 0, 0)) {
  103506. mesh.setPivotMatrix(BABYLON.Matrix.IdentityReadOnly);
  103507. BoundingBoxGizmo._OldPivotPoint.subtractToRef(mesh.getPivotPoint(), BoundingBoxGizmo._PivotTranslation);
  103508. BoundingBoxGizmo._PivotTmpVector.copyFromFloats(1, 1, 1);
  103509. BoundingBoxGizmo._PivotTmpVector.subtractInPlace(mesh.scaling);
  103510. BoundingBoxGizmo._PivotTmpVector.multiplyInPlace(BoundingBoxGizmo._PivotTranslation);
  103511. mesh.position.addInPlace(BoundingBoxGizmo._PivotTmpVector);
  103512. }
  103513. }
  103514. BoundingBoxGizmo._PivotCached++;
  103515. };
  103516. /** @hidden */
  103517. BoundingBoxGizmo._RestorePivotPoint = function (mesh) {
  103518. if (mesh && !BoundingBoxGizmo._OldPivotPoint.equalsToFloats(0, 0, 0) && BoundingBoxGizmo._PivotCached === 1) {
  103519. mesh.setPivotPoint(BoundingBoxGizmo._OldPivotPoint);
  103520. BoundingBoxGizmo._PivotTmpVector.copyFromFloats(1, 1, 1);
  103521. BoundingBoxGizmo._PivotTmpVector.subtractInPlace(mesh.scaling);
  103522. BoundingBoxGizmo._PivotTmpVector.multiplyInPlace(BoundingBoxGizmo._PivotTranslation);
  103523. mesh.position.subtractInPlace(BoundingBoxGizmo._PivotTmpVector);
  103524. }
  103525. this._PivotCached--;
  103526. };
  103527. BoundingBoxGizmo.prototype._attachedMeshChanged = function (value) {
  103528. if (value) {
  103529. // Reset anchor mesh to match attached mesh's scale
  103530. // This is needed to avoid invalid box/sphere position on first drag
  103531. BoundingBoxGizmo._RemoveAndStorePivotPoint(value);
  103532. this._anchorMesh.addChild(value);
  103533. this._anchorMesh.removeChild(value);
  103534. BoundingBoxGizmo._RestorePivotPoint(value);
  103535. this.updateBoundingBox();
  103536. }
  103537. };
  103538. BoundingBoxGizmo.prototype._selectNode = function (selectedMesh) {
  103539. this._rotateSpheresParent.getChildMeshes()
  103540. .concat(this._scaleBoxesParent.getChildMeshes()).forEach(function (m, i) {
  103541. m.isVisible = (!selectedMesh || m == selectedMesh);
  103542. });
  103543. };
  103544. /**
  103545. * Updates the bounding box information for the Gizmo
  103546. */
  103547. BoundingBoxGizmo.prototype.updateBoundingBox = function () {
  103548. if (this.attachedMesh) {
  103549. BoundingBoxGizmo._RemoveAndStorePivotPoint(this.attachedMesh);
  103550. this._update();
  103551. // Rotate based on axis
  103552. if (!this.attachedMesh.rotationQuaternion) {
  103553. this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.attachedMesh.rotation.y, this.attachedMesh.rotation.x, this.attachedMesh.rotation.z);
  103554. }
  103555. if (!this._anchorMesh.rotationQuaternion) {
  103556. this._anchorMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this._anchorMesh.rotation.y, this._anchorMesh.rotation.x, this._anchorMesh.rotation.z);
  103557. }
  103558. this._anchorMesh.rotationQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  103559. // Store original position and reset mesh to origin before computing the bounding box
  103560. this._tmpQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  103561. this._tmpVector.copyFrom(this.attachedMesh.position);
  103562. this.attachedMesh.rotationQuaternion.set(0, 0, 0, 1);
  103563. this.attachedMesh.position.set(0, 0, 0);
  103564. // Update bounding dimensions/positions
  103565. var boundingMinMax = this.attachedMesh.getHierarchyBoundingVectors(!this.ignoreChildren, this.includeChildPredicate);
  103566. boundingMinMax.max.subtractToRef(boundingMinMax.min, this._boundingDimensions);
  103567. // Update gizmo to match bounding box scaling and rotation
  103568. this._lineBoundingBox.scaling.copyFrom(this._boundingDimensions);
  103569. 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);
  103570. this._rotateSpheresParent.position.copyFrom(this._lineBoundingBox.position);
  103571. this._scaleBoxesParent.position.copyFrom(this._lineBoundingBox.position);
  103572. this._lineBoundingBox.computeWorldMatrix();
  103573. this._anchorMesh.position.copyFrom(this._lineBoundingBox.absolutePosition);
  103574. // restore position/rotation values
  103575. this.attachedMesh.rotationQuaternion.copyFrom(this._tmpQuaternion);
  103576. this.attachedMesh.position.copyFrom(this._tmpVector);
  103577. }
  103578. this._updateRotationSpheres();
  103579. this._updateScaleBoxes();
  103580. if (this.attachedMesh) {
  103581. this._existingMeshScale.copyFrom(this.attachedMesh.scaling);
  103582. BoundingBoxGizmo._RestorePivotPoint(this.attachedMesh);
  103583. }
  103584. };
  103585. BoundingBoxGizmo.prototype._updateRotationSpheres = function () {
  103586. var rotateSpheres = this._rotateSpheresParent.getChildMeshes();
  103587. for (var i = 0; i < 3; i++) {
  103588. for (var j = 0; j < 2; j++) {
  103589. for (var k = 0; k < 2; k++) {
  103590. var index = ((i * 4) + (j * 2)) + k;
  103591. if (i == 0) {
  103592. rotateSpheres[index].position.set(this._boundingDimensions.x / 2, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  103593. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  103594. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Right(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  103595. }
  103596. if (i == 1) {
  103597. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y / 2, this._boundingDimensions.z * k);
  103598. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  103599. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Up(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  103600. }
  103601. if (i == 2) {
  103602. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y * k, this._boundingDimensions.z / 2);
  103603. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  103604. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Forward(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  103605. }
  103606. if (this.fixedDragMeshScreenSize) {
  103607. rotateSpheres[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  103608. var distanceFromCamera = this.rotationSphereSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  103609. rotateSpheres[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  103610. }
  103611. else {
  103612. rotateSpheres[index].scaling.set(this.rotationSphereSize, this.rotationSphereSize, this.rotationSphereSize);
  103613. }
  103614. }
  103615. }
  103616. }
  103617. };
  103618. BoundingBoxGizmo.prototype._updateScaleBoxes = function () {
  103619. var scaleBoxes = this._scaleBoxesParent.getChildMeshes();
  103620. for (var i = 0; i < 2; i++) {
  103621. for (var j = 0; j < 2; j++) {
  103622. for (var k = 0; k < 2; k++) {
  103623. var index = ((i * 4) + (j * 2)) + k;
  103624. if (scaleBoxes[index]) {
  103625. scaleBoxes[index].position.set(this._boundingDimensions.x * i, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  103626. scaleBoxes[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  103627. if (this.fixedDragMeshScreenSize) {
  103628. scaleBoxes[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  103629. var distanceFromCamera = this.scaleBoxSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  103630. scaleBoxes[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  103631. }
  103632. else {
  103633. scaleBoxes[index].scaling.set(this.scaleBoxSize, this.scaleBoxSize, this.scaleBoxSize);
  103634. }
  103635. }
  103636. }
  103637. }
  103638. }
  103639. };
  103640. /**
  103641. * Enables rotation on the specified axis and disables rotation on the others
  103642. * @param axis The list of axis that should be enabled (eg. "xy" or "xyz")
  103643. */
  103644. BoundingBoxGizmo.prototype.setEnabledRotationAxis = function (axis) {
  103645. this._rotateSpheresParent.getChildMeshes().forEach(function (m, i) {
  103646. if (i < 4) {
  103647. m.setEnabled(axis.indexOf("x") != -1);
  103648. }
  103649. else if (i < 8) {
  103650. m.setEnabled(axis.indexOf("y") != -1);
  103651. }
  103652. else {
  103653. m.setEnabled(axis.indexOf("z") != -1);
  103654. }
  103655. });
  103656. };
  103657. /**
  103658. * Disposes of the gizmo
  103659. */
  103660. BoundingBoxGizmo.prototype.dispose = function () {
  103661. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  103662. this.gizmoLayer.originalScene.onBeforeRenderObservable.remove(this._renderObserver);
  103663. this._lineBoundingBox.dispose();
  103664. this._rotateSpheresParent.dispose();
  103665. this._scaleBoxesParent.dispose();
  103666. _super.prototype.dispose.call(this);
  103667. };
  103668. /**
  103669. * 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)
  103670. * @param mesh the mesh to wrap in the bounding box mesh and make not pickable
  103671. * @returns the bounding box mesh with the passed in mesh as a child
  103672. */
  103673. BoundingBoxGizmo.MakeNotPickableAndWrapInBoundingBox = function (mesh) {
  103674. var makeNotPickable = function (root) {
  103675. root.isPickable = false;
  103676. root.getChildMeshes().forEach(function (c) {
  103677. makeNotPickable(c);
  103678. });
  103679. };
  103680. makeNotPickable(mesh);
  103681. // Reset position to get boudning box from origin with no rotation
  103682. if (!mesh.rotationQuaternion) {
  103683. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  103684. }
  103685. var oldPos = mesh.position.clone();
  103686. var oldRot = mesh.rotationQuaternion.clone();
  103687. mesh.rotationQuaternion.set(0, 0, 0, 1);
  103688. mesh.position.set(0, 0, 0);
  103689. // Update bounding dimensions/positions
  103690. var box = BABYLON.MeshBuilder.CreateBox("box", { size: 1 }, mesh.getScene());
  103691. var boundingMinMax = mesh.getHierarchyBoundingVectors();
  103692. boundingMinMax.max.subtractToRef(boundingMinMax.min, box.scaling);
  103693. box.position.set((boundingMinMax.max.x + boundingMinMax.min.x) / 2, (boundingMinMax.max.y + boundingMinMax.min.y) / 2, (boundingMinMax.max.z + boundingMinMax.min.z) / 2);
  103694. // Restore original positions
  103695. mesh.addChild(box);
  103696. mesh.rotationQuaternion.copyFrom(oldRot);
  103697. mesh.position.copyFrom(oldPos);
  103698. // Reverse parenting
  103699. mesh.removeChild(box);
  103700. box.addChild(mesh);
  103701. box.visibility = 0;
  103702. return box;
  103703. };
  103704. /**
  103705. * CustomMeshes are not supported by this gizmo
  103706. * @param mesh The mesh to replace the default mesh of the gizmo
  103707. */
  103708. BoundingBoxGizmo.prototype.setCustomMesh = function (mesh) {
  103709. BABYLON.Tools.Error("Custom meshes are not supported on this gizmo");
  103710. };
  103711. // Stores the state of the pivot cache (_oldPivotPoint, _pivotTranslation)
  103712. // store/remove pivot point should only be applied during their outermost calls
  103713. BoundingBoxGizmo._PivotCached = 0;
  103714. BoundingBoxGizmo._OldPivotPoint = new BABYLON.Vector3();
  103715. BoundingBoxGizmo._PivotTranslation = new BABYLON.Vector3();
  103716. BoundingBoxGizmo._PivotTmpVector = new BABYLON.Vector3();
  103717. return BoundingBoxGizmo;
  103718. }(BABYLON.Gizmo));
  103719. BABYLON.BoundingBoxGizmo = BoundingBoxGizmo;
  103720. })(BABYLON || (BABYLON = {}));
  103721. //# sourceMappingURL=babylon.boundingBoxGizmo.js.map
  103722. var BABYLON;
  103723. (function (BABYLON) {
  103724. /**
  103725. * Helps setup gizmo's in the scene to rotate/scale/position meshes
  103726. */
  103727. var GizmoManager = /** @class */ (function () {
  103728. /**
  103729. * Instatiates a gizmo manager
  103730. * @param scene the scene to overlay the gizmos on top of
  103731. */
  103732. function GizmoManager(scene) {
  103733. var _this = this;
  103734. this.scene = scene;
  103735. this._gizmosEnabled = { positionGizmo: false, rotationGizmo: false, scaleGizmo: false, boundingBoxGizmo: false };
  103736. this._pointerObserver = null;
  103737. this._attachedMesh = null;
  103738. this._boundingBoxColor = BABYLON.Color3.FromHexString("#0984e3");
  103739. /**
  103740. * When bounding box gizmo is enabled, this can be used to track drag/end events
  103741. */
  103742. this.boundingBoxDragBehavior = new BABYLON.SixDofDragBehavior();
  103743. /**
  103744. * Array of meshes which will have the gizmo attached when a pointer selected them. If null, all meshes are attachable. (Default: null)
  103745. */
  103746. this.attachableMeshes = null;
  103747. /**
  103748. * If pointer events should perform attaching/detaching a gizmo, if false this can be done manually via attachToMesh. (Default: true)
  103749. */
  103750. this.usePointerToAttachGizmos = true;
  103751. this._defaultKeepDepthUtilityLayer = new BABYLON.UtilityLayerRenderer(scene);
  103752. this._defaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil = false;
  103753. this._defaultUtilityLayer = new BABYLON.UtilityLayerRenderer(scene);
  103754. this.gizmos = { positionGizmo: null, rotationGizmo: null, scaleGizmo: null, boundingBoxGizmo: null };
  103755. // Instatiate/dispose gizmos based on pointer actions
  103756. this._pointerObserver = scene.onPointerObservable.add(function (pointerInfo, state) {
  103757. if (!_this.usePointerToAttachGizmos) {
  103758. return;
  103759. }
  103760. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  103761. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh) {
  103762. var node = pointerInfo.pickInfo.pickedMesh;
  103763. if (_this.attachableMeshes == null) {
  103764. // Attach to the most parent node
  103765. while (node && node.parent != null) {
  103766. node = node.parent;
  103767. }
  103768. }
  103769. else {
  103770. // Attach to the parent node that is an attachableMesh
  103771. var found = false;
  103772. _this.attachableMeshes.forEach(function (mesh) {
  103773. if (node && (node == mesh || node.isDescendantOf(mesh))) {
  103774. node = mesh;
  103775. found = true;
  103776. }
  103777. });
  103778. if (!found) {
  103779. node = null;
  103780. }
  103781. }
  103782. if (node instanceof BABYLON.AbstractMesh) {
  103783. if (_this._attachedMesh != node) {
  103784. _this.attachToMesh(node);
  103785. }
  103786. }
  103787. else {
  103788. _this.attachToMesh(null);
  103789. }
  103790. }
  103791. else {
  103792. _this.attachToMesh(null);
  103793. }
  103794. }
  103795. });
  103796. }
  103797. /**
  103798. * Attaches a set of gizmos to the specified mesh
  103799. * @param mesh The mesh the gizmo's should be attached to
  103800. */
  103801. GizmoManager.prototype.attachToMesh = function (mesh) {
  103802. if (this._attachedMesh) {
  103803. this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior);
  103804. }
  103805. this._attachedMesh = mesh;
  103806. for (var key in this.gizmos) {
  103807. var gizmo = (this.gizmos[key]);
  103808. if (gizmo && this._gizmosEnabled[key]) {
  103809. gizmo.attachedMesh = mesh;
  103810. }
  103811. }
  103812. if (this.boundingBoxGizmoEnabled && this._attachedMesh) {
  103813. this._attachedMesh.addBehavior(this.boundingBoxDragBehavior);
  103814. }
  103815. };
  103816. Object.defineProperty(GizmoManager.prototype, "positionGizmoEnabled", {
  103817. get: function () {
  103818. return this._gizmosEnabled.positionGizmo;
  103819. },
  103820. /**
  103821. * If the position gizmo is enabled
  103822. */
  103823. set: function (value) {
  103824. if (value) {
  103825. if (!this.gizmos.positionGizmo) {
  103826. this.gizmos.positionGizmo = new BABYLON.PositionGizmo(this._defaultUtilityLayer);
  103827. }
  103828. this.gizmos.positionGizmo.attachedMesh = this._attachedMesh;
  103829. }
  103830. else if (this.gizmos.positionGizmo) {
  103831. this.gizmos.positionGizmo.attachedMesh = null;
  103832. }
  103833. this._gizmosEnabled.positionGizmo = value;
  103834. },
  103835. enumerable: true,
  103836. configurable: true
  103837. });
  103838. Object.defineProperty(GizmoManager.prototype, "rotationGizmoEnabled", {
  103839. get: function () {
  103840. return this._gizmosEnabled.rotationGizmo;
  103841. },
  103842. /**
  103843. * If the rotation gizmo is enabled
  103844. */
  103845. set: function (value) {
  103846. if (value) {
  103847. if (!this.gizmos.rotationGizmo) {
  103848. this.gizmos.rotationGizmo = new BABYLON.RotationGizmo(this._defaultUtilityLayer);
  103849. }
  103850. this.gizmos.rotationGizmo.attachedMesh = this._attachedMesh;
  103851. }
  103852. else if (this.gizmos.rotationGizmo) {
  103853. this.gizmos.rotationGizmo.attachedMesh = null;
  103854. }
  103855. this._gizmosEnabled.rotationGizmo = value;
  103856. },
  103857. enumerable: true,
  103858. configurable: true
  103859. });
  103860. Object.defineProperty(GizmoManager.prototype, "scaleGizmoEnabled", {
  103861. get: function () {
  103862. return this._gizmosEnabled.scaleGizmo;
  103863. },
  103864. /**
  103865. * If the scale gizmo is enabled
  103866. */
  103867. set: function (value) {
  103868. if (value) {
  103869. this.gizmos.scaleGizmo = this.gizmos.scaleGizmo || new BABYLON.ScaleGizmo(this._defaultUtilityLayer);
  103870. this.gizmos.scaleGizmo.attachedMesh = this._attachedMesh;
  103871. }
  103872. else if (this.gizmos.scaleGizmo) {
  103873. this.gizmos.scaleGizmo.attachedMesh = null;
  103874. }
  103875. this._gizmosEnabled.scaleGizmo = value;
  103876. },
  103877. enumerable: true,
  103878. configurable: true
  103879. });
  103880. Object.defineProperty(GizmoManager.prototype, "boundingBoxGizmoEnabled", {
  103881. get: function () {
  103882. return this._gizmosEnabled.boundingBoxGizmo;
  103883. },
  103884. /**
  103885. * If the boundingBox gizmo is enabled
  103886. */
  103887. set: function (value) {
  103888. if (value) {
  103889. this.gizmos.boundingBoxGizmo = this.gizmos.boundingBoxGizmo || new BABYLON.BoundingBoxGizmo(this._boundingBoxColor, this._defaultKeepDepthUtilityLayer);
  103890. this.gizmos.boundingBoxGizmo.attachedMesh = this._attachedMesh;
  103891. if (this._attachedMesh) {
  103892. this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior);
  103893. this._attachedMesh.addBehavior(this.boundingBoxDragBehavior);
  103894. }
  103895. }
  103896. else if (this.gizmos.boundingBoxGizmo) {
  103897. this.gizmos.boundingBoxGizmo.attachedMesh = null;
  103898. }
  103899. this._gizmosEnabled.boundingBoxGizmo = value;
  103900. },
  103901. enumerable: true,
  103902. configurable: true
  103903. });
  103904. /**
  103905. * Disposes of the gizmo manager
  103906. */
  103907. GizmoManager.prototype.dispose = function () {
  103908. this.scene.onPointerObservable.remove(this._pointerObserver);
  103909. for (var key in this.gizmos) {
  103910. var gizmo = (this.gizmos[key]);
  103911. if (gizmo) {
  103912. gizmo.dispose();
  103913. }
  103914. }
  103915. this._defaultKeepDepthUtilityLayer.dispose();
  103916. this._defaultUtilityLayer.dispose();
  103917. this.boundingBoxDragBehavior.detach();
  103918. };
  103919. return GizmoManager;
  103920. }());
  103921. BABYLON.GizmoManager = GizmoManager;
  103922. })(BABYLON || (BABYLON = {}));
  103923. //# sourceMappingURL=babylon.gizmoManager.js.map
  103924. var BABYLON;
  103925. (function (BABYLON) {
  103926. /**
  103927. * Defines a target to use with MorphTargetManager
  103928. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  103929. */
  103930. var MorphTarget = /** @class */ (function () {
  103931. /**
  103932. * Creates a new MorphTarget
  103933. * @param name defines the name of the target
  103934. * @param influence defines the influence to use
  103935. */
  103936. function MorphTarget(
  103937. /** defines the name of the target */
  103938. name, influence, scene) {
  103939. if (influence === void 0) { influence = 0; }
  103940. if (scene === void 0) { scene = null; }
  103941. this.name = name;
  103942. /**
  103943. * Gets or sets the list of animations
  103944. */
  103945. this.animations = new Array();
  103946. this._positions = null;
  103947. this._normals = null;
  103948. this._tangents = null;
  103949. /**
  103950. * Observable raised when the influence changes
  103951. */
  103952. this.onInfluenceChanged = new BABYLON.Observable();
  103953. /** @hidden */
  103954. this._onDataLayoutChanged = new BABYLON.Observable();
  103955. this._animationPropertiesOverride = null;
  103956. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  103957. this.influence = influence;
  103958. }
  103959. Object.defineProperty(MorphTarget.prototype, "influence", {
  103960. /**
  103961. * Gets or sets the influence of this target (ie. its weight in the overall morphing)
  103962. */
  103963. get: function () {
  103964. return this._influence;
  103965. },
  103966. set: function (influence) {
  103967. if (this._influence === influence) {
  103968. return;
  103969. }
  103970. var previous = this._influence;
  103971. this._influence = influence;
  103972. if (this.onInfluenceChanged.hasObservers) {
  103973. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  103974. }
  103975. },
  103976. enumerable: true,
  103977. configurable: true
  103978. });
  103979. Object.defineProperty(MorphTarget.prototype, "animationPropertiesOverride", {
  103980. /**
  103981. * Gets or sets the animation properties override
  103982. */
  103983. get: function () {
  103984. if (!this._animationPropertiesOverride && this._scene) {
  103985. return this._scene.animationPropertiesOverride;
  103986. }
  103987. return this._animationPropertiesOverride;
  103988. },
  103989. set: function (value) {
  103990. this._animationPropertiesOverride = value;
  103991. },
  103992. enumerable: true,
  103993. configurable: true
  103994. });
  103995. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  103996. /**
  103997. * Gets a boolean defining if the target contains position data
  103998. */
  103999. get: function () {
  104000. return !!this._positions;
  104001. },
  104002. enumerable: true,
  104003. configurable: true
  104004. });
  104005. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  104006. /**
  104007. * Gets a boolean defining if the target contains normal data
  104008. */
  104009. get: function () {
  104010. return !!this._normals;
  104011. },
  104012. enumerable: true,
  104013. configurable: true
  104014. });
  104015. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  104016. /**
  104017. * Gets a boolean defining if the target contains tangent data
  104018. */
  104019. get: function () {
  104020. return !!this._tangents;
  104021. },
  104022. enumerable: true,
  104023. configurable: true
  104024. });
  104025. /**
  104026. * Affects position data to this target
  104027. * @param data defines the position data to use
  104028. */
  104029. MorphTarget.prototype.setPositions = function (data) {
  104030. var hadPositions = this.hasPositions;
  104031. this._positions = data;
  104032. if (hadPositions !== this.hasPositions) {
  104033. this._onDataLayoutChanged.notifyObservers(undefined);
  104034. }
  104035. };
  104036. /**
  104037. * Gets the position data stored in this target
  104038. * @returns a FloatArray containing the position data (or null if not present)
  104039. */
  104040. MorphTarget.prototype.getPositions = function () {
  104041. return this._positions;
  104042. };
  104043. /**
  104044. * Affects normal data to this target
  104045. * @param data defines the normal data to use
  104046. */
  104047. MorphTarget.prototype.setNormals = function (data) {
  104048. var hadNormals = this.hasNormals;
  104049. this._normals = data;
  104050. if (hadNormals !== this.hasNormals) {
  104051. this._onDataLayoutChanged.notifyObservers(undefined);
  104052. }
  104053. };
  104054. /**
  104055. * Gets the normal data stored in this target
  104056. * @returns a FloatArray containing the normal data (or null if not present)
  104057. */
  104058. MorphTarget.prototype.getNormals = function () {
  104059. return this._normals;
  104060. };
  104061. /**
  104062. * Affects tangent data to this target
  104063. * @param data defines the tangent data to use
  104064. */
  104065. MorphTarget.prototype.setTangents = function (data) {
  104066. var hadTangents = this.hasTangents;
  104067. this._tangents = data;
  104068. if (hadTangents !== this.hasTangents) {
  104069. this._onDataLayoutChanged.notifyObservers(undefined);
  104070. }
  104071. };
  104072. /**
  104073. * Gets the tangent data stored in this target
  104074. * @returns a FloatArray containing the tangent data (or null if not present)
  104075. */
  104076. MorphTarget.prototype.getTangents = function () {
  104077. return this._tangents;
  104078. };
  104079. /**
  104080. * Serializes the current target into a Serialization object
  104081. * @returns the serialized object
  104082. */
  104083. MorphTarget.prototype.serialize = function () {
  104084. var serializationObject = {};
  104085. serializationObject.name = this.name;
  104086. serializationObject.influence = this.influence;
  104087. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  104088. if (this.id != null) {
  104089. serializationObject.id = this.id;
  104090. }
  104091. if (this.hasNormals) {
  104092. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  104093. }
  104094. if (this.hasTangents) {
  104095. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  104096. }
  104097. // Animations
  104098. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  104099. return serializationObject;
  104100. };
  104101. /**
  104102. * Returns the string "MorphTarget"
  104103. * @returns "MorphTarget"
  104104. */
  104105. MorphTarget.prototype.getClassName = function () {
  104106. return "MorphTarget";
  104107. };
  104108. // Statics
  104109. /**
  104110. * Creates a new target from serialized data
  104111. * @param serializationObject defines the serialized data to use
  104112. * @returns a new MorphTarget
  104113. */
  104114. MorphTarget.Parse = function (serializationObject) {
  104115. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  104116. result.setPositions(serializationObject.positions);
  104117. if (serializationObject.id != null) {
  104118. result.id = serializationObject.id;
  104119. }
  104120. if (serializationObject.normals) {
  104121. result.setNormals(serializationObject.normals);
  104122. }
  104123. if (serializationObject.tangents) {
  104124. result.setTangents(serializationObject.tangents);
  104125. }
  104126. // Animations
  104127. if (serializationObject.animations) {
  104128. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  104129. var parsedAnimation = serializationObject.animations[animationIndex];
  104130. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  104131. }
  104132. }
  104133. return result;
  104134. };
  104135. /**
  104136. * Creates a MorphTarget from mesh data
  104137. * @param mesh defines the source mesh
  104138. * @param name defines the name to use for the new target
  104139. * @param influence defines the influence to attach to the target
  104140. * @returns a new MorphTarget
  104141. */
  104142. MorphTarget.FromMesh = function (mesh, name, influence) {
  104143. if (!name) {
  104144. name = mesh.name;
  104145. }
  104146. var result = new MorphTarget(name, influence, mesh.getScene());
  104147. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  104148. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  104149. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  104150. }
  104151. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  104152. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  104153. }
  104154. return result;
  104155. };
  104156. __decorate([
  104157. BABYLON.serialize()
  104158. ], MorphTarget.prototype, "id", void 0);
  104159. return MorphTarget;
  104160. }());
  104161. BABYLON.MorphTarget = MorphTarget;
  104162. })(BABYLON || (BABYLON = {}));
  104163. //# sourceMappingURL=babylon.morphTarget.js.map
  104164. var BABYLON;
  104165. (function (BABYLON) {
  104166. /**
  104167. * This class is used to deform meshes using morphing between different targets
  104168. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  104169. */
  104170. var MorphTargetManager = /** @class */ (function () {
  104171. /**
  104172. * Creates a new MorphTargetManager
  104173. * @param scene defines the current scene
  104174. */
  104175. function MorphTargetManager(scene) {
  104176. if (scene === void 0) { scene = null; }
  104177. this._targets = new Array();
  104178. this._targetInfluenceChangedObservers = new Array();
  104179. this._targetDataLayoutChangedObservers = new Array();
  104180. this._activeTargets = new BABYLON.SmartArray(16);
  104181. this._supportsNormals = false;
  104182. this._supportsTangents = false;
  104183. this._vertexCount = 0;
  104184. this._uniqueId = 0;
  104185. this._tempInfluences = new Array();
  104186. if (!scene) {
  104187. scene = BABYLON.Engine.LastCreatedScene;
  104188. }
  104189. this._scene = scene;
  104190. if (this._scene) {
  104191. this._scene.morphTargetManagers.push(this);
  104192. this._uniqueId = this._scene.getUniqueId();
  104193. }
  104194. }
  104195. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  104196. /**
  104197. * Gets the unique ID of this manager
  104198. */
  104199. get: function () {
  104200. return this._uniqueId;
  104201. },
  104202. enumerable: true,
  104203. configurable: true
  104204. });
  104205. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  104206. /**
  104207. * Gets the number of vertices handled by this manager
  104208. */
  104209. get: function () {
  104210. return this._vertexCount;
  104211. },
  104212. enumerable: true,
  104213. configurable: true
  104214. });
  104215. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  104216. /**
  104217. * Gets a boolean indicating if this manager supports morphing of normals
  104218. */
  104219. get: function () {
  104220. return this._supportsNormals;
  104221. },
  104222. enumerable: true,
  104223. configurable: true
  104224. });
  104225. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  104226. /**
  104227. * Gets a boolean indicating if this manager supports morphing of tangents
  104228. */
  104229. get: function () {
  104230. return this._supportsTangents;
  104231. },
  104232. enumerable: true,
  104233. configurable: true
  104234. });
  104235. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  104236. /**
  104237. * Gets the number of targets stored in this manager
  104238. */
  104239. get: function () {
  104240. return this._targets.length;
  104241. },
  104242. enumerable: true,
  104243. configurable: true
  104244. });
  104245. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  104246. /**
  104247. * Gets the number of influencers (ie. the number of targets with influences > 0)
  104248. */
  104249. get: function () {
  104250. return this._activeTargets.length;
  104251. },
  104252. enumerable: true,
  104253. configurable: true
  104254. });
  104255. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  104256. /**
  104257. * Gets the list of influences (one per target)
  104258. */
  104259. get: function () {
  104260. return this._influences;
  104261. },
  104262. enumerable: true,
  104263. configurable: true
  104264. });
  104265. /**
  104266. * Gets the active target at specified index. An active target is a target with an influence > 0
  104267. * @param index defines the index to check
  104268. * @returns the requested target
  104269. */
  104270. MorphTargetManager.prototype.getActiveTarget = function (index) {
  104271. return this._activeTargets.data[index];
  104272. };
  104273. /**
  104274. * Gets the target at specified index
  104275. * @param index defines the index to check
  104276. * @returns the requested target
  104277. */
  104278. MorphTargetManager.prototype.getTarget = function (index) {
  104279. return this._targets[index];
  104280. };
  104281. /**
  104282. * Add a new target to this manager
  104283. * @param target defines the target to add
  104284. */
  104285. MorphTargetManager.prototype.addTarget = function (target) {
  104286. var _this = this;
  104287. this._targets.push(target);
  104288. this._targetInfluenceChangedObservers.push(target.onInfluenceChanged.add(function (needUpdate) {
  104289. _this._syncActiveTargets(needUpdate);
  104290. }));
  104291. this._targetDataLayoutChangedObservers.push(target._onDataLayoutChanged.add(function () {
  104292. _this._syncActiveTargets(true);
  104293. }));
  104294. this._syncActiveTargets(true);
  104295. };
  104296. /**
  104297. * Removes a target from the manager
  104298. * @param target defines the target to remove
  104299. */
  104300. MorphTargetManager.prototype.removeTarget = function (target) {
  104301. var index = this._targets.indexOf(target);
  104302. if (index >= 0) {
  104303. this._targets.splice(index, 1);
  104304. target.onInfluenceChanged.remove(this._targetInfluenceChangedObservers.splice(index, 1)[0]);
  104305. target._onDataLayoutChanged.remove(this._targetDataLayoutChangedObservers.splice(index, 1)[0]);
  104306. this._syncActiveTargets(true);
  104307. }
  104308. };
  104309. /**
  104310. * Serializes the current manager into a Serialization object
  104311. * @returns the serialized object
  104312. */
  104313. MorphTargetManager.prototype.serialize = function () {
  104314. var serializationObject = {};
  104315. serializationObject.id = this.uniqueId;
  104316. serializationObject.targets = [];
  104317. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  104318. var target = _a[_i];
  104319. serializationObject.targets.push(target.serialize());
  104320. }
  104321. return serializationObject;
  104322. };
  104323. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  104324. var influenceCount = 0;
  104325. this._activeTargets.reset();
  104326. this._supportsNormals = true;
  104327. this._supportsTangents = true;
  104328. this._vertexCount = 0;
  104329. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  104330. var target = _a[_i];
  104331. if (target.influence === 0) {
  104332. continue;
  104333. }
  104334. this._activeTargets.push(target);
  104335. this._tempInfluences[influenceCount++] = target.influence;
  104336. this._supportsNormals = this._supportsNormals && target.hasNormals;
  104337. this._supportsTangents = this._supportsTangents && target.hasTangents;
  104338. var positions = target.getPositions();
  104339. if (positions) {
  104340. var vertexCount = positions.length / 3;
  104341. if (this._vertexCount === 0) {
  104342. this._vertexCount = vertexCount;
  104343. }
  104344. else if (this._vertexCount !== vertexCount) {
  104345. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  104346. return;
  104347. }
  104348. }
  104349. }
  104350. if (!this._influences || this._influences.length !== influenceCount) {
  104351. this._influences = new Float32Array(influenceCount);
  104352. }
  104353. for (var index = 0; index < influenceCount; index++) {
  104354. this._influences[index] = this._tempInfluences[index];
  104355. }
  104356. if (needUpdate) {
  104357. this.synchronize();
  104358. }
  104359. };
  104360. /**
  104361. * Syncrhonize the targets with all the meshes using this morph target manager
  104362. */
  104363. MorphTargetManager.prototype.synchronize = function () {
  104364. if (!this._scene) {
  104365. return;
  104366. }
  104367. // Flag meshes as dirty to resync with the active targets
  104368. for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {
  104369. var mesh = _a[_i];
  104370. if (mesh.morphTargetManager === this) {
  104371. mesh._syncGeometryWithMorphTargetManager();
  104372. }
  104373. }
  104374. };
  104375. // Statics
  104376. /**
  104377. * Creates a new MorphTargetManager from serialized data
  104378. * @param serializationObject defines the serialized data
  104379. * @param scene defines the hosting scene
  104380. * @returns the new MorphTargetManager
  104381. */
  104382. MorphTargetManager.Parse = function (serializationObject, scene) {
  104383. var result = new MorphTargetManager(scene);
  104384. result._uniqueId = serializationObject.id;
  104385. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  104386. var targetData = _a[_i];
  104387. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  104388. }
  104389. return result;
  104390. };
  104391. return MorphTargetManager;
  104392. }());
  104393. BABYLON.MorphTargetManager = MorphTargetManager;
  104394. })(BABYLON || (BABYLON = {}));
  104395. //# sourceMappingURL=babylon.morphTargetManager.js.map
  104396. var BABYLON;
  104397. (function (BABYLON) {
  104398. /**
  104399. * Octrees are a really powerful data structure that can quickly select entities based on space coordinates.
  104400. * @see https://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  104401. */
  104402. var Octree = /** @class */ (function () {
  104403. /**
  104404. * Creates a octree
  104405. * @see https://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  104406. * @param creationFunc function to be used to instatiate the octree
  104407. * @param maxBlockCapacity defines the maximum number of meshes you want on your octree's leaves (default: 64)
  104408. * @param maxDepth defines the maximum depth (sub-levels) for your octree. Default value is 2, which means 8 8 8 = 512 blocks :) (This parameter takes precedence over capacity.)
  104409. */
  104410. function Octree(creationFunc, maxBlockCapacity,
  104411. /** Defines the maximum depth (sub-levels) for your octree. Default value is 2, which means 8 8 8 = 512 blocks :) (This parameter takes precedence over capacity.) */
  104412. maxDepth) {
  104413. if (maxDepth === void 0) { maxDepth = 2; }
  104414. this.maxDepth = maxDepth;
  104415. /**
  104416. * Content stored in the octree
  104417. */
  104418. this.dynamicContent = new Array();
  104419. this._maxBlockCapacity = maxBlockCapacity || 64;
  104420. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  104421. this._creationFunc = creationFunc;
  104422. }
  104423. // Methods
  104424. /**
  104425. * Updates the octree by adding blocks for the passed in meshes within the min and max world parameters
  104426. * @param worldMin worldMin for the octree blocks var blockSize = new Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  104427. * @param worldMax worldMax for the octree blocks var blockSize = new Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  104428. * @param entries meshes to be added to the octree blocks
  104429. */
  104430. Octree.prototype.update = function (worldMin, worldMax, entries) {
  104431. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  104432. };
  104433. /**
  104434. * Adds a mesh to the octree
  104435. * @param entry Mesh to add to the octree
  104436. */
  104437. Octree.prototype.addMesh = function (entry) {
  104438. for (var index = 0; index < this.blocks.length; index++) {
  104439. var block = this.blocks[index];
  104440. block.addEntry(entry);
  104441. }
  104442. };
  104443. /**
  104444. * Selects an array of meshes within the frustum
  104445. * @param frustumPlanes The frustum planes to use which will select all meshes within it
  104446. * @param allowDuplicate If duplicate objects are allowed in the resulting object array
  104447. * @returns array of meshes within the frustum
  104448. */
  104449. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  104450. this._selectionContent.reset();
  104451. for (var index = 0; index < this.blocks.length; index++) {
  104452. var block = this.blocks[index];
  104453. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  104454. }
  104455. if (allowDuplicate) {
  104456. this._selectionContent.concat(this.dynamicContent);
  104457. }
  104458. else {
  104459. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  104460. }
  104461. return this._selectionContent;
  104462. };
  104463. /**
  104464. * Test if the octree intersect with the given bounding sphere and if yes, then add its content to the selection array
  104465. * @param sphereCenter defines the bounding sphere center
  104466. * @param sphereRadius defines the bounding sphere radius
  104467. * @param allowDuplicate defines if the selection array can contains duplicated entries
  104468. * @returns an array of objects that intersect the sphere
  104469. */
  104470. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  104471. this._selectionContent.reset();
  104472. for (var index = 0; index < this.blocks.length; index++) {
  104473. var block = this.blocks[index];
  104474. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  104475. }
  104476. if (allowDuplicate) {
  104477. this._selectionContent.concat(this.dynamicContent);
  104478. }
  104479. else {
  104480. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  104481. }
  104482. return this._selectionContent;
  104483. };
  104484. /**
  104485. * Test if the octree intersect with the given ray and if yes, then add its content to resulting array
  104486. * @param ray defines the ray to test with
  104487. * @returns array of intersected objects
  104488. */
  104489. Octree.prototype.intersectsRay = function (ray) {
  104490. this._selectionContent.reset();
  104491. for (var index = 0; index < this.blocks.length; index++) {
  104492. var block = this.blocks[index];
  104493. block.intersectsRay(ray, this._selectionContent);
  104494. }
  104495. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  104496. return this._selectionContent;
  104497. };
  104498. /**
  104499. * @hidden
  104500. */
  104501. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  104502. target.blocks = new Array();
  104503. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  104504. // Segmenting space
  104505. for (var x = 0; x < 2; x++) {
  104506. for (var y = 0; y < 2; y++) {
  104507. for (var z = 0; z < 2; z++) {
  104508. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  104509. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  104510. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  104511. block.addEntries(entries);
  104512. target.blocks.push(block);
  104513. }
  104514. }
  104515. }
  104516. };
  104517. /**
  104518. * Adds a mesh into the octree block if it intersects the block
  104519. */
  104520. Octree.CreationFuncForMeshes = function (entry, block) {
  104521. var boundingInfo = entry.getBoundingInfo();
  104522. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  104523. block.entries.push(entry);
  104524. }
  104525. };
  104526. /**
  104527. * Adds a submesh into the octree block if it intersects the block
  104528. */
  104529. Octree.CreationFuncForSubMeshes = function (entry, block) {
  104530. var boundingInfo = entry.getBoundingInfo();
  104531. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  104532. block.entries.push(entry);
  104533. }
  104534. };
  104535. return Octree;
  104536. }());
  104537. BABYLON.Octree = Octree;
  104538. })(BABYLON || (BABYLON = {}));
  104539. //# sourceMappingURL=babylon.octree.js.map
  104540. var BABYLON;
  104541. (function (BABYLON) {
  104542. /**
  104543. * Class used to store a cell in an octree
  104544. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  104545. */
  104546. var OctreeBlock = /** @class */ (function () {
  104547. /**
  104548. * Creates a new block
  104549. * @param minPoint defines the minimum vector (in world space) of the block's bounding box
  104550. * @param maxPoint defines the maximum vector (in world space) of the block's bounding box
  104551. * @param capacity defines the maximum capacity of this block (if capacity is reached the block will be split into sub blocks)
  104552. * @param depth defines the current depth of this block in the octree
  104553. * @param maxDepth defines the maximal depth allowed (beyond this value, the capacity is ignored)
  104554. * @param creationFunc defines a callback to call when an element is added to the block
  104555. */
  104556. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  104557. /**
  104558. * Gets the content of the current block
  104559. */
  104560. this.entries = new Array();
  104561. this._boundingVectors = new Array();
  104562. this._capacity = capacity;
  104563. this._depth = depth;
  104564. this._maxDepth = maxDepth;
  104565. this._creationFunc = creationFunc;
  104566. this._minPoint = minPoint;
  104567. this._maxPoint = maxPoint;
  104568. this._boundingVectors.push(minPoint.clone());
  104569. this._boundingVectors.push(maxPoint.clone());
  104570. this._boundingVectors.push(minPoint.clone());
  104571. this._boundingVectors[2].x = maxPoint.x;
  104572. this._boundingVectors.push(minPoint.clone());
  104573. this._boundingVectors[3].y = maxPoint.y;
  104574. this._boundingVectors.push(minPoint.clone());
  104575. this._boundingVectors[4].z = maxPoint.z;
  104576. this._boundingVectors.push(maxPoint.clone());
  104577. this._boundingVectors[5].z = minPoint.z;
  104578. this._boundingVectors.push(maxPoint.clone());
  104579. this._boundingVectors[6].x = minPoint.x;
  104580. this._boundingVectors.push(maxPoint.clone());
  104581. this._boundingVectors[7].y = minPoint.y;
  104582. }
  104583. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  104584. // Property
  104585. /**
  104586. * Gets the maximum capacity of this block (if capacity is reached the block will be split into sub blocks)
  104587. */
  104588. get: function () {
  104589. return this._capacity;
  104590. },
  104591. enumerable: true,
  104592. configurable: true
  104593. });
  104594. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  104595. /**
  104596. * Gets the minimum vector (in world space) of the block's bounding box
  104597. */
  104598. get: function () {
  104599. return this._minPoint;
  104600. },
  104601. enumerable: true,
  104602. configurable: true
  104603. });
  104604. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  104605. /**
  104606. * Gets the maximum vector (in world space) of the block's bounding box
  104607. */
  104608. get: function () {
  104609. return this._maxPoint;
  104610. },
  104611. enumerable: true,
  104612. configurable: true
  104613. });
  104614. // Methods
  104615. /**
  104616. * Add a new element to this block
  104617. * @param entry defines the element to add
  104618. */
  104619. OctreeBlock.prototype.addEntry = function (entry) {
  104620. if (this.blocks) {
  104621. for (var index = 0; index < this.blocks.length; index++) {
  104622. var block = this.blocks[index];
  104623. block.addEntry(entry);
  104624. }
  104625. return;
  104626. }
  104627. this._creationFunc(entry, this);
  104628. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  104629. this.createInnerBlocks();
  104630. }
  104631. };
  104632. /**
  104633. * Add an array of elements to this block
  104634. * @param entries defines the array of elements to add
  104635. */
  104636. OctreeBlock.prototype.addEntries = function (entries) {
  104637. for (var index = 0; index < entries.length; index++) {
  104638. var mesh = entries[index];
  104639. this.addEntry(mesh);
  104640. }
  104641. };
  104642. /**
  104643. * Test if the current block intersects the furstum planes and if yes, then add its content to the selection array
  104644. * @param frustumPlanes defines the frustum planes to test
  104645. * @param selection defines the array to store current content if selection is positive
  104646. * @param allowDuplicate defines if the selection array can contains duplicated entries
  104647. */
  104648. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  104649. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  104650. if (this.blocks) {
  104651. for (var index = 0; index < this.blocks.length; index++) {
  104652. var block = this.blocks[index];
  104653. block.select(frustumPlanes, selection, allowDuplicate);
  104654. }
  104655. return;
  104656. }
  104657. if (allowDuplicate) {
  104658. selection.concat(this.entries);
  104659. }
  104660. else {
  104661. selection.concatWithNoDuplicate(this.entries);
  104662. }
  104663. }
  104664. };
  104665. /**
  104666. * Test if the current block intersect with the given bounding sphere and if yes, then add its content to the selection array
  104667. * @param sphereCenter defines the bounding sphere center
  104668. * @param sphereRadius defines the bounding sphere radius
  104669. * @param selection defines the array to store current content if selection is positive
  104670. * @param allowDuplicate defines if the selection array can contains duplicated entries
  104671. */
  104672. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  104673. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  104674. if (this.blocks) {
  104675. for (var index = 0; index < this.blocks.length; index++) {
  104676. var block = this.blocks[index];
  104677. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  104678. }
  104679. return;
  104680. }
  104681. if (allowDuplicate) {
  104682. selection.concat(this.entries);
  104683. }
  104684. else {
  104685. selection.concatWithNoDuplicate(this.entries);
  104686. }
  104687. }
  104688. };
  104689. /**
  104690. * Test if the current block intersect with the given ray and if yes, then add its content to the selection array
  104691. * @param ray defines the ray to test with
  104692. * @param selection defines the array to store current content if selection is positive
  104693. */
  104694. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  104695. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  104696. if (this.blocks) {
  104697. for (var index = 0; index < this.blocks.length; index++) {
  104698. var block = this.blocks[index];
  104699. block.intersectsRay(ray, selection);
  104700. }
  104701. return;
  104702. }
  104703. selection.concatWithNoDuplicate(this.entries);
  104704. }
  104705. };
  104706. /**
  104707. * Subdivide the content into child blocks (this block will then be empty)
  104708. */
  104709. OctreeBlock.prototype.createInnerBlocks = function () {
  104710. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  104711. };
  104712. return OctreeBlock;
  104713. }());
  104714. BABYLON.OctreeBlock = OctreeBlock;
  104715. })(BABYLON || (BABYLON = {}));
  104716. //# sourceMappingURL=babylon.octreeBlock.js.map
  104717. var BABYLON;
  104718. (function (BABYLON) {
  104719. BABYLON.Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  104720. if (maxCapacity === void 0) { maxCapacity = 64; }
  104721. if (maxDepth === void 0) { maxDepth = 2; }
  104722. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_OCTREE);
  104723. if (!component) {
  104724. component = new OctreeSceneComponent(this);
  104725. this._addComponent(component);
  104726. }
  104727. if (!this._selectionOctree) {
  104728. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  104729. }
  104730. var worldExtends = this.getWorldExtends();
  104731. // Update octree
  104732. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  104733. return this._selectionOctree;
  104734. };
  104735. Object.defineProperty(BABYLON.Scene.prototype, "selectionOctree", {
  104736. get: function () {
  104737. return this._selectionOctree;
  104738. },
  104739. enumerable: true,
  104740. configurable: true
  104741. });
  104742. /**
  104743. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  104744. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  104745. * @param maxCapacity defines the maximum size of each block (64 by default)
  104746. * @param maxDepth defines the maximum depth to use (no more than 2 levels by default)
  104747. * @returns the new octree
  104748. * @see https://www.babylonjs-playground.com/#NA4OQ#12
  104749. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  104750. */
  104751. BABYLON.AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  104752. if (maxCapacity === void 0) { maxCapacity = 64; }
  104753. if (maxDepth === void 0) { maxDepth = 2; }
  104754. var scene = this.getScene();
  104755. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_OCTREE);
  104756. if (!component) {
  104757. component = new OctreeSceneComponent(scene);
  104758. scene._addComponent(component);
  104759. }
  104760. if (!this._submeshesOctree) {
  104761. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  104762. }
  104763. this.computeWorldMatrix(true);
  104764. var boundingInfo = this.getBoundingInfo();
  104765. // Update octree
  104766. var bbox = boundingInfo.boundingBox;
  104767. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  104768. return this._submeshesOctree;
  104769. };
  104770. /**
  104771. * Defines the octree scene component responsible to manage any octrees
  104772. * in a given scene.
  104773. */
  104774. var OctreeSceneComponent = /** @class */ (function () {
  104775. /**
  104776. * Creates a new instance of the component for the given scene
  104777. * @param scene Defines the scene to register the component in
  104778. */
  104779. function OctreeSceneComponent(scene) {
  104780. /**
  104781. * The component name helpfull to identify the component in the list of scene components.
  104782. */
  104783. this.name = BABYLON.SceneComponentConstants.NAME_OCTREE;
  104784. /**
  104785. * Indicates if the meshes have been checked to make sure they are isEnabled()
  104786. */
  104787. this.checksIsEnabled = true;
  104788. this._tempRay = new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(1, 1, 1));
  104789. this.scene = scene;
  104790. this.scene.getActiveMeshCandidates = this.getActiveMeshCandidates.bind(this);
  104791. this.scene.getActiveSubMeshCandidates = this.getActiveSubMeshCandidates.bind(this);
  104792. this.scene.getCollidingSubMeshCandidates = this.getCollidingSubMeshCandidates.bind(this);
  104793. this.scene.getIntersectingSubMeshCandidates = this.getIntersectingSubMeshCandidates.bind(this);
  104794. }
  104795. /**
  104796. * Registers the component in a given scene
  104797. */
  104798. OctreeSceneComponent.prototype.register = function () {
  104799. var _this = this;
  104800. this.scene.onMeshRemovedObservable.add(function (mesh) {
  104801. var sceneOctree = _this.scene.selectionOctree;
  104802. if (sceneOctree !== undefined && sceneOctree !== null) {
  104803. var index = sceneOctree.dynamicContent.indexOf(mesh);
  104804. if (index !== -1) {
  104805. sceneOctree.dynamicContent.splice(index, 1);
  104806. }
  104807. }
  104808. });
  104809. this.scene.onMeshImportedObservable.add(function (mesh) {
  104810. var sceneOctree = _this.scene.selectionOctree;
  104811. if (sceneOctree !== undefined && sceneOctree !== null) {
  104812. sceneOctree.addMesh(mesh);
  104813. }
  104814. });
  104815. };
  104816. /**
  104817. * Return the list of active meshes
  104818. * @returns the list of active meshes
  104819. */
  104820. OctreeSceneComponent.prototype.getActiveMeshCandidates = function () {
  104821. if (this.scene._selectionOctree) {
  104822. var selection = this.scene._selectionOctree.select(this.scene.frustumPlanes);
  104823. return selection;
  104824. }
  104825. return this.scene._getDefaultMeshCandidates();
  104826. };
  104827. /**
  104828. * Return the list of active sub meshes
  104829. * @param mesh The mesh to get the candidates sub meshes from
  104830. * @returns the list of active sub meshes
  104831. */
  104832. OctreeSceneComponent.prototype.getActiveSubMeshCandidates = function (mesh) {
  104833. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  104834. var intersections = mesh._submeshesOctree.select(this.scene.frustumPlanes);
  104835. return intersections;
  104836. }
  104837. return this.scene._getDefaultSubMeshCandidates(mesh);
  104838. };
  104839. /**
  104840. * Return the list of sub meshes intersecting with a given local ray
  104841. * @param mesh defines the mesh to find the submesh for
  104842. * @param localRay defines the ray in local space
  104843. * @returns the list of intersecting sub meshes
  104844. */
  104845. OctreeSceneComponent.prototype.getIntersectingSubMeshCandidates = function (mesh, localRay) {
  104846. if (mesh._submeshesOctree && mesh.useOctreeForPicking) {
  104847. BABYLON.Ray.TransformToRef(localRay, mesh.getWorldMatrix(), this._tempRay);
  104848. var intersections = mesh._submeshesOctree.intersectsRay(this._tempRay);
  104849. return intersections;
  104850. }
  104851. return this.scene._getDefaultSubMeshCandidates(mesh);
  104852. };
  104853. /**
  104854. * Return the list of sub meshes colliding with a collider
  104855. * @param mesh defines the mesh to find the submesh for
  104856. * @param collider defines the collider to evaluate the collision against
  104857. * @returns the list of colliding sub meshes
  104858. */
  104859. OctreeSceneComponent.prototype.getCollidingSubMeshCandidates = function (mesh, collider) {
  104860. if (mesh._submeshesOctree && mesh.useOctreeForCollisions) {
  104861. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  104862. var intersections = mesh._submeshesOctree.intersects(collider._basePointWorld, radius);
  104863. return intersections;
  104864. }
  104865. return this.scene._getDefaultSubMeshCandidates(mesh);
  104866. };
  104867. /**
  104868. * Rebuilds the elements related to this component in case of
  104869. * context lost for instance.
  104870. */
  104871. OctreeSceneComponent.prototype.rebuild = function () {
  104872. // Nothing to do here.
  104873. };
  104874. /**
  104875. * Disposes the component and the associated ressources.
  104876. */
  104877. OctreeSceneComponent.prototype.dispose = function () {
  104878. // Nothing to do here.
  104879. };
  104880. return OctreeSceneComponent;
  104881. }());
  104882. BABYLON.OctreeSceneComponent = OctreeSceneComponent;
  104883. })(BABYLON || (BABYLON = {}));
  104884. //# sourceMappingURL=babylon.octreeSceneComponent.js.map
  104885. var BABYLON;
  104886. (function (BABYLON) {
  104887. /**
  104888. * Postprocess used to generate anaglyphic rendering
  104889. */
  104890. var AnaglyphPostProcess = /** @class */ (function (_super) {
  104891. __extends(AnaglyphPostProcess, _super);
  104892. /**
  104893. * Creates a new AnaglyphPostProcess
  104894. * @param name defines postprocess name
  104895. * @param options defines creation options or target ratio scale
  104896. * @param rigCameras defines cameras using this postprocess
  104897. * @param samplingMode defines required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  104898. * @param engine defines hosting engine
  104899. * @param reusable defines if the postprocess will be reused multiple times per frame
  104900. */
  104901. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  104902. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  104903. _this._passedProcess = rigCameras[0]._rigPostProcess;
  104904. _this.onApplyObservable.add(function (effect) {
  104905. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  104906. });
  104907. return _this;
  104908. }
  104909. return AnaglyphPostProcess;
  104910. }(BABYLON.PostProcess));
  104911. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  104912. })(BABYLON || (BABYLON = {}));
  104913. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  104914. var BABYLON;
  104915. (function (BABYLON) {
  104916. BABYLON.Node.AddNodeConstructor("AnaglyphArcRotateCamera", function (name, scene, options) {
  104917. return function () { return new AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  104918. });
  104919. /**
  104920. * Camera used to simulate anaglyphic rendering (based on ArcRotateCamera)
  104921. * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras
  104922. */
  104923. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  104924. __extends(AnaglyphArcRotateCamera, _super);
  104925. /**
  104926. * Creates a new AnaglyphArcRotateCamera
  104927. * @param name defines camera name
  104928. * @param alpha defines alpha angle (in radians)
  104929. * @param beta defines beta angle (in radians)
  104930. * @param radius defines radius
  104931. * @param target defines camera target
  104932. * @param interaxialDistance defines distance between each color axis
  104933. * @param scene defines the hosting scene
  104934. */
  104935. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  104936. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  104937. _this.interaxialDistance = interaxialDistance;
  104938. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  104939. return _this;
  104940. }
  104941. /**
  104942. * Gets camera class name
  104943. * @returns AnaglyphArcRotateCamera
  104944. */
  104945. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  104946. return "AnaglyphArcRotateCamera";
  104947. };
  104948. return AnaglyphArcRotateCamera;
  104949. }(BABYLON.ArcRotateCamera));
  104950. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  104951. })(BABYLON || (BABYLON = {}));
  104952. //# sourceMappingURL=babylon.anaglyphArcRotateCamera.js.map
  104953. var BABYLON;
  104954. (function (BABYLON) {
  104955. BABYLON.Node.AddNodeConstructor("AnaglyphFreeCamera", function (name, scene, options) {
  104956. return function () { return new AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  104957. });
  104958. /**
  104959. * Camera used to simulate anaglyphic rendering (based on FreeCamera)
  104960. * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras
  104961. */
  104962. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  104963. __extends(AnaglyphFreeCamera, _super);
  104964. /**
  104965. * Creates a new AnaglyphFreeCamera
  104966. * @param name defines camera name
  104967. * @param position defines initial position
  104968. * @param interaxialDistance defines distance between each color axis
  104969. * @param scene defines the hosting scene
  104970. */
  104971. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  104972. var _this = _super.call(this, name, position, scene) || this;
  104973. _this.interaxialDistance = interaxialDistance;
  104974. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  104975. return _this;
  104976. }
  104977. /**
  104978. * Gets camera class name
  104979. * @returns AnaglyphFreeCamera
  104980. */
  104981. AnaglyphFreeCamera.prototype.getClassName = function () {
  104982. return "AnaglyphFreeCamera";
  104983. };
  104984. return AnaglyphFreeCamera;
  104985. }(BABYLON.FreeCamera));
  104986. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  104987. })(BABYLON || (BABYLON = {}));
  104988. //# sourceMappingURL=babylon.anaglyphFreeCamera.js.map
  104989. var BABYLON;
  104990. (function (BABYLON) {
  104991. BABYLON.Node.AddNodeConstructor("AnaglyphGamepadCamera", function (name, scene, options) {
  104992. return function () { return new AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  104993. });
  104994. /**
  104995. * Camera used to simulate anaglyphic rendering (based on GamepadCamera)
  104996. * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras
  104997. */
  104998. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  104999. __extends(AnaglyphGamepadCamera, _super);
  105000. /**
  105001. * Creates a new AnaglyphGamepadCamera
  105002. * @param name defines camera name
  105003. * @param position defines initial position
  105004. * @param interaxialDistance defines distance between each color axis
  105005. * @param scene defines the hosting scene
  105006. */
  105007. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  105008. var _this = _super.call(this, name, position, scene) || this;
  105009. _this.interaxialDistance = interaxialDistance;
  105010. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  105011. return _this;
  105012. }
  105013. /**
  105014. * Gets camera class name
  105015. * @returns AnaglyphGamepadCamera
  105016. */
  105017. AnaglyphGamepadCamera.prototype.getClassName = function () {
  105018. return "AnaglyphGamepadCamera";
  105019. };
  105020. return AnaglyphGamepadCamera;
  105021. }(BABYLON.GamepadCamera));
  105022. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  105023. })(BABYLON || (BABYLON = {}));
  105024. //# sourceMappingURL=babylon.anaglyphGamepadCamera.js.map
  105025. var BABYLON;
  105026. (function (BABYLON) {
  105027. BABYLON.Node.AddNodeConstructor("AnaglyphUniversalCamera", function (name, scene, options) {
  105028. return function () { return new AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  105029. });
  105030. /**
  105031. * Camera used to simulate anaglyphic rendering (based on UniversalCamera)
  105032. * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras
  105033. */
  105034. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  105035. __extends(AnaglyphUniversalCamera, _super);
  105036. /**
  105037. * Creates a new AnaglyphUniversalCamera
  105038. * @param name defines camera name
  105039. * @param position defines initial position
  105040. * @param interaxialDistance defines distance between each color axis
  105041. * @param scene defines the hosting scene
  105042. */
  105043. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  105044. var _this = _super.call(this, name, position, scene) || this;
  105045. _this.interaxialDistance = interaxialDistance;
  105046. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  105047. return _this;
  105048. }
  105049. /**
  105050. * Gets camera class name
  105051. * @returns AnaglyphUniversalCamera
  105052. */
  105053. AnaglyphUniversalCamera.prototype.getClassName = function () {
  105054. return "AnaglyphUniversalCamera";
  105055. };
  105056. return AnaglyphUniversalCamera;
  105057. }(BABYLON.UniversalCamera));
  105058. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  105059. })(BABYLON || (BABYLON = {}));
  105060. //# sourceMappingURL=babylon.anaglyphUniversalCamera.js.map
  105061. var BABYLON;
  105062. (function (BABYLON) {
  105063. /**
  105064. * StereoscopicInterlacePostProcess used to render stereo views from a rigged camera
  105065. */
  105066. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  105067. __extends(StereoscopicInterlacePostProcess, _super);
  105068. /**
  105069. * Initializes a StereoscopicInterlacePostProcess
  105070. * @param name The name of the effect.
  105071. * @param rigCameras The rig cameras to be appled to the post process
  105072. * @param isStereoscopicHoriz If the rendered results are horizontal or verticle
  105073. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  105074. * @param engine The engine which the post process will be applied. (default: current engine)
  105075. * @param reusable If the post process can be reused on the same frame. (default: false)
  105076. */
  105077. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  105078. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  105079. _this._passedProcess = rigCameras[0]._rigPostProcess;
  105080. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  105081. _this.onSizeChangedObservable.add(function () {
  105082. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  105083. });
  105084. _this.onApplyObservable.add(function (effect) {
  105085. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  105086. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  105087. });
  105088. return _this;
  105089. }
  105090. return StereoscopicInterlacePostProcess;
  105091. }(BABYLON.PostProcess));
  105092. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  105093. })(BABYLON || (BABYLON = {}));
  105094. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  105095. var BABYLON;
  105096. (function (BABYLON) {
  105097. BABYLON.Node.AddNodeConstructor("StereoscopicArcRotateCamera", function (name, scene, options) {
  105098. return function () { return new StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  105099. });
  105100. /**
  105101. * Camera used to simulate stereoscopic rendering (based on ArcRotateCamera)
  105102. * @see http://doc.babylonjs.com/features/cameras
  105103. */
  105104. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  105105. __extends(StereoscopicArcRotateCamera, _super);
  105106. /**
  105107. * Creates a new StereoscopicArcRotateCamera
  105108. * @param name defines camera name
  105109. * @param alpha defines alpha angle (in radians)
  105110. * @param beta defines beta angle (in radians)
  105111. * @param radius defines radius
  105112. * @param target defines camera target
  105113. * @param interaxialDistance defines distance between each color axis
  105114. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  105115. * @param scene defines the hosting scene
  105116. */
  105117. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  105118. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  105119. _this.interaxialDistance = interaxialDistance;
  105120. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  105121. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  105122. return _this;
  105123. }
  105124. /**
  105125. * Gets camera class name
  105126. * @returns StereoscopicArcRotateCamera
  105127. */
  105128. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  105129. return "StereoscopicArcRotateCamera";
  105130. };
  105131. return StereoscopicArcRotateCamera;
  105132. }(BABYLON.ArcRotateCamera));
  105133. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  105134. })(BABYLON || (BABYLON = {}));
  105135. //# sourceMappingURL=babylon.stereoscopicArcRotateCamera.js.map
  105136. var BABYLON;
  105137. (function (BABYLON) {
  105138. BABYLON.Node.AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) {
  105139. return function () { return new StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  105140. });
  105141. /**
  105142. * Camera used to simulate stereoscopic rendering (based on FreeCamera)
  105143. * @see http://doc.babylonjs.com/features/cameras
  105144. */
  105145. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  105146. __extends(StereoscopicFreeCamera, _super);
  105147. /**
  105148. * Creates a new StereoscopicFreeCamera
  105149. * @param name defines camera name
  105150. * @param position defines initial position
  105151. * @param interaxialDistance defines distance between each color axis
  105152. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  105153. * @param scene defines the hosting scene
  105154. */
  105155. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  105156. var _this = _super.call(this, name, position, scene) || this;
  105157. _this.interaxialDistance = interaxialDistance;
  105158. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  105159. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  105160. return _this;
  105161. }
  105162. /**
  105163. * Gets camera class name
  105164. * @returns StereoscopicFreeCamera
  105165. */
  105166. StereoscopicFreeCamera.prototype.getClassName = function () {
  105167. return "StereoscopicFreeCamera";
  105168. };
  105169. return StereoscopicFreeCamera;
  105170. }(BABYLON.FreeCamera));
  105171. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  105172. })(BABYLON || (BABYLON = {}));
  105173. //# sourceMappingURL=babylon.stereoscopicFreeCamera.js.map
  105174. var BABYLON;
  105175. (function (BABYLON) {
  105176. BABYLON.Node.AddNodeConstructor("StereoscopicGamepadCamera", function (name, scene, options) {
  105177. return function () { return new StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  105178. });
  105179. /**
  105180. * Camera used to simulate stereoscopic rendering (based on GamepadCamera)
  105181. * @see http://doc.babylonjs.com/features/cameras
  105182. */
  105183. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  105184. __extends(StereoscopicGamepadCamera, _super);
  105185. /**
  105186. * Creates a new StereoscopicGamepadCamera
  105187. * @param name defines camera name
  105188. * @param position defines initial position
  105189. * @param interaxialDistance defines distance between each color axis
  105190. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  105191. * @param scene defines the hosting scene
  105192. */
  105193. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  105194. var _this = _super.call(this, name, position, scene) || this;
  105195. _this.interaxialDistance = interaxialDistance;
  105196. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  105197. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  105198. return _this;
  105199. }
  105200. /**
  105201. * Gets camera class name
  105202. * @returns StereoscopicGamepadCamera
  105203. */
  105204. StereoscopicGamepadCamera.prototype.getClassName = function () {
  105205. return "StereoscopicGamepadCamera";
  105206. };
  105207. return StereoscopicGamepadCamera;
  105208. }(BABYLON.GamepadCamera));
  105209. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  105210. })(BABYLON || (BABYLON = {}));
  105211. //# sourceMappingURL=babylon.stereoscopicGamepadCamera.js.map
  105212. var BABYLON;
  105213. (function (BABYLON) {
  105214. BABYLON.Node.AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) {
  105215. return function () { return new StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  105216. });
  105217. /**
  105218. * Camera used to simulate stereoscopic rendering (based on UniversalCamera)
  105219. * @see http://doc.babylonjs.com/features/cameras
  105220. */
  105221. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  105222. __extends(StereoscopicUniversalCamera, _super);
  105223. /**
  105224. * Creates a new StereoscopicUniversalCamera
  105225. * @param name defines camera name
  105226. * @param position defines initial position
  105227. * @param interaxialDistance defines distance between each color axis
  105228. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  105229. * @param scene defines the hosting scene
  105230. */
  105231. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  105232. var _this = _super.call(this, name, position, scene) || this;
  105233. _this.interaxialDistance = interaxialDistance;
  105234. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  105235. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  105236. return _this;
  105237. }
  105238. /**
  105239. * Gets camera class name
  105240. * @returns StereoscopicUniversalCamera
  105241. */
  105242. StereoscopicUniversalCamera.prototype.getClassName = function () {
  105243. return "StereoscopicUniversalCamera";
  105244. };
  105245. return StereoscopicUniversalCamera;
  105246. }(BABYLON.UniversalCamera));
  105247. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  105248. })(BABYLON || (BABYLON = {}));
  105249. //# sourceMappingURL=babylon.stereoscopicUniversalCamera.js.map
  105250. var BABYLON;
  105251. (function (BABYLON) {
  105252. /**
  105253. * VRDistortionCorrectionPostProcess used for mobile VR
  105254. */
  105255. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  105256. __extends(VRDistortionCorrectionPostProcess, _super);
  105257. /**
  105258. * Initializes the VRDistortionCorrectionPostProcess
  105259. * @param name The name of the effect.
  105260. * @param camera The camera to apply the render pass to.
  105261. * @param isRightEye If this is for the right eye distortion
  105262. * @param vrMetrics All the required metrics for the VR camera
  105263. */
  105264. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  105265. var _this = _super.call(this, name, "vrDistortionCorrection", [
  105266. 'LensCenter',
  105267. 'Scale',
  105268. 'ScaleIn',
  105269. 'HmdWarpParam'
  105270. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  105271. _this._isRightEye = isRightEye;
  105272. _this._distortionFactors = vrMetrics.distortionK;
  105273. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  105274. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  105275. _this.adaptScaleToCurrentViewport = true;
  105276. _this.onSizeChangedObservable.add(function () {
  105277. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  105278. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  105279. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  105280. });
  105281. _this.onApplyObservable.add(function (effect) {
  105282. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  105283. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  105284. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  105285. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  105286. });
  105287. return _this;
  105288. }
  105289. return VRDistortionCorrectionPostProcess;
  105290. }(BABYLON.PostProcess));
  105291. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  105292. })(BABYLON || (BABYLON = {}));
  105293. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  105294. var BABYLON;
  105295. (function (BABYLON) {
  105296. /**
  105297. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  105298. * Screen rotation is taken into account.
  105299. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  105300. */
  105301. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  105302. /**
  105303. * Instantiates a new input
  105304. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  105305. */
  105306. function FreeCameraDeviceOrientationInput() {
  105307. var _this = this;
  105308. this._screenOrientationAngle = 0;
  105309. this._screenQuaternion = new BABYLON.Quaternion();
  105310. this._alpha = 0;
  105311. this._beta = 0;
  105312. this._gamma = 0;
  105313. this._orientationChanged = function () {
  105314. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && (window.screen.orientation)['angle'] ? (window.screen.orientation).angle : 0));
  105315. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  105316. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  105317. };
  105318. this._deviceOrientation = function (evt) {
  105319. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  105320. _this._beta = evt.beta !== null ? evt.beta : 0;
  105321. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  105322. };
  105323. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  105324. this._orientationChanged();
  105325. }
  105326. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  105327. /**
  105328. * Define the camera controlled by the input.
  105329. */
  105330. get: function () {
  105331. return this._camera;
  105332. },
  105333. set: function (camera) {
  105334. this._camera = camera;
  105335. if (this._camera != null && !this._camera.rotationQuaternion) {
  105336. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  105337. }
  105338. },
  105339. enumerable: true,
  105340. configurable: true
  105341. });
  105342. /**
  105343. * Attach the input controls to a specific dom element to get the input from.
  105344. * @param element Defines the element the controls should be listened from
  105345. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  105346. */
  105347. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  105348. window.addEventListener("orientationchange", this._orientationChanged);
  105349. window.addEventListener("deviceorientation", this._deviceOrientation);
  105350. //In certain cases, the attach control is called AFTER orientation was changed,
  105351. //So this is needed.
  105352. this._orientationChanged();
  105353. };
  105354. /**
  105355. * Detach the current controls from the specified dom element.
  105356. * @param element Defines the element to stop listening the inputs from
  105357. */
  105358. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  105359. window.removeEventListener("orientationchange", this._orientationChanged);
  105360. window.removeEventListener("deviceorientation", this._deviceOrientation);
  105361. };
  105362. /**
  105363. * Update the current camera state depending on the inputs that have been used this frame.
  105364. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  105365. */
  105366. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  105367. //if no device orientation provided, don't update the rotation.
  105368. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  105369. if (!this._alpha) {
  105370. return;
  105371. }
  105372. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  105373. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  105374. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  105375. //Mirror on XY Plane
  105376. this._camera.rotationQuaternion.z *= -1;
  105377. this._camera.rotationQuaternion.w *= -1;
  105378. };
  105379. /**
  105380. * Gets the class name of the current intput.
  105381. * @returns the class name
  105382. */
  105383. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  105384. return "FreeCameraDeviceOrientationInput";
  105385. };
  105386. /**
  105387. * Get the friendly name associated with the input class.
  105388. * @returns the input friendly name
  105389. */
  105390. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  105391. return "deviceOrientation";
  105392. };
  105393. return FreeCameraDeviceOrientationInput;
  105394. }());
  105395. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  105396. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  105397. })(BABYLON || (BABYLON = {}));
  105398. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  105399. var BABYLON;
  105400. (function (BABYLON) {
  105401. /**
  105402. * Manage the device orientation inputs (gyroscope) to control an arc rotate camera.
  105403. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  105404. */
  105405. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  105406. /**
  105407. * Instantiate a new ArcRotateCameraVRDeviceOrientationInput.
  105408. */
  105409. function ArcRotateCameraVRDeviceOrientationInput() {
  105410. /**
  105411. * Defines a correction factor applied on the alpha value retrieved from the orientation events.
  105412. */
  105413. this.alphaCorrection = 1;
  105414. /**
  105415. * Defines a correction factor applied on the gamma value retrieved from the orientation events.
  105416. */
  105417. this.gammaCorrection = 1;
  105418. this._alpha = 0;
  105419. this._gamma = 0;
  105420. this._dirty = false;
  105421. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  105422. }
  105423. /**
  105424. * Attach the input controls to a specific dom element to get the input from.
  105425. * @param element Defines the element the controls should be listened from
  105426. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  105427. */
  105428. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  105429. this.camera.attachControl(element, noPreventDefault);
  105430. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  105431. };
  105432. /** @hidden */
  105433. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  105434. if (evt.alpha !== null) {
  105435. this._alpha = (+evt.alpha | 0) * this.alphaCorrection;
  105436. }
  105437. if (evt.gamma !== null) {
  105438. this._gamma = (+evt.gamma | 0) * this.gammaCorrection;
  105439. }
  105440. this._dirty = true;
  105441. };
  105442. /**
  105443. * Update the current camera state depending on the inputs that have been used this frame.
  105444. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  105445. */
  105446. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  105447. if (this._dirty) {
  105448. this._dirty = false;
  105449. if (this._gamma < 0) {
  105450. this._gamma = 180 + this._gamma;
  105451. }
  105452. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  105453. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  105454. }
  105455. };
  105456. /**
  105457. * Detach the current controls from the specified dom element.
  105458. * @param element Defines the element to stop listening the inputs from
  105459. */
  105460. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  105461. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  105462. };
  105463. /**
  105464. * Gets the class name of the current intput.
  105465. * @returns the class name
  105466. */
  105467. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  105468. return "ArcRotateCameraVRDeviceOrientationInput";
  105469. };
  105470. /**
  105471. * Get the friendly name associated with the input class.
  105472. * @returns the input friendly name
  105473. */
  105474. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  105475. return "VRDeviceOrientation";
  105476. };
  105477. return ArcRotateCameraVRDeviceOrientationInput;
  105478. }());
  105479. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  105480. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  105481. })(BABYLON || (BABYLON = {}));
  105482. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  105483. var BABYLON;
  105484. (function (BABYLON) {
  105485. /**
  105486. * This represents all the required metrics to create a VR camera.
  105487. * @see http://doc.babylonjs.com/babylon101/cameras#device-orientation-camera
  105488. */
  105489. var VRCameraMetrics = /** @class */ (function () {
  105490. function VRCameraMetrics() {
  105491. /**
  105492. * Define if the current vr camera should compensate the distortion of the lense or not.
  105493. */
  105494. this.compensateDistortion = true;
  105495. }
  105496. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  105497. /**
  105498. * Gets the rendering aspect ratio based on the provided resolutions.
  105499. */
  105500. get: function () {
  105501. return this.hResolution / (2 * this.vResolution);
  105502. },
  105503. enumerable: true,
  105504. configurable: true
  105505. });
  105506. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  105507. /**
  105508. * Gets the aspect ratio based on the FOV, scale factors, and real screen sizes.
  105509. */
  105510. get: function () {
  105511. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  105512. },
  105513. enumerable: true,
  105514. configurable: true
  105515. });
  105516. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  105517. /**
  105518. * @hidden
  105519. */
  105520. get: function () {
  105521. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  105522. var h = (4 * meters) / this.hScreenSize;
  105523. return BABYLON.Matrix.Translation(h, 0, 0);
  105524. },
  105525. enumerable: true,
  105526. configurable: true
  105527. });
  105528. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  105529. /**
  105530. * @hidden
  105531. */
  105532. get: function () {
  105533. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  105534. var h = (4 * meters) / this.hScreenSize;
  105535. return BABYLON.Matrix.Translation(-h, 0, 0);
  105536. },
  105537. enumerable: true,
  105538. configurable: true
  105539. });
  105540. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  105541. /**
  105542. * @hidden
  105543. */
  105544. get: function () {
  105545. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  105546. },
  105547. enumerable: true,
  105548. configurable: true
  105549. });
  105550. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  105551. /**
  105552. * @hidden
  105553. */
  105554. get: function () {
  105555. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  105556. },
  105557. enumerable: true,
  105558. configurable: true
  105559. });
  105560. /**
  105561. * Get the default VRMetrics based on the most generic setup.
  105562. * @returns the default vr metrics
  105563. */
  105564. VRCameraMetrics.GetDefault = function () {
  105565. var result = new VRCameraMetrics();
  105566. result.hResolution = 1280;
  105567. result.vResolution = 800;
  105568. result.hScreenSize = 0.149759993;
  105569. result.vScreenSize = 0.0935999975;
  105570. result.vScreenCenter = 0.0467999987;
  105571. result.eyeToScreenDistance = 0.0410000011;
  105572. result.lensSeparationDistance = 0.0635000020;
  105573. result.interpupillaryDistance = 0.0640000030;
  105574. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  105575. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  105576. result.postProcessScaleFactor = 1.714605507808412;
  105577. result.lensCenterOffset = 0.151976421;
  105578. return result;
  105579. };
  105580. return VRCameraMetrics;
  105581. }());
  105582. BABYLON.VRCameraMetrics = VRCameraMetrics;
  105583. })(BABYLON || (BABYLON = {}));
  105584. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  105585. var BABYLON;
  105586. (function (BABYLON) {
  105587. BABYLON.Node.AddNodeConstructor("WebVRFreeCamera", function (name, scene) {
  105588. return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  105589. });
  105590. BABYLON.Node.AddNodeConstructor("WebVRGamepadCamera", function (name, scene) {
  105591. return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  105592. });
  105593. /**
  105594. * This represents a WebVR camera.
  105595. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  105596. * @example http://doc.babylonjs.com/how_to/webvr_camera
  105597. */
  105598. var WebVRFreeCamera = /** @class */ (function (_super) {
  105599. __extends(WebVRFreeCamera, _super);
  105600. /**
  105601. * Instantiates a WebVRFreeCamera.
  105602. * @param name The name of the WebVRFreeCamera
  105603. * @param position The starting anchor position for the camera
  105604. * @param scene The scene the camera belongs to
  105605. * @param webVROptions a set of customizable options for the webVRCamera
  105606. */
  105607. function WebVRFreeCamera(name, position, scene, webVROptions) {
  105608. if (webVROptions === void 0) { webVROptions = {}; }
  105609. var _this = _super.call(this, name, position, scene) || this;
  105610. _this.webVROptions = webVROptions;
  105611. /**
  105612. * @hidden
  105613. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  105614. */
  105615. _this._vrDevice = null;
  105616. /**
  105617. * The rawPose of the vrDevice.
  105618. */
  105619. _this.rawPose = null;
  105620. _this._specsVersion = "1.1";
  105621. _this._attached = false;
  105622. _this._descendants = [];
  105623. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  105624. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  105625. /** @hidden */
  105626. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  105627. _this._standingMatrix = null;
  105628. /**
  105629. * Represents device position in babylon space.
  105630. */
  105631. _this.devicePosition = BABYLON.Vector3.Zero();
  105632. /**
  105633. * Represents device rotation in babylon space.
  105634. */
  105635. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  105636. /**
  105637. * The scale of the device to be used when translating from device space to babylon space.
  105638. */
  105639. _this.deviceScaleFactor = 1;
  105640. _this._deviceToWorld = BABYLON.Matrix.Identity();
  105641. _this._worldToDevice = BABYLON.Matrix.Identity();
  105642. /**
  105643. * References to the webVR controllers for the vrDevice.
  105644. */
  105645. _this.controllers = [];
  105646. /**
  105647. * Emits an event when a controller is attached.
  105648. */
  105649. _this.onControllersAttachedObservable = new BABYLON.Observable();
  105650. /**
  105651. * Emits an event when a controller's mesh has been loaded;
  105652. */
  105653. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  105654. /**
  105655. * Emits an event when the HMD's pose has been updated.
  105656. */
  105657. _this.onPoseUpdatedFromDeviceObservable = new BABYLON.Observable();
  105658. _this._poseSet = false;
  105659. /**
  105660. * If the rig cameras be used as parent instead of this camera.
  105661. */
  105662. _this.rigParenting = true;
  105663. _this._defaultHeight = undefined;
  105664. _this._htmlElementAttached = null;
  105665. _this._detachIfAttached = function () {
  105666. var vrDisplay = _this.getEngine().getVRDevice();
  105667. if (vrDisplay && !vrDisplay.isPresenting && _this._htmlElementAttached) {
  105668. _this.detachControl(_this._htmlElementAttached);
  105669. }
  105670. };
  105671. _this._workingVector = BABYLON.Vector3.Zero();
  105672. _this._oneVector = BABYLON.Vector3.One();
  105673. _this._workingMatrix = BABYLON.Matrix.Identity();
  105674. _this._tmpMatrix = new BABYLON.Matrix();
  105675. _this._cache.position = BABYLON.Vector3.Zero();
  105676. if (webVROptions.defaultHeight) {
  105677. _this._defaultHeight = webVROptions.defaultHeight;
  105678. _this.position.y = _this._defaultHeight;
  105679. }
  105680. _this.minZ = 0.1;
  105681. //legacy support - the compensation boolean was removed.
  105682. if (arguments.length === 5) {
  105683. _this.webVROptions = arguments[4];
  105684. }
  105685. // default webVR options
  105686. if (_this.webVROptions.trackPosition == undefined) {
  105687. _this.webVROptions.trackPosition = true;
  105688. }
  105689. if (_this.webVROptions.controllerMeshes == undefined) {
  105690. _this.webVROptions.controllerMeshes = true;
  105691. }
  105692. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  105693. _this.webVROptions.defaultLightingOnControllers = true;
  105694. }
  105695. _this.rotationQuaternion = new BABYLON.Quaternion();
  105696. if (_this.webVROptions && _this.webVROptions.positionScale) {
  105697. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  105698. }
  105699. //enable VR
  105700. var engine = _this.getEngine();
  105701. _this._onVREnabled = function (success) { if (success) {
  105702. _this.initControllers();
  105703. } };
  105704. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  105705. engine.initWebVR().add(function (event) {
  105706. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  105707. return;
  105708. }
  105709. _this._vrDevice = event.vrDisplay;
  105710. //reset the rig parameters.
  105711. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  105712. if (_this._attached) {
  105713. _this.getEngine().enableVR();
  105714. }
  105715. });
  105716. if (typeof (VRFrameData) !== "undefined") {
  105717. _this._frameData = new VRFrameData();
  105718. }
  105719. /**
  105720. * The idea behind the following lines:
  105721. * objects that have the camera as parent should actually have the rig cameras as a parent.
  105722. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  105723. * the second will not show it correctly.
  105724. *
  105725. * To solve this - each object that has the camera as parent will be added to a protected array.
  105726. * When the rig camera renders, it will take this array and set all of those to be its children.
  105727. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  105728. * Amazing!
  105729. */
  105730. scene.onBeforeCameraRenderObservable.add(function (camera) {
  105731. if (camera.parent === _this && _this.rigParenting) {
  105732. _this._descendants = _this.getDescendants(true, function (n) {
  105733. // don't take the cameras or the controllers!
  105734. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  105735. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  105736. return !isController && !isRigCamera;
  105737. });
  105738. _this._descendants.forEach(function (node) {
  105739. node.parent = camera;
  105740. });
  105741. }
  105742. });
  105743. scene.onAfterCameraRenderObservable.add(function (camera) {
  105744. if (camera.parent === _this && _this.rigParenting) {
  105745. _this._descendants.forEach(function (node) {
  105746. node.parent = _this;
  105747. });
  105748. }
  105749. });
  105750. return _this;
  105751. }
  105752. /**
  105753. * Gets the device distance from the ground in meters.
  105754. * @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.
  105755. */
  105756. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  105757. if (this._standingMatrix) {
  105758. // Add standing matrix offset to get real offset from ground in room
  105759. this._standingMatrix.getTranslationToRef(this._workingVector);
  105760. return this._deviceRoomPosition.y + this._workingVector.y;
  105761. }
  105762. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  105763. return this._defaultHeight || 0;
  105764. };
  105765. /**
  105766. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  105767. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  105768. */
  105769. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  105770. var _this = this;
  105771. if (callback === void 0) { callback = function (bool) { }; }
  105772. // Use standing matrix if available
  105773. this.getEngine().initWebVRAsync().then(function (result) {
  105774. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform || !_this.webVROptions.trackPosition) {
  105775. callback(false);
  105776. }
  105777. else {
  105778. _this._standingMatrix = new BABYLON.Matrix();
  105779. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  105780. if (!_this.getScene().useRightHandedSystem) {
  105781. if (_this._standingMatrix) {
  105782. _this._standingMatrix.toggleModelMatrixHandInPlace();
  105783. }
  105784. }
  105785. callback(true);
  105786. }
  105787. });
  105788. };
  105789. /**
  105790. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  105791. * @returns A promise with a boolean set to if the standing matrix is supported.
  105792. */
  105793. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  105794. var _this = this;
  105795. return new Promise(function (res, rej) {
  105796. _this.useStandingMatrix(function (supported) {
  105797. res(supported);
  105798. });
  105799. });
  105800. };
  105801. /**
  105802. * Disposes the camera
  105803. */
  105804. WebVRFreeCamera.prototype.dispose = function () {
  105805. this._detachIfAttached();
  105806. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  105807. if (this._updateCacheWhenTrackingDisabledObserver) {
  105808. this._scene.onBeforeRenderObservable.remove(this._updateCacheWhenTrackingDisabledObserver);
  105809. }
  105810. _super.prototype.dispose.call(this);
  105811. };
  105812. /**
  105813. * Gets a vrController by name.
  105814. * @param name The name of the controller to retreive
  105815. * @returns the controller matching the name specified or null if not found
  105816. */
  105817. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  105818. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  105819. var gp = _a[_i];
  105820. if (gp.hand === name) {
  105821. return gp;
  105822. }
  105823. }
  105824. return null;
  105825. };
  105826. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  105827. /**
  105828. * The controller corrisponding to the users left hand.
  105829. */
  105830. get: function () {
  105831. if (!this._leftController) {
  105832. this._leftController = this.getControllerByName("left");
  105833. }
  105834. return this._leftController;
  105835. },
  105836. enumerable: true,
  105837. configurable: true
  105838. });
  105839. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  105840. /**
  105841. * The controller corrisponding to the users right hand.
  105842. */
  105843. get: function () {
  105844. if (!this._rightController) {
  105845. this._rightController = this.getControllerByName("right");
  105846. }
  105847. return this._rightController;
  105848. },
  105849. enumerable: true,
  105850. configurable: true
  105851. });
  105852. /**
  105853. * Casts a ray forward from the vrCamera's gaze.
  105854. * @param length Length of the ray (default: 100)
  105855. * @returns the ray corrisponding to the gaze
  105856. */
  105857. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  105858. if (length === void 0) { length = 100; }
  105859. if (this.leftCamera) {
  105860. // Use left eye to avoid computation to compute center on every call
  105861. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  105862. }
  105863. else {
  105864. return _super.prototype.getForwardRay.call(this, length);
  105865. }
  105866. };
  105867. /**
  105868. * @hidden
  105869. * Updates the camera based on device's frame data
  105870. */
  105871. WebVRFreeCamera.prototype._checkInputs = function () {
  105872. if (this._vrDevice && this._vrDevice.isPresenting) {
  105873. this._vrDevice.getFrameData(this._frameData);
  105874. this.updateFromDevice(this._frameData.pose);
  105875. }
  105876. _super.prototype._checkInputs.call(this);
  105877. };
  105878. /**
  105879. * Updates the poseControlled values based on the input device pose.
  105880. * @param poseData Pose coming from the device
  105881. */
  105882. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  105883. if (poseData && poseData.orientation) {
  105884. this.rawPose = poseData;
  105885. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  105886. if (this.getScene().useRightHandedSystem) {
  105887. this._deviceRoomRotationQuaternion.z *= -1;
  105888. this._deviceRoomRotationQuaternion.w *= -1;
  105889. }
  105890. if (this.webVROptions.trackPosition && this.rawPose.position) {
  105891. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  105892. if (this.getScene().useRightHandedSystem) {
  105893. this._deviceRoomPosition.z *= -1;
  105894. }
  105895. }
  105896. this._poseSet = true;
  105897. }
  105898. };
  105899. /**
  105900. * WebVR's attach control will start broadcasting frames to the device.
  105901. * Note that in certain browsers (chrome for example) this function must be called
  105902. * within a user-interaction callback. Example:
  105903. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  105904. *
  105905. * @param element html element to attach the vrDevice to
  105906. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  105907. */
  105908. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  105909. _super.prototype.attachControl.call(this, element, noPreventDefault);
  105910. this._attached = true;
  105911. this._htmlElementAttached = element;
  105912. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  105913. if (this._vrDevice) {
  105914. this.getEngine().enableVR();
  105915. }
  105916. window.addEventListener('vrdisplaypresentchange', this._detachIfAttached);
  105917. };
  105918. /**
  105919. * Detaches the camera from the html element and disables VR
  105920. *
  105921. * @param element html element to detach from
  105922. */
  105923. WebVRFreeCamera.prototype.detachControl = function (element) {
  105924. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  105925. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  105926. _super.prototype.detachControl.call(this, element);
  105927. this._attached = false;
  105928. this.getEngine().disableVR();
  105929. window.removeEventListener('vrdisplaypresentchange', this._detachIfAttached);
  105930. };
  105931. /**
  105932. * @returns the name of this class
  105933. */
  105934. WebVRFreeCamera.prototype.getClassName = function () {
  105935. return "WebVRFreeCamera";
  105936. };
  105937. /**
  105938. * Calls resetPose on the vrDisplay
  105939. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  105940. */
  105941. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  105942. //uses the vrDisplay's "resetPose()".
  105943. //pitch and roll won't be affected.
  105944. this._vrDevice.resetPose();
  105945. };
  105946. /**
  105947. * @hidden
  105948. * Updates the rig cameras (left and right eye)
  105949. */
  105950. WebVRFreeCamera.prototype._updateRigCameras = function () {
  105951. var camLeft = this._rigCameras[0];
  105952. var camRight = this._rigCameras[1];
  105953. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  105954. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  105955. camLeft.position.copyFrom(this._deviceRoomPosition);
  105956. camRight.position.copyFrom(this._deviceRoomPosition);
  105957. };
  105958. // Remove translation from 6dof headset if trackposition is set to false
  105959. WebVRFreeCamera.prototype._correctPositionIfNotTrackPosition = function (matrix, isViewMatrix) {
  105960. if (isViewMatrix === void 0) { isViewMatrix = false; }
  105961. if (this.rawPose && this.rawPose.position && !this.webVROptions.trackPosition) {
  105962. BABYLON.Matrix.TranslationToRef(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2], this._tmpMatrix);
  105963. if (!isViewMatrix) {
  105964. this._tmpMatrix.invert();
  105965. }
  105966. this._tmpMatrix.multiplyToRef(matrix, matrix);
  105967. }
  105968. };
  105969. /**
  105970. * @hidden
  105971. * Updates the cached values of the camera
  105972. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  105973. */
  105974. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  105975. var _this = this;
  105976. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  105977. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  105978. if (!this.updateCacheCalled) {
  105979. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  105980. this.updateCacheCalled = true;
  105981. this.update();
  105982. }
  105983. // Set working vector to the device position in room space rotated by the new rotation
  105984. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  105985. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  105986. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  105987. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  105988. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  105989. // Add translation from anchor position
  105990. this._deviceToWorld.getTranslationToRef(this._workingVector);
  105991. this._workingVector.addInPlace(this.position);
  105992. this._workingVector.subtractInPlace(this._cache.position);
  105993. this._deviceToWorld.setTranslation(this._workingVector);
  105994. // Set an inverted matrix to be used when updating the camera
  105995. this._deviceToWorld.invertToRef(this._worldToDevice);
  105996. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  105997. this.controllers.forEach(function (controller) {
  105998. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  105999. _this._correctPositionIfNotTrackPosition(controller._deviceToWorld);
  106000. controller.update();
  106001. });
  106002. }
  106003. if (!ignoreParentClass) {
  106004. _super.prototype._updateCache.call(this);
  106005. }
  106006. this.updateCacheCalled = false;
  106007. };
  106008. /**
  106009. * @hidden
  106010. * Get current device position in babylon world
  106011. */
  106012. WebVRFreeCamera.prototype._computeDevicePosition = function () {
  106013. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  106014. };
  106015. /**
  106016. * Updates the current device position and rotation in the babylon world
  106017. */
  106018. WebVRFreeCamera.prototype.update = function () {
  106019. this._computeDevicePosition();
  106020. // Get current device rotation in babylon world
  106021. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  106022. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  106023. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  106024. if (this._poseSet) {
  106025. this.onPoseUpdatedFromDeviceObservable.notifyObservers(null);
  106026. }
  106027. _super.prototype.update.call(this);
  106028. };
  106029. /**
  106030. * @hidden
  106031. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  106032. * @returns an identity matrix
  106033. */
  106034. WebVRFreeCamera.prototype._getViewMatrix = function () {
  106035. return BABYLON.Matrix.Identity();
  106036. };
  106037. /**
  106038. * This function is called by the two RIG cameras.
  106039. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  106040. */
  106041. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  106042. // Update the parent camera prior to using a child camera to avoid desynchronization
  106043. var parentCamera = this._cameraRigParams["parentCamera"];
  106044. parentCamera._updateCache();
  106045. //WebVR 1.1
  106046. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  106047. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  106048. if (!this.getScene().useRightHandedSystem) {
  106049. this._webvrViewMatrix.toggleModelMatrixHandInPlace();
  106050. }
  106051. // update the camera rotation matrix
  106052. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  106053. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  106054. // Computing target and final matrix
  106055. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  106056. // should the view matrix be updated with scale and position offset?
  106057. if (parentCamera.deviceScaleFactor !== 1) {
  106058. this._webvrViewMatrix.invert();
  106059. // scale the position, if set
  106060. if (parentCamera.deviceScaleFactor) {
  106061. this._webvrViewMatrix.multiplyAtIndex(12, parentCamera.deviceScaleFactor);
  106062. this._webvrViewMatrix.multiplyAtIndex(13, parentCamera.deviceScaleFactor);
  106063. this._webvrViewMatrix.multiplyAtIndex(14, parentCamera.deviceScaleFactor);
  106064. }
  106065. this._webvrViewMatrix.invert();
  106066. }
  106067. // Remove translation from 6dof headset if trackposition is set to false
  106068. parentCamera._correctPositionIfNotTrackPosition(this._webvrViewMatrix, true);
  106069. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  106070. // Compute global position
  106071. this._workingMatrix = this._workingMatrix || BABYLON.Matrix.Identity();
  106072. this._webvrViewMatrix.invertToRef(this._workingMatrix);
  106073. this._workingMatrix.multiplyToRef(parentCamera.getWorldMatrix(), this._workingMatrix);
  106074. this._workingMatrix.getTranslationToRef(this._globalPosition);
  106075. this._markSyncedWithParent();
  106076. return this._webvrViewMatrix;
  106077. };
  106078. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  106079. var parentCamera = this.parent;
  106080. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  106081. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  106082. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  106083. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  106084. //babylon compatible matrix
  106085. if (!this.getScene().useRightHandedSystem) {
  106086. this._projectionMatrix.toggleProjectionMatrixHandInPlace();
  106087. }
  106088. return this._projectionMatrix;
  106089. };
  106090. /**
  106091. * Initializes the controllers and their meshes
  106092. */
  106093. WebVRFreeCamera.prototype.initControllers = function () {
  106094. var _this = this;
  106095. this.controllers = [];
  106096. var manager = this.getScene().gamepadManager;
  106097. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  106098. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  106099. var webVrController = gamepad;
  106100. if (webVrController.defaultModel) {
  106101. webVrController.defaultModel.setEnabled(false);
  106102. }
  106103. if (webVrController.hand === "right") {
  106104. _this._rightController = null;
  106105. }
  106106. if (webVrController.hand === "left") {
  106107. _this._leftController = null;
  106108. }
  106109. var controllerIndex = _this.controllers.indexOf(webVrController);
  106110. if (controllerIndex !== -1) {
  106111. _this.controllers.splice(controllerIndex, 1);
  106112. }
  106113. }
  106114. });
  106115. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  106116. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  106117. var webVrController_1 = gamepad;
  106118. if (!_this.webVROptions.trackPosition) {
  106119. webVrController_1._disableTrackPosition(new BABYLON.Vector3(webVrController_1.hand == "left" ? -0.15 : 0.15, -0.5, 0.25));
  106120. // Cache must be updated before rendering controllers to avoid them being one frame behind
  106121. if (!_this._updateCacheWhenTrackingDisabledObserver) {
  106122. _this._updateCacheWhenTrackingDisabledObserver = _this._scene.onBeforeRenderObservable.add(function () {
  106123. _this._updateCache();
  106124. });
  106125. }
  106126. }
  106127. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  106128. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  106129. _this._correctPositionIfNotTrackPosition(webVrController_1._deviceToWorld);
  106130. if (_this.webVROptions.controllerMeshes) {
  106131. if (webVrController_1.defaultModel) {
  106132. webVrController_1.defaultModel.setEnabled(true);
  106133. }
  106134. else {
  106135. // Load the meshes
  106136. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  106137. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  106138. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  106139. if (_this.webVROptions.defaultLightingOnControllers) {
  106140. if (!_this._lightOnControllers) {
  106141. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  106142. }
  106143. var activateLightOnSubMeshes_1 = function (mesh, light) {
  106144. var children = mesh.getChildren();
  106145. if (children && children.length !== 0) {
  106146. children.forEach(function (mesh) {
  106147. light.includedOnlyMeshes.push(mesh);
  106148. activateLightOnSubMeshes_1(mesh, light);
  106149. });
  106150. }
  106151. };
  106152. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  106153. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  106154. }
  106155. });
  106156. }
  106157. }
  106158. webVrController_1.attachToPoseControlledCamera(_this);
  106159. // since this is async - sanity check. Is the controller already stored?
  106160. if (_this.controllers.indexOf(webVrController_1) === -1) {
  106161. //add to the controllers array
  106162. _this.controllers.push(webVrController_1);
  106163. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  106164. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  106165. // So we're overriding setting left & right manually to be sure
  106166. var firstViveWandDetected = false;
  106167. for (var i = 0; i < _this.controllers.length; i++) {
  106168. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  106169. if (!firstViveWandDetected) {
  106170. firstViveWandDetected = true;
  106171. _this.controllers[i].hand = "left";
  106172. }
  106173. else {
  106174. _this.controllers[i].hand = "right";
  106175. }
  106176. }
  106177. }
  106178. //did we find enough controllers? Great! let the developer know.
  106179. if (_this.controllers.length >= 2) {
  106180. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  106181. }
  106182. }
  106183. }
  106184. });
  106185. };
  106186. return WebVRFreeCamera;
  106187. }(BABYLON.FreeCamera));
  106188. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  106189. })(BABYLON || (BABYLON = {}));
  106190. //# sourceMappingURL=babylon.webVRCamera.js.map
  106191. var BABYLON;
  106192. (function (BABYLON) {
  106193. BABYLON.Node.AddNodeConstructor("DeviceOrientationCamera", function (name, scene) {
  106194. return function () { return new DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  106195. });
  106196. // We're mainly based on the logic defined into the FreeCamera code
  106197. /**
  106198. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  106199. * being tilted forward or back and left or right.
  106200. */
  106201. var DeviceOrientationCamera = /** @class */ (function (_super) {
  106202. __extends(DeviceOrientationCamera, _super);
  106203. /**
  106204. * Creates a new device orientation camera
  106205. * @param name The name of the camera
  106206. * @param position The start position camera
  106207. * @param scene The scene the camera belongs to
  106208. */
  106209. function DeviceOrientationCamera(name, position, scene) {
  106210. var _this = _super.call(this, name, position, scene) || this;
  106211. _this._quaternionCache = new BABYLON.Quaternion();
  106212. _this.inputs.addDeviceOrientation();
  106213. return _this;
  106214. }
  106215. /**
  106216. * Gets the current instance class name ("DeviceOrientationCamera").
  106217. * This helps avoiding instanceof at run time.
  106218. * @returns the class name
  106219. */
  106220. DeviceOrientationCamera.prototype.getClassName = function () {
  106221. return "DeviceOrientationCamera";
  106222. };
  106223. /**
  106224. * @hidden
  106225. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  106226. */
  106227. DeviceOrientationCamera.prototype._checkInputs = function () {
  106228. _super.prototype._checkInputs.call(this);
  106229. this._quaternionCache.copyFrom(this.rotationQuaternion);
  106230. if (this._initialQuaternion) {
  106231. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  106232. }
  106233. };
  106234. /**
  106235. * Reset the camera to its default orientation on the specified axis only.
  106236. * @param axis The axis to reset
  106237. */
  106238. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  106239. var _this = this;
  106240. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  106241. //can only work if this camera has a rotation quaternion already.
  106242. if (!this.rotationQuaternion) {
  106243. return;
  106244. }
  106245. if (!this._initialQuaternion) {
  106246. this._initialQuaternion = new BABYLON.Quaternion();
  106247. }
  106248. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  106249. ['x', 'y', 'z'].forEach(function (axisName) {
  106250. if (!axis[axisName]) {
  106251. _this._initialQuaternion[axisName] = 0;
  106252. }
  106253. else {
  106254. _this._initialQuaternion[axisName] *= -1;
  106255. }
  106256. });
  106257. this._initialQuaternion.normalize();
  106258. //force rotation update
  106259. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  106260. };
  106261. return DeviceOrientationCamera;
  106262. }(BABYLON.FreeCamera));
  106263. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  106264. })(BABYLON || (BABYLON = {}));
  106265. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  106266. var BABYLON;
  106267. (function (BABYLON) {
  106268. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) {
  106269. return function () { return new VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  106270. });
  106271. /**
  106272. * Camera used to simulate VR rendering (based on FreeCamera)
  106273. * @see http://doc.babylonjs.com/babylon101/cameras#vr-device-orientation-cameras
  106274. */
  106275. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  106276. __extends(VRDeviceOrientationFreeCamera, _super);
  106277. /**
  106278. * Creates a new VRDeviceOrientationFreeCamera
  106279. * @param name defines camera name
  106280. * @param position defines the start position of the camera
  106281. * @param scene defines the scene the camera belongs to
  106282. * @param compensateDistortion defines if the camera needs to compensate the lens distorsion
  106283. * @param vrCameraMetrics defines the vr metrics associated to the camera
  106284. */
  106285. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  106286. if (compensateDistortion === void 0) { compensateDistortion = true; }
  106287. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  106288. var _this = _super.call(this, name, position, scene) || this;
  106289. vrCameraMetrics.compensateDistortion = compensateDistortion;
  106290. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  106291. return _this;
  106292. }
  106293. /**
  106294. * Gets camera class name
  106295. * @returns VRDeviceOrientationFreeCamera
  106296. */
  106297. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  106298. return "VRDeviceOrientationFreeCamera";
  106299. };
  106300. return VRDeviceOrientationFreeCamera;
  106301. }(BABYLON.DeviceOrientationCamera));
  106302. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  106303. })(BABYLON || (BABYLON = {}));
  106304. //# sourceMappingURL=babylon.vrDeviceOrientationFreeCamera.js.map
  106305. var BABYLON;
  106306. (function (BABYLON) {
  106307. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) {
  106308. return function () { return new VRDeviceOrientationArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  106309. });
  106310. /**
  106311. * Camera used to simulate VR rendering (based on ArcRotateCamera)
  106312. * @see http://doc.babylonjs.com/babylon101/cameras#vr-device-orientation-cameras
  106313. */
  106314. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  106315. __extends(VRDeviceOrientationArcRotateCamera, _super);
  106316. /**
  106317. * Creates a new VRDeviceOrientationArcRotateCamera
  106318. * @param name defines camera name
  106319. * @param alpha defines the camera rotation along the logitudinal axis
  106320. * @param beta defines the camera rotation along the latitudinal axis
  106321. * @param radius defines the camera distance from its target
  106322. * @param target defines the camera target
  106323. * @param scene defines the scene the camera belongs to
  106324. * @param compensateDistortion defines if the camera needs to compensate the lens distorsion
  106325. * @param vrCameraMetrics defines the vr metrics associated to the camera
  106326. */
  106327. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  106328. if (compensateDistortion === void 0) { compensateDistortion = true; }
  106329. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  106330. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  106331. vrCameraMetrics.compensateDistortion = compensateDistortion;
  106332. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  106333. _this.inputs.addVRDeviceOrientation();
  106334. return _this;
  106335. }
  106336. /**
  106337. * Gets camera class name
  106338. * @returns VRDeviceOrientationArcRotateCamera
  106339. */
  106340. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  106341. return "VRDeviceOrientationArcRotateCamera";
  106342. };
  106343. return VRDeviceOrientationArcRotateCamera;
  106344. }(BABYLON.ArcRotateCamera));
  106345. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  106346. })(BABYLON || (BABYLON = {}));
  106347. //# sourceMappingURL=babylon.vrDeviceOrientationArcRotateCamera.js.map
  106348. var BABYLON;
  106349. (function (BABYLON) {
  106350. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationGamepadCamera", function (name, scene) {
  106351. return function () { return new VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  106352. });
  106353. /**
  106354. * Camera used to simulate VR rendering (based on VRDeviceOrientationFreeCamera)
  106355. * @see http://doc.babylonjs.com/babylon101/cameras#vr-device-orientation-cameras
  106356. */
  106357. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  106358. __extends(VRDeviceOrientationGamepadCamera, _super);
  106359. /**
  106360. * Creates a new VRDeviceOrientationGamepadCamera
  106361. * @param name defines camera name
  106362. * @param position defines the start position of the camera
  106363. * @param scene defines the scene the camera belongs to
  106364. * @param compensateDistortion defines if the camera needs to compensate the lens distorsion
  106365. * @param vrCameraMetrics defines the vr metrics associated to the camera
  106366. */
  106367. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  106368. if (compensateDistortion === void 0) { compensateDistortion = true; }
  106369. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  106370. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  106371. _this.inputs.addGamepad();
  106372. return _this;
  106373. }
  106374. /**
  106375. * Gets camera class name
  106376. * @returns VRDeviceOrientationGamepadCamera
  106377. */
  106378. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  106379. return "VRDeviceOrientationGamepadCamera";
  106380. };
  106381. return VRDeviceOrientationGamepadCamera;
  106382. }(BABYLON.VRDeviceOrientationFreeCamera));
  106383. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  106384. })(BABYLON || (BABYLON = {}));
  106385. //# sourceMappingURL=babylon.vrDeviceOrientationGamepadCamera.js.map
  106386. var BABYLON;
  106387. (function (BABYLON) {
  106388. var VRExperienceHelperGazer = /** @class */ (function () {
  106389. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  106390. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  106391. this.scene = scene;
  106392. /** @hidden */
  106393. this._pointerDownOnMeshAsked = false;
  106394. /** @hidden */
  106395. this._isActionableMesh = false;
  106396. /** @hidden */
  106397. this._teleportationRequestInitiated = false;
  106398. /** @hidden */
  106399. this._teleportationBackRequestInitiated = false;
  106400. /** @hidden */
  106401. this._rotationRightAsked = false;
  106402. /** @hidden */
  106403. this._rotationLeftAsked = false;
  106404. /** @hidden */
  106405. this._dpadPressed = true;
  106406. /** @hidden */
  106407. this._activePointer = false;
  106408. this._id = VRExperienceHelperGazer._idCounter++;
  106409. // Gaze tracker
  106410. if (!gazeTrackerToClone) {
  106411. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  106412. this._gazeTracker.bakeCurrentTransformIntoVertices();
  106413. this._gazeTracker.isPickable = false;
  106414. this._gazeTracker.isVisible = false;
  106415. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  106416. targetMat.specularColor = BABYLON.Color3.Black();
  106417. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  106418. targetMat.backFaceCulling = false;
  106419. this._gazeTracker.material = targetMat;
  106420. }
  106421. else {
  106422. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  106423. }
  106424. }
  106425. /** @hidden */
  106426. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  106427. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  106428. };
  106429. /** @hidden */
  106430. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  106431. this._pointerDownOnMeshAsked = true;
  106432. if (this._currentHit) {
  106433. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  106434. }
  106435. };
  106436. /** @hidden */
  106437. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  106438. if (this._currentHit) {
  106439. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  106440. }
  106441. this._pointerDownOnMeshAsked = false;
  106442. };
  106443. /** @hidden */
  106444. VRExperienceHelperGazer.prototype._activatePointer = function () {
  106445. this._activePointer = true;
  106446. };
  106447. /** @hidden */
  106448. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  106449. this._activePointer = false;
  106450. };
  106451. /** @hidden */
  106452. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  106453. if (distance === void 0) { distance = 100; }
  106454. };
  106455. VRExperienceHelperGazer.prototype.dispose = function () {
  106456. this._interactionsEnabled = false;
  106457. this._teleportationEnabled = false;
  106458. if (this._gazeTracker) {
  106459. this._gazeTracker.dispose();
  106460. }
  106461. };
  106462. VRExperienceHelperGazer._idCounter = 0;
  106463. return VRExperienceHelperGazer;
  106464. }());
  106465. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  106466. __extends(VRExperienceHelperControllerGazer, _super);
  106467. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  106468. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  106469. _this.webVRController = webVRController;
  106470. // Laser pointer
  106471. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  106472. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  106473. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  106474. laserPointerMaterial.alpha = 0.6;
  106475. _this._laserPointer.material = laserPointerMaterial;
  106476. _this._laserPointer.rotation.x = Math.PI / 2;
  106477. _this._laserPointer.position.z = -0.5;
  106478. _this._laserPointer.isVisible = false;
  106479. _this._laserPointer.isPickable = false;
  106480. if (!webVRController.mesh) {
  106481. // Create an empty mesh that is used prior to loading the high quality model
  106482. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  106483. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  106484. preloadPointerPose.rotation.x = -0.7;
  106485. preloadMesh.addChild(preloadPointerPose);
  106486. webVRController.attachToMesh(preloadMesh);
  106487. }
  106488. _this._setLaserPointerParent(webVRController.mesh);
  106489. _this._meshAttachedObserver = webVRController._meshAttachedObservable.add(function (mesh) {
  106490. _this._setLaserPointerParent(mesh);
  106491. });
  106492. return _this;
  106493. }
  106494. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  106495. return this.webVRController.getForwardRay(length);
  106496. };
  106497. /** @hidden */
  106498. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  106499. _super.prototype._activatePointer.call(this);
  106500. this._laserPointer.isVisible = true;
  106501. };
  106502. /** @hidden */
  106503. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  106504. _super.prototype._deactivatePointer.call(this);
  106505. this._laserPointer.isVisible = false;
  106506. };
  106507. /** @hidden */
  106508. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  106509. this._laserPointer.material.emissiveColor = color;
  106510. };
  106511. /** @hidden */
  106512. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  106513. var makeNotPick = function (root) {
  106514. root.isPickable = false;
  106515. root.getChildMeshes().forEach(function (c) {
  106516. makeNotPick(c);
  106517. });
  106518. };
  106519. makeNotPick(mesh);
  106520. var meshChildren = mesh.getChildren(undefined, false);
  106521. var laserParent = mesh;
  106522. this.webVRController._pointingPoseNode = null;
  106523. for (var i = 0; i < meshChildren.length; i++) {
  106524. if (meshChildren[i].name && meshChildren[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  106525. laserParent = meshChildren[i];
  106526. this.webVRController._pointingPoseNode = laserParent;
  106527. break;
  106528. }
  106529. }
  106530. this._laserPointer.parent = laserParent;
  106531. };
  106532. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  106533. if (distance === void 0) { distance = 100; }
  106534. this._laserPointer.scaling.y = distance;
  106535. this._laserPointer.position.z = -distance / 2;
  106536. };
  106537. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  106538. _super.prototype.dispose.call(this);
  106539. this._laserPointer.dispose();
  106540. if (this._meshAttachedObserver) {
  106541. this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver);
  106542. }
  106543. };
  106544. return VRExperienceHelperControllerGazer;
  106545. }(VRExperienceHelperGazer));
  106546. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  106547. __extends(VRExperienceHelperCameraGazer, _super);
  106548. function VRExperienceHelperCameraGazer(getCamera, scene) {
  106549. var _this = _super.call(this, scene) || this;
  106550. _this.getCamera = getCamera;
  106551. return _this;
  106552. }
  106553. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  106554. var camera = this.getCamera();
  106555. if (camera) {
  106556. return camera.getForwardRay(length);
  106557. }
  106558. else {
  106559. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  106560. }
  106561. };
  106562. return VRExperienceHelperCameraGazer;
  106563. }(VRExperienceHelperGazer));
  106564. /**
  106565. * Helps to quickly add VR support to an existing scene.
  106566. * See http://doc.babylonjs.com/how_to/webvr_helper
  106567. */
  106568. var VRExperienceHelper = /** @class */ (function () {
  106569. /**
  106570. * Instantiates a VRExperienceHelper.
  106571. * Helps to quickly add VR support to an existing scene.
  106572. * @param scene The scene the VRExperienceHelper belongs to.
  106573. * @param webVROptions Options to modify the vr experience helper's behavior.
  106574. */
  106575. function VRExperienceHelper(scene,
  106576. /** Options to modify the vr experience helper's behavior. */
  106577. webVROptions) {
  106578. if (webVROptions === void 0) { webVROptions = {}; }
  106579. var _this = this;
  106580. this.webVROptions = webVROptions;
  106581. // Can the system support WebVR, even if a headset isn't plugged in?
  106582. this._webVRsupported = false;
  106583. // If WebVR is supported, is a headset plugged in and are we ready to present?
  106584. this._webVRready = false;
  106585. // Are we waiting for the requestPresent callback to complete?
  106586. this._webVRrequesting = false;
  106587. // Are we presenting to the headset right now? (this is the vrDevice state)
  106588. this._webVRpresenting = false;
  106589. // Are we presenting in the fullscreen fallback?
  106590. this._fullscreenVRpresenting = false;
  106591. /**
  106592. * Observable raised when entering VR.
  106593. */
  106594. this.onEnteringVRObservable = new BABYLON.Observable();
  106595. /**
  106596. * Observable raised when exiting VR.
  106597. */
  106598. this.onExitingVRObservable = new BABYLON.Observable();
  106599. /**
  106600. * Observable raised when controller mesh is loaded.
  106601. */
  106602. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  106603. this._useCustomVRButton = false;
  106604. this._teleportationRequested = false;
  106605. this._teleportActive = false;
  106606. this._floorMeshesCollection = [];
  106607. this._rotationAllowed = true;
  106608. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  106609. this._isDefaultTeleportationTarget = true;
  106610. this._teleportationFillColor = "#444444";
  106611. this._teleportationBorderColor = "#FFFFFF";
  106612. this._rotationAngle = 0;
  106613. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  106614. this._padSensibilityUp = 0.65;
  106615. this._padSensibilityDown = 0.35;
  106616. this._leftController = null;
  106617. this._rightController = null;
  106618. /**
  106619. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  106620. */
  106621. this.onNewMeshSelected = new BABYLON.Observable();
  106622. /**
  106623. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  106624. */
  106625. this.onNewMeshPicked = new BABYLON.Observable();
  106626. /**
  106627. * Observable raised before camera teleportation
  106628. */
  106629. this.onBeforeCameraTeleport = new BABYLON.Observable();
  106630. /**
  106631. * Observable raised after camera teleportation
  106632. */
  106633. this.onAfterCameraTeleport = new BABYLON.Observable();
  106634. /**
  106635. * Observable raised when current selected mesh gets unselected
  106636. */
  106637. this.onSelectedMeshUnselected = new BABYLON.Observable();
  106638. /**
  106639. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  106640. */
  106641. this.teleportationEnabled = true;
  106642. this._teleportationInitialized = false;
  106643. this._interactionsEnabled = false;
  106644. this._interactionsRequested = false;
  106645. this._displayGaze = true;
  106646. this._displayLaserPointer = true;
  106647. /**
  106648. * If the gaze trackers scale should be updated to be constant size when pointing at near/far meshes
  106649. */
  106650. this.updateGazeTrackerScale = true;
  106651. this._onResize = function () {
  106652. _this.moveButtonToBottomRight();
  106653. if (_this._fullscreenVRpresenting && _this._webVRready) {
  106654. _this.exitVR();
  106655. }
  106656. };
  106657. this._onFullscreenChange = function () {
  106658. if (document.fullscreen !== undefined) {
  106659. _this._fullscreenVRpresenting = document.fullscreen;
  106660. }
  106661. else if (document.mozFullScreen !== undefined) {
  106662. _this._fullscreenVRpresenting = document.mozFullScreen;
  106663. }
  106664. else if (document.webkitIsFullScreen !== undefined) {
  106665. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  106666. }
  106667. else if (document.msIsFullScreen !== undefined) {
  106668. _this._fullscreenVRpresenting = document.msIsFullScreen;
  106669. }
  106670. else if (document.msFullscreenElement !== undefined) {
  106671. _this._fullscreenVRpresenting = document.msFullscreenElement;
  106672. }
  106673. if (!_this._fullscreenVRpresenting && _this._canvas) {
  106674. _this.exitVR();
  106675. if (!_this._useCustomVRButton) {
  106676. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  106677. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  106678. }
  106679. }
  106680. };
  106681. this._cachedAngularSensibility = { angularSensibilityX: null, angularSensibilityY: null, angularSensibility: null };
  106682. this.beforeRender = function () {
  106683. if (_this._leftController && _this._leftController._activePointer) {
  106684. _this._castRayAndSelectObject(_this._leftController);
  106685. }
  106686. if (_this._rightController && _this._rightController._activePointer) {
  106687. _this._castRayAndSelectObject(_this._rightController);
  106688. }
  106689. if (_this._noControllerIsActive) {
  106690. _this._castRayAndSelectObject(_this._cameraGazer);
  106691. }
  106692. else {
  106693. _this._cameraGazer._gazeTracker.isVisible = false;
  106694. }
  106695. };
  106696. this._onNewGamepadConnected = function (gamepad) {
  106697. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  106698. if (gamepad.leftStick) {
  106699. gamepad.onleftstickchanged(function (stickValues) {
  106700. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  106701. // Listening to classic/xbox gamepad only if no VR controller is active
  106702. if ((!_this._leftController && !_this._rightController) ||
  106703. ((_this._leftController && !_this._leftController._activePointer) &&
  106704. (_this._rightController && !_this._rightController._activePointer))) {
  106705. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  106706. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  106707. }
  106708. }
  106709. });
  106710. }
  106711. if (gamepad.rightStick) {
  106712. gamepad.onrightstickchanged(function (stickValues) {
  106713. if (_this._teleportationInitialized) {
  106714. _this._checkRotate(stickValues, _this._cameraGazer);
  106715. }
  106716. });
  106717. }
  106718. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  106719. gamepad.onbuttondown(function (buttonPressed) {
  106720. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  106721. _this._cameraGazer._selectionPointerDown();
  106722. }
  106723. });
  106724. gamepad.onbuttonup(function (buttonPressed) {
  106725. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  106726. _this._cameraGazer._selectionPointerUp();
  106727. }
  106728. });
  106729. }
  106730. }
  106731. else {
  106732. var webVRController = gamepad;
  106733. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  106734. if (webVRController.hand === "right" || (_this._leftController && _this._leftController.webVRController != webVRController)) {
  106735. _this._rightController = controller;
  106736. }
  106737. else {
  106738. _this._leftController = controller;
  106739. }
  106740. _this._tryEnableInteractionOnController(controller);
  106741. }
  106742. };
  106743. // 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
  106744. this._tryEnableInteractionOnController = function (controller) {
  106745. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  106746. _this._enableInteractionOnController(controller);
  106747. }
  106748. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  106749. _this._enableTeleportationOnController(controller);
  106750. }
  106751. };
  106752. this._onNewGamepadDisconnected = function (gamepad) {
  106753. if (gamepad instanceof BABYLON.WebVRController) {
  106754. if (gamepad.hand === "left" && _this._leftController != null) {
  106755. _this._leftController.dispose();
  106756. _this._leftController = null;
  106757. }
  106758. if (gamepad.hand === "right" && _this._rightController != null) {
  106759. _this._rightController.dispose();
  106760. _this._rightController = null;
  106761. }
  106762. }
  106763. };
  106764. this._workingVector = BABYLON.Vector3.Zero();
  106765. this._workingQuaternion = BABYLON.Quaternion.Identity();
  106766. this._workingMatrix = BABYLON.Matrix.Identity();
  106767. this._scene = scene;
  106768. this._canvas = scene.getEngine().getRenderingCanvas();
  106769. // Parse options
  106770. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  106771. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  106772. }
  106773. if (webVROptions.createDeviceOrientationCamera === undefined) {
  106774. webVROptions.createDeviceOrientationCamera = true;
  106775. }
  106776. if (webVROptions.laserToggle === undefined) {
  106777. webVROptions.laserToggle = true;
  106778. }
  106779. if (webVROptions.defaultHeight === undefined) {
  106780. webVROptions.defaultHeight = 1.7;
  106781. }
  106782. if (webVROptions.useCustomVRButton) {
  106783. this._useCustomVRButton = true;
  106784. if (webVROptions.customVRButton) {
  106785. this._btnVR = webVROptions.customVRButton;
  106786. }
  106787. }
  106788. if (webVROptions.rayLength) {
  106789. this._rayLength = webVROptions.rayLength;
  106790. }
  106791. this._defaultHeight = webVROptions.defaultHeight;
  106792. if (webVROptions.positionScale) {
  106793. this._rayLength *= webVROptions.positionScale;
  106794. this._defaultHeight *= webVROptions.positionScale;
  106795. }
  106796. this._hasEnteredVR = false;
  106797. // Set position
  106798. if (this._scene.activeCamera) {
  106799. this._position = this._scene.activeCamera.position.clone();
  106800. }
  106801. else {
  106802. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  106803. }
  106804. // Set non-vr camera
  106805. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  106806. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  106807. // Copy data from existing camera
  106808. if (this._scene.activeCamera) {
  106809. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  106810. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  106811. // Set rotation from previous camera
  106812. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  106813. var targetCamera = this._scene.activeCamera;
  106814. if (targetCamera.rotationQuaternion) {
  106815. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  106816. }
  106817. else {
  106818. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  106819. }
  106820. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  106821. }
  106822. }
  106823. this._scene.activeCamera = this._deviceOrientationCamera;
  106824. if (this._canvas) {
  106825. this._scene.activeCamera.attachControl(this._canvas);
  106826. }
  106827. }
  106828. else {
  106829. this._existingCamera = this._scene.activeCamera;
  106830. }
  106831. // Create VR cameras
  106832. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  106833. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  106834. this._vrDeviceOrientationCamera.angularSensibility = Number.MAX_VALUE;
  106835. }
  106836. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  106837. this._webVRCamera.useStandingMatrix();
  106838. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  106839. // Create default button
  106840. if (!this._useCustomVRButton) {
  106841. this._btnVR = document.createElement("BUTTON");
  106842. this._btnVR.className = "babylonVRicon";
  106843. this._btnVR.id = "babylonVRiconbtn";
  106844. this._btnVR.title = "Click to switch to VR";
  106845. 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) }";
  106846. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  106847. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  106848. // css += ".babylonVRicon.vrdisplaysupported { }";
  106849. // css += ".babylonVRicon.vrdisplayready { }";
  106850. // css += ".babylonVRicon.vrdisplayrequesting { }";
  106851. var style = document.createElement('style');
  106852. style.appendChild(document.createTextNode(css));
  106853. document.getElementsByTagName('head')[0].appendChild(style);
  106854. this.moveButtonToBottomRight();
  106855. }
  106856. // VR button click event
  106857. if (this._btnVR) {
  106858. this._btnVR.addEventListener("click", function () {
  106859. if (!_this.isInVRMode) {
  106860. _this.enterVR();
  106861. }
  106862. else {
  106863. _this.exitVR();
  106864. }
  106865. });
  106866. }
  106867. // Window events
  106868. window.addEventListener("resize", this._onResize);
  106869. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  106870. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  106871. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  106872. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  106873. document.onmsfullscreenchange = this._onFullscreenChange;
  106874. // Display vr button when headset is connected
  106875. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  106876. this.displayVRButton();
  106877. }
  106878. else {
  106879. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  106880. if (e.vrDisplay) {
  106881. _this.displayVRButton();
  106882. }
  106883. });
  106884. }
  106885. // Exiting VR mode using 'ESC' key on desktop
  106886. this._onKeyDown = function (event) {
  106887. if (event.keyCode === 27 && _this.isInVRMode) {
  106888. _this.exitVR();
  106889. }
  106890. };
  106891. document.addEventListener("keydown", this._onKeyDown);
  106892. // Exiting VR mode double tapping the touch screen
  106893. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  106894. if (_this.isInVRMode) {
  106895. _this.exitVR();
  106896. if (_this._fullscreenVRpresenting) {
  106897. _this._scene.getEngine().switchFullscreen(true);
  106898. }
  106899. }
  106900. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  106901. // Listen for WebVR display changes
  106902. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  106903. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  106904. this._onVRRequestPresentStart = function () {
  106905. _this._webVRrequesting = true;
  106906. _this.updateButtonVisibility();
  106907. };
  106908. this._onVRRequestPresentComplete = function (success) {
  106909. _this._webVRrequesting = false;
  106910. _this.updateButtonVisibility();
  106911. };
  106912. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  106913. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  106914. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  106915. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  106916. scene.onDisposeObservable.add(function () {
  106917. _this.dispose();
  106918. });
  106919. // Gamepad connection events
  106920. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  106921. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  106922. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  106923. this.updateButtonVisibility();
  106924. //create easing functions
  106925. this._circleEase = new BABYLON.CircleEase();
  106926. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  106927. if (this.webVROptions.floorMeshes) {
  106928. this.enableTeleportation({ floorMeshes: this.webVROptions.floorMeshes });
  106929. }
  106930. }
  106931. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  106932. /** Return this.onEnteringVRObservable
  106933. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  106934. */
  106935. get: function () {
  106936. return this.onEnteringVRObservable;
  106937. },
  106938. enumerable: true,
  106939. configurable: true
  106940. });
  106941. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  106942. /** Return this.onExitingVRObservable
  106943. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  106944. */
  106945. get: function () {
  106946. return this.onExitingVRObservable;
  106947. },
  106948. enumerable: true,
  106949. configurable: true
  106950. });
  106951. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  106952. /** Return this.onControllerMeshLoadedObservable
  106953. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  106954. */
  106955. get: function () {
  106956. return this.onControllerMeshLoadedObservable;
  106957. },
  106958. enumerable: true,
  106959. configurable: true
  106960. });
  106961. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  106962. /**
  106963. * The mesh used to display where the user is going to teleport.
  106964. */
  106965. get: function () {
  106966. return this._teleportationTarget;
  106967. },
  106968. /**
  106969. * Sets the mesh to be used to display where the user is going to teleport.
  106970. */
  106971. set: function (value) {
  106972. if (value) {
  106973. value.name = "teleportationTarget";
  106974. this._isDefaultTeleportationTarget = false;
  106975. this._teleportationTarget = value;
  106976. }
  106977. },
  106978. enumerable: true,
  106979. configurable: true
  106980. });
  106981. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  106982. /**
  106983. * 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
  106984. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  106985. * See http://doc.babylonjs.com/resources/baking_transformations
  106986. */
  106987. get: function () {
  106988. return this._cameraGazer._gazeTracker;
  106989. },
  106990. set: function (value) {
  106991. if (value) {
  106992. // Dispose of existing meshes
  106993. if (this._cameraGazer._gazeTracker) {
  106994. this._cameraGazer._gazeTracker.dispose();
  106995. }
  106996. if (this._leftController && this._leftController._gazeTracker) {
  106997. this._leftController._gazeTracker.dispose();
  106998. }
  106999. if (this._rightController && this._rightController._gazeTracker) {
  107000. this._rightController._gazeTracker.dispose();
  107001. }
  107002. // Set and create gaze trackers on head and controllers
  107003. this._cameraGazer._gazeTracker = value;
  107004. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  107005. this._cameraGazer._gazeTracker.isPickable = false;
  107006. this._cameraGazer._gazeTracker.isVisible = false;
  107007. this._cameraGazer._gazeTracker.name = "gazeTracker";
  107008. if (this._leftController) {
  107009. this._leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  107010. }
  107011. if (this._rightController) {
  107012. this._rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  107013. }
  107014. }
  107015. },
  107016. enumerable: true,
  107017. configurable: true
  107018. });
  107019. Object.defineProperty(VRExperienceHelper.prototype, "leftControllerGazeTrackerMesh", {
  107020. /**
  107021. * The gaze tracking mesh corresponding to the left controller
  107022. */
  107023. get: function () {
  107024. if (this._leftController) {
  107025. return this._leftController._gazeTracker;
  107026. }
  107027. return null;
  107028. },
  107029. enumerable: true,
  107030. configurable: true
  107031. });
  107032. Object.defineProperty(VRExperienceHelper.prototype, "rightControllerGazeTrackerMesh", {
  107033. /**
  107034. * The gaze tracking mesh corresponding to the right controller
  107035. */
  107036. get: function () {
  107037. if (this._rightController) {
  107038. return this._rightController._gazeTracker;
  107039. }
  107040. return null;
  107041. },
  107042. enumerable: true,
  107043. configurable: true
  107044. });
  107045. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  107046. /**
  107047. * If the ray of the gaze should be displayed.
  107048. */
  107049. get: function () {
  107050. return this._displayGaze;
  107051. },
  107052. /**
  107053. * Sets if the ray of the gaze should be displayed.
  107054. */
  107055. set: function (value) {
  107056. this._displayGaze = value;
  107057. if (!value) {
  107058. this._cameraGazer._gazeTracker.isVisible = false;
  107059. if (this._leftController) {
  107060. this._leftController._gazeTracker.isVisible = false;
  107061. }
  107062. if (this._rightController) {
  107063. this._rightController._gazeTracker.isVisible = false;
  107064. }
  107065. }
  107066. },
  107067. enumerable: true,
  107068. configurable: true
  107069. });
  107070. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  107071. /**
  107072. * If the ray of the LaserPointer should be displayed.
  107073. */
  107074. get: function () {
  107075. return this._displayLaserPointer;
  107076. },
  107077. /**
  107078. * Sets if the ray of the LaserPointer should be displayed.
  107079. */
  107080. set: function (value) {
  107081. this._displayLaserPointer = value;
  107082. if (!value) {
  107083. if (this._rightController) {
  107084. this._rightController._deactivatePointer();
  107085. this._rightController._gazeTracker.isVisible = false;
  107086. }
  107087. if (this._leftController) {
  107088. this._leftController._deactivatePointer();
  107089. this._leftController._gazeTracker.isVisible = false;
  107090. }
  107091. }
  107092. else {
  107093. if (this._rightController) {
  107094. this._rightController._activatePointer();
  107095. }
  107096. if (this._leftController) {
  107097. this._leftController._activatePointer();
  107098. }
  107099. }
  107100. },
  107101. enumerable: true,
  107102. configurable: true
  107103. });
  107104. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  107105. /**
  107106. * The deviceOrientationCamera used as the camera when not in VR.
  107107. */
  107108. get: function () {
  107109. return this._deviceOrientationCamera;
  107110. },
  107111. enumerable: true,
  107112. configurable: true
  107113. });
  107114. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  107115. /**
  107116. * Based on the current WebVR support, returns the current VR camera used.
  107117. */
  107118. get: function () {
  107119. if (this._webVRready) {
  107120. return this._webVRCamera;
  107121. }
  107122. else {
  107123. return this._scene.activeCamera;
  107124. }
  107125. },
  107126. enumerable: true,
  107127. configurable: true
  107128. });
  107129. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  107130. /**
  107131. * The webVRCamera which is used when in VR.
  107132. */
  107133. get: function () {
  107134. return this._webVRCamera;
  107135. },
  107136. enumerable: true,
  107137. configurable: true
  107138. });
  107139. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  107140. /**
  107141. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  107142. */
  107143. get: function () {
  107144. return this._vrDeviceOrientationCamera;
  107145. },
  107146. enumerable: true,
  107147. configurable: true
  107148. });
  107149. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  107150. get: function () {
  107151. var result = this._cameraGazer._teleportationRequestInitiated
  107152. || (this._leftController !== null && this._leftController._teleportationRequestInitiated)
  107153. || (this._rightController !== null && this._rightController._teleportationRequestInitiated);
  107154. return result;
  107155. },
  107156. enumerable: true,
  107157. configurable: true
  107158. });
  107159. // Raised when one of the controller has loaded successfully its associated default mesh
  107160. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  107161. if (this._leftController && this._leftController.webVRController == webVRController) {
  107162. if (webVRController.mesh) {
  107163. this._leftController._setLaserPointerParent(webVRController.mesh);
  107164. }
  107165. }
  107166. if (this._rightController && this._rightController.webVRController == webVRController) {
  107167. if (webVRController.mesh) {
  107168. this._rightController._setLaserPointerParent(webVRController.mesh);
  107169. }
  107170. }
  107171. try {
  107172. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  107173. }
  107174. catch (err) {
  107175. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  107176. }
  107177. };
  107178. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  107179. /**
  107180. * Gets a value indicating if we are currently in VR mode.
  107181. */
  107182. get: function () {
  107183. return this._webVRpresenting || this._fullscreenVRpresenting;
  107184. },
  107185. enumerable: true,
  107186. configurable: true
  107187. });
  107188. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  107189. var vrDisplay = this._scene.getEngine().getVRDevice();
  107190. if (vrDisplay) {
  107191. var wasPresenting = this._webVRpresenting;
  107192. this._webVRpresenting = vrDisplay.isPresenting;
  107193. if (wasPresenting && !this._webVRpresenting) {
  107194. this.exitVR();
  107195. }
  107196. }
  107197. else {
  107198. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  107199. }
  107200. this.updateButtonVisibility();
  107201. };
  107202. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  107203. this._webVRsupported = eventArgs.vrSupported;
  107204. this._webVRready = !!eventArgs.vrDisplay;
  107205. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  107206. this.updateButtonVisibility();
  107207. };
  107208. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  107209. if (this._canvas && !this._useCustomVRButton) {
  107210. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  107211. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  107212. }
  107213. };
  107214. VRExperienceHelper.prototype.displayVRButton = function () {
  107215. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  107216. document.body.appendChild(this._btnVR);
  107217. this._btnVRDisplayed = true;
  107218. }
  107219. };
  107220. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  107221. if (!this._btnVR || this._useCustomVRButton) {
  107222. return;
  107223. }
  107224. this._btnVR.className = "babylonVRicon";
  107225. if (this.isInVRMode) {
  107226. this._btnVR.className += " vrdisplaypresenting";
  107227. }
  107228. else {
  107229. if (this._webVRready) {
  107230. this._btnVR.className += " vrdisplayready";
  107231. }
  107232. if (this._webVRsupported) {
  107233. this._btnVR.className += " vrdisplaysupported";
  107234. }
  107235. if (this._webVRrequesting) {
  107236. this._btnVR.className += " vrdisplayrequesting";
  107237. }
  107238. }
  107239. };
  107240. /**
  107241. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  107242. * Otherwise, will use the fullscreen API.
  107243. */
  107244. VRExperienceHelper.prototype.enterVR = function () {
  107245. if (this.onEnteringVRObservable) {
  107246. try {
  107247. this.onEnteringVRObservable.notifyObservers(this);
  107248. }
  107249. catch (err) {
  107250. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  107251. }
  107252. }
  107253. if (this._scene.activeCamera) {
  107254. this._position = this._scene.activeCamera.position.clone();
  107255. if (this.vrDeviceOrientationCamera) {
  107256. this.vrDeviceOrientationCamera.rotation = BABYLON.Quaternion.FromRotationMatrix(this._scene.activeCamera.getWorldMatrix().getRotationMatrix()).toEulerAngles();
  107257. this.vrDeviceOrientationCamera.angularSensibility = 2000;
  107258. }
  107259. if (this.webVRCamera) {
  107260. var currentYRotation = this.webVRCamera.deviceRotationQuaternion.toEulerAngles().y;
  107261. var desiredYRotation = BABYLON.Quaternion.FromRotationMatrix(this._scene.activeCamera.getWorldMatrix().getRotationMatrix()).toEulerAngles().y;
  107262. var delta = desiredYRotation - currentYRotation;
  107263. var currentGlobalRotation = this.webVRCamera.rotationQuaternion.toEulerAngles().y;
  107264. this.webVRCamera.rotationQuaternion = BABYLON.Quaternion.FromEulerAngles(0, currentGlobalRotation + delta, 0);
  107265. }
  107266. // make sure that we return to the last active camera
  107267. this._existingCamera = this._scene.activeCamera;
  107268. // Remove and cache angular sensability to avoid camera rotation when in VR
  107269. if (this._existingCamera.angularSensibilityX) {
  107270. this._cachedAngularSensibility.angularSensibilityX = this._existingCamera.angularSensibilityX;
  107271. this._existingCamera.angularSensibilityX = Number.MAX_VALUE;
  107272. }
  107273. if (this._existingCamera.angularSensibilityY) {
  107274. this._cachedAngularSensibility.angularSensibilityY = this._existingCamera.angularSensibilityY;
  107275. this._existingCamera.angularSensibilityY = Number.MAX_VALUE;
  107276. }
  107277. if (this._existingCamera.angularSensibility) {
  107278. this._cachedAngularSensibility.angularSensibility = this._existingCamera.angularSensibility;
  107279. this._existingCamera.angularSensibility = Number.MAX_VALUE;
  107280. }
  107281. }
  107282. if (this._webVRrequesting) {
  107283. return;
  107284. }
  107285. // If WebVR is supported and a headset is connected
  107286. if (this._webVRready) {
  107287. if (!this._webVRpresenting) {
  107288. this._webVRCamera.position = this._position;
  107289. this._scene.activeCamera = this._webVRCamera;
  107290. }
  107291. }
  107292. else if (this._vrDeviceOrientationCamera) {
  107293. this._vrDeviceOrientationCamera.position = this._position;
  107294. if (this._scene.activeCamera) {
  107295. this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  107296. }
  107297. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  107298. this._scene.getEngine().switchFullscreen(true);
  107299. this.updateButtonVisibility();
  107300. }
  107301. if (this._scene.activeCamera && this._canvas) {
  107302. this._scene.activeCamera.attachControl(this._canvas);
  107303. }
  107304. if (this._interactionsEnabled) {
  107305. this._scene.registerBeforeRender(this.beforeRender);
  107306. }
  107307. this._hasEnteredVR = true;
  107308. };
  107309. /**
  107310. * Attempt to exit VR, or fullscreen.
  107311. */
  107312. VRExperienceHelper.prototype.exitVR = function () {
  107313. if (this._hasEnteredVR) {
  107314. if (this.onExitingVRObservable) {
  107315. try {
  107316. this.onExitingVRObservable.notifyObservers(this);
  107317. }
  107318. catch (err) {
  107319. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  107320. }
  107321. }
  107322. if (this._webVRpresenting) {
  107323. this._scene.getEngine().disableVR();
  107324. }
  107325. if (this._scene.activeCamera) {
  107326. this._position = this._scene.activeCamera.position.clone();
  107327. }
  107328. if (this.vrDeviceOrientationCamera) {
  107329. this.vrDeviceOrientationCamera.angularSensibility = Number.MAX_VALUE;
  107330. }
  107331. if (this._deviceOrientationCamera) {
  107332. this._deviceOrientationCamera.position = this._position;
  107333. this._scene.activeCamera = this._deviceOrientationCamera;
  107334. if (this._canvas) {
  107335. this._scene.activeCamera.attachControl(this._canvas);
  107336. }
  107337. // Restore angular sensibility
  107338. if (this._cachedAngularSensibility.angularSensibilityX) {
  107339. this._deviceOrientationCamera.angularSensibilityX = this._cachedAngularSensibility.angularSensibilityX;
  107340. this._cachedAngularSensibility.angularSensibilityX = null;
  107341. }
  107342. if (this._cachedAngularSensibility.angularSensibilityY) {
  107343. this._deviceOrientationCamera.angularSensibilityY = this._cachedAngularSensibility.angularSensibilityY;
  107344. this._cachedAngularSensibility.angularSensibilityY = null;
  107345. }
  107346. if (this._cachedAngularSensibility.angularSensibility) {
  107347. this._deviceOrientationCamera.angularSensibility = this._cachedAngularSensibility.angularSensibility;
  107348. this._cachedAngularSensibility.angularSensibility = null;
  107349. }
  107350. }
  107351. else if (this._existingCamera) {
  107352. this._existingCamera.position = this._position;
  107353. this._scene.activeCamera = this._existingCamera;
  107354. // Restore angular sensibility
  107355. if (this._cachedAngularSensibility.angularSensibilityX) {
  107356. this._existingCamera.angularSensibilityX = this._cachedAngularSensibility.angularSensibilityX;
  107357. this._cachedAngularSensibility.angularSensibilityX = null;
  107358. }
  107359. if (this._cachedAngularSensibility.angularSensibilityY) {
  107360. this._existingCamera.angularSensibilityY = this._cachedAngularSensibility.angularSensibilityY;
  107361. this._cachedAngularSensibility.angularSensibilityY = null;
  107362. }
  107363. if (this._cachedAngularSensibility.angularSensibility) {
  107364. this._existingCamera.angularSensibility = this._cachedAngularSensibility.angularSensibility;
  107365. this._cachedAngularSensibility.angularSensibility = null;
  107366. }
  107367. }
  107368. this.updateButtonVisibility();
  107369. if (this._interactionsEnabled) {
  107370. this._scene.unregisterBeforeRender(this.beforeRender);
  107371. this._cameraGazer._gazeTracker.isVisible = false;
  107372. if (this._leftController) {
  107373. this._leftController._gazeTracker.isVisible = false;
  107374. }
  107375. if (this._rightController) {
  107376. this._rightController._gazeTracker.isVisible = false;
  107377. }
  107378. }
  107379. // resize to update width and height when exiting vr exits fullscreen
  107380. this._scene.getEngine().resize();
  107381. this._hasEnteredVR = false;
  107382. }
  107383. };
  107384. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  107385. /**
  107386. * The position of the vr experience helper.
  107387. */
  107388. get: function () {
  107389. return this._position;
  107390. },
  107391. /**
  107392. * Sets the position of the vr experience helper.
  107393. */
  107394. set: function (value) {
  107395. this._position = value;
  107396. if (this._scene.activeCamera) {
  107397. this._scene.activeCamera.position = value;
  107398. }
  107399. },
  107400. enumerable: true,
  107401. configurable: true
  107402. });
  107403. /**
  107404. * Enables controllers and user interactions such as selecting and object or clicking on an object.
  107405. */
  107406. VRExperienceHelper.prototype.enableInteractions = function () {
  107407. var _this = this;
  107408. if (!this._interactionsEnabled) {
  107409. this._interactionsRequested = true;
  107410. if (this._leftController) {
  107411. this._enableInteractionOnController(this._leftController);
  107412. }
  107413. if (this._rightController) {
  107414. this._enableInteractionOnController(this._rightController);
  107415. }
  107416. this.raySelectionPredicate = function (mesh) {
  107417. return mesh.isVisible && (mesh.isPickable || mesh.name === _this._floorMeshName);
  107418. };
  107419. this.meshSelectionPredicate = function (mesh) {
  107420. return true;
  107421. };
  107422. this._raySelectionPredicate = function (mesh) {
  107423. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  107424. && mesh.name.indexOf("teleportationTarget") === -1
  107425. && mesh.name.indexOf("torusTeleportation") === -1)) {
  107426. return _this.raySelectionPredicate(mesh);
  107427. }
  107428. return false;
  107429. };
  107430. this._interactionsEnabled = true;
  107431. }
  107432. };
  107433. Object.defineProperty(VRExperienceHelper.prototype, "_noControllerIsActive", {
  107434. get: function () {
  107435. return !(this._leftController && this._leftController._activePointer) && !(this._rightController && this._rightController._activePointer);
  107436. },
  107437. enumerable: true,
  107438. configurable: true
  107439. });
  107440. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  107441. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  107442. if (this._floorMeshesCollection[i].id === mesh.id) {
  107443. return true;
  107444. }
  107445. }
  107446. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  107447. return true;
  107448. }
  107449. return false;
  107450. };
  107451. /**
  107452. * Adds a floor mesh to be used for teleportation.
  107453. * @param floorMesh the mesh to be used for teleportation.
  107454. */
  107455. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  107456. if (!this._floorMeshesCollection) {
  107457. return;
  107458. }
  107459. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  107460. return;
  107461. }
  107462. this._floorMeshesCollection.push(floorMesh);
  107463. };
  107464. /**
  107465. * Removes a floor mesh from being used for teleportation.
  107466. * @param floorMesh the mesh to be removed.
  107467. */
  107468. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  107469. if (!this._floorMeshesCollection) {
  107470. return;
  107471. }
  107472. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  107473. if (meshIndex !== -1) {
  107474. this._floorMeshesCollection.splice(meshIndex, 1);
  107475. }
  107476. };
  107477. /**
  107478. * Enables interactions and teleportation using the VR controllers and gaze.
  107479. * @param vrTeleportationOptions options to modify teleportation behavior.
  107480. */
  107481. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  107482. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  107483. if (!this._teleportationInitialized) {
  107484. this._teleportationRequested = true;
  107485. this.enableInteractions();
  107486. if (vrTeleportationOptions.floorMeshName) {
  107487. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  107488. }
  107489. if (vrTeleportationOptions.floorMeshes) {
  107490. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  107491. }
  107492. if (this._leftController != null) {
  107493. this._enableTeleportationOnController(this._leftController);
  107494. }
  107495. if (this._rightController != null) {
  107496. this._enableTeleportationOnController(this._rightController);
  107497. }
  107498. // Creates an image processing post process for the vignette not relying
  107499. // on the main scene configuration for image processing to reduce setup and spaces
  107500. // (gamma/linear) conflicts.
  107501. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  107502. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  107503. imageProcessingConfiguration.vignetteEnabled = true;
  107504. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  107505. this._webVRCamera.detachPostProcess(this._postProcessMove);
  107506. this._teleportationInitialized = true;
  107507. if (this._isDefaultTeleportationTarget) {
  107508. this._createTeleportationCircles();
  107509. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  107510. }
  107511. }
  107512. };
  107513. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  107514. var _this = this;
  107515. var controllerMesh = controller.webVRController.mesh;
  107516. if (controllerMesh) {
  107517. controller._interactionsEnabled = true;
  107518. controller._activatePointer();
  107519. if (this.webVROptions.laserToggle) {
  107520. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  107521. // Enabling / disabling laserPointer
  107522. if (_this._displayLaserPointer && stateObject.value === 1) {
  107523. if (controller._activePointer) {
  107524. controller._deactivatePointer();
  107525. }
  107526. else {
  107527. controller._activatePointer();
  107528. }
  107529. if (_this.displayGaze) {
  107530. controller._gazeTracker.isVisible = controller._activePointer;
  107531. }
  107532. }
  107533. });
  107534. }
  107535. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  107536. var gazer = controller;
  107537. if (_this._noControllerIsActive) {
  107538. gazer = _this._cameraGazer;
  107539. }
  107540. if (!gazer._pointerDownOnMeshAsked) {
  107541. if (stateObject.value > _this._padSensibilityUp) {
  107542. gazer._selectionPointerDown();
  107543. }
  107544. }
  107545. else if (stateObject.value < _this._padSensibilityDown) {
  107546. gazer._selectionPointerUp();
  107547. }
  107548. });
  107549. }
  107550. };
  107551. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  107552. // Dont teleport if another gaze already requested teleportation
  107553. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  107554. return;
  107555. }
  107556. if (!gazer._teleportationRequestInitiated) {
  107557. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  107558. gazer._activatePointer();
  107559. gazer._teleportationRequestInitiated = true;
  107560. }
  107561. }
  107562. else {
  107563. // Listening to the proper controller values changes to confirm teleportation
  107564. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  107565. if (this._teleportActive) {
  107566. this.teleportCamera(this._haloCenter);
  107567. }
  107568. gazer._teleportationRequestInitiated = false;
  107569. }
  107570. }
  107571. };
  107572. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  107573. // Only rotate when user is not currently selecting a teleportation location
  107574. if (gazer._teleportationRequestInitiated) {
  107575. return;
  107576. }
  107577. if (!gazer._rotationLeftAsked) {
  107578. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  107579. gazer._rotationLeftAsked = true;
  107580. if (this._rotationAllowed) {
  107581. this._rotateCamera(false);
  107582. }
  107583. }
  107584. }
  107585. else {
  107586. if (stateObject.x > -this._padSensibilityDown) {
  107587. gazer._rotationLeftAsked = false;
  107588. }
  107589. }
  107590. if (!gazer._rotationRightAsked) {
  107591. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  107592. gazer._rotationRightAsked = true;
  107593. if (this._rotationAllowed) {
  107594. this._rotateCamera(true);
  107595. }
  107596. }
  107597. }
  107598. else {
  107599. if (stateObject.x < this._padSensibilityDown) {
  107600. gazer._rotationRightAsked = false;
  107601. }
  107602. }
  107603. };
  107604. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  107605. // Only teleport backwards when user is not currently selecting a teleportation location
  107606. if (gazer._teleportationRequestInitiated) {
  107607. return;
  107608. }
  107609. // Teleport backwards
  107610. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  107611. if (!gazer._teleportationBackRequestInitiated) {
  107612. if (!this.currentVRCamera) {
  107613. return;
  107614. }
  107615. // Get rotation and position of the current camera
  107616. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  107617. var position = this.currentVRCamera.position;
  107618. // If the camera has device position, use that instead
  107619. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  107620. rotation = this.currentVRCamera.deviceRotationQuaternion;
  107621. position = this.currentVRCamera.devicePosition;
  107622. }
  107623. // Get matrix with only the y rotation of the device rotation
  107624. rotation.toEulerAnglesToRef(this._workingVector);
  107625. this._workingVector.z = 0;
  107626. this._workingVector.x = 0;
  107627. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  107628. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  107629. // Rotate backwards ray by device rotation to cast at the ground behind the user
  107630. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  107631. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  107632. var ray = new BABYLON.Ray(position, this._workingVector);
  107633. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  107634. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  107635. this.teleportCamera(hit.pickedPoint);
  107636. }
  107637. gazer._teleportationBackRequestInitiated = true;
  107638. }
  107639. }
  107640. else {
  107641. gazer._teleportationBackRequestInitiated = false;
  107642. }
  107643. };
  107644. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  107645. var _this = this;
  107646. var controllerMesh = controller.webVRController.mesh;
  107647. if (controllerMesh) {
  107648. if (!controller._interactionsEnabled) {
  107649. this._enableInteractionOnController(controller);
  107650. }
  107651. controller._interactionsEnabled = true;
  107652. controller._teleportationEnabled = true;
  107653. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  107654. controller._dpadPressed = false;
  107655. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  107656. controller._dpadPressed = stateObject.pressed;
  107657. if (!controller._dpadPressed) {
  107658. controller._rotationLeftAsked = false;
  107659. controller._rotationRightAsked = false;
  107660. controller._teleportationBackRequestInitiated = false;
  107661. }
  107662. });
  107663. }
  107664. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  107665. if (_this.teleportationEnabled) {
  107666. _this._checkTeleportBackwards(stateObject, controller);
  107667. _this._checkTeleportWithRay(stateObject, controller);
  107668. }
  107669. _this._checkRotate(stateObject, controller);
  107670. });
  107671. }
  107672. };
  107673. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  107674. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  107675. this._teleportationTarget.isPickable = false;
  107676. var length = 512;
  107677. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  107678. dynamicTexture.hasAlpha = true;
  107679. var context = dynamicTexture.getContext();
  107680. var centerX = length / 2;
  107681. var centerY = length / 2;
  107682. var radius = 200;
  107683. context.beginPath();
  107684. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  107685. context.fillStyle = this._teleportationFillColor;
  107686. context.fill();
  107687. context.lineWidth = 10;
  107688. context.strokeStyle = this._teleportationBorderColor;
  107689. context.stroke();
  107690. context.closePath();
  107691. dynamicTexture.update();
  107692. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  107693. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  107694. this._teleportationTarget.material = teleportationCircleMaterial;
  107695. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  107696. torus.isPickable = false;
  107697. torus.parent = this._teleportationTarget;
  107698. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  107699. var keys = [];
  107700. keys.push({
  107701. frame: 0,
  107702. value: 0
  107703. });
  107704. keys.push({
  107705. frame: 30,
  107706. value: 0.4
  107707. });
  107708. keys.push({
  107709. frame: 60,
  107710. value: 0
  107711. });
  107712. animationInnerCircle.setKeys(keys);
  107713. var easingFunction = new BABYLON.SineEase();
  107714. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  107715. animationInnerCircle.setEasingFunction(easingFunction);
  107716. torus.animations = [];
  107717. torus.animations.push(animationInnerCircle);
  107718. this._scene.beginAnimation(torus, 0, 60, true);
  107719. this._hideTeleportationTarget();
  107720. };
  107721. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  107722. this._teleportActive = true;
  107723. if (this._teleportationInitialized) {
  107724. this._teleportationTarget.isVisible = true;
  107725. if (this._isDefaultTeleportationTarget) {
  107726. this._teleportationTarget.getChildren()[0].isVisible = true;
  107727. }
  107728. }
  107729. };
  107730. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  107731. this._teleportActive = false;
  107732. if (this._teleportationInitialized) {
  107733. this._teleportationTarget.isVisible = false;
  107734. if (this._isDefaultTeleportationTarget) {
  107735. this._teleportationTarget.getChildren()[0].isVisible = false;
  107736. }
  107737. }
  107738. };
  107739. VRExperienceHelper.prototype._rotateCamera = function (right) {
  107740. var _this = this;
  107741. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  107742. return;
  107743. }
  107744. if (right) {
  107745. this._rotationAngle++;
  107746. }
  107747. else {
  107748. this._rotationAngle--;
  107749. }
  107750. this.currentVRCamera.animations = [];
  107751. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  107752. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  107753. var animationRotationKeys = [];
  107754. animationRotationKeys.push({
  107755. frame: 0,
  107756. value: this.currentVRCamera.rotationQuaternion
  107757. });
  107758. animationRotationKeys.push({
  107759. frame: 6,
  107760. value: target
  107761. });
  107762. animationRotation.setKeys(animationRotationKeys);
  107763. animationRotation.setEasingFunction(this._circleEase);
  107764. this.currentVRCamera.animations.push(animationRotation);
  107765. this._postProcessMove.animations = [];
  107766. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  107767. var vignetteWeightKeys = [];
  107768. vignetteWeightKeys.push({
  107769. frame: 0,
  107770. value: 0
  107771. });
  107772. vignetteWeightKeys.push({
  107773. frame: 3,
  107774. value: 4
  107775. });
  107776. vignetteWeightKeys.push({
  107777. frame: 6,
  107778. value: 0
  107779. });
  107780. animationPP.setKeys(vignetteWeightKeys);
  107781. animationPP.setEasingFunction(this._circleEase);
  107782. this._postProcessMove.animations.push(animationPP);
  107783. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  107784. var vignetteStretchKeys = [];
  107785. vignetteStretchKeys.push({
  107786. frame: 0,
  107787. value: 0
  107788. });
  107789. vignetteStretchKeys.push({
  107790. frame: 3,
  107791. value: 10
  107792. });
  107793. vignetteStretchKeys.push({
  107794. frame: 6,
  107795. value: 0
  107796. });
  107797. animationPP2.setKeys(vignetteStretchKeys);
  107798. animationPP2.setEasingFunction(this._circleEase);
  107799. this._postProcessMove.animations.push(animationPP2);
  107800. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  107801. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  107802. this._postProcessMove.samples = 4;
  107803. this._webVRCamera.attachPostProcess(this._postProcessMove);
  107804. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  107805. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  107806. });
  107807. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  107808. };
  107809. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer, ray) {
  107810. if (hit.pickedPoint) {
  107811. if (gazer._teleportationRequestInitiated) {
  107812. this._displayTeleportationTarget();
  107813. this._haloCenter.copyFrom(hit.pickedPoint);
  107814. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  107815. }
  107816. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(true, false), ray);
  107817. if (pickNormal) {
  107818. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  107819. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  107820. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  107821. }
  107822. this._teleportationTarget.position.y += 0.1;
  107823. }
  107824. };
  107825. /**
  107826. * Teleports the users feet to the desired location
  107827. * @param location The location where the user's feet should be placed
  107828. */
  107829. VRExperienceHelper.prototype.teleportCamera = function (location) {
  107830. var _this = this;
  107831. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  107832. return;
  107833. }
  107834. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  107835. // offset of the headset from the anchor.
  107836. if (this.webVRCamera.leftCamera) {
  107837. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  107838. this._workingVector.subtractInPlace(this.webVRCamera.position);
  107839. location.subtractToRef(this._workingVector, this._workingVector);
  107840. }
  107841. else {
  107842. this._workingVector.copyFrom(location);
  107843. }
  107844. // Add height to account for user's height offset
  107845. if (this.isInVRMode) {
  107846. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  107847. }
  107848. else {
  107849. this._workingVector.y += this._defaultHeight;
  107850. }
  107851. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  107852. // Create animation from the camera's position to the new location
  107853. this.currentVRCamera.animations = [];
  107854. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  107855. var animationCameraTeleportationKeys = [{
  107856. frame: 0,
  107857. value: this.currentVRCamera.position
  107858. },
  107859. {
  107860. frame: 11,
  107861. value: this._workingVector
  107862. }
  107863. ];
  107864. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  107865. animationCameraTeleportation.setEasingFunction(this._circleEase);
  107866. this.currentVRCamera.animations.push(animationCameraTeleportation);
  107867. this._postProcessMove.animations = [];
  107868. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  107869. var vignetteWeightKeys = [];
  107870. vignetteWeightKeys.push({
  107871. frame: 0,
  107872. value: 0
  107873. });
  107874. vignetteWeightKeys.push({
  107875. frame: 5,
  107876. value: 8
  107877. });
  107878. vignetteWeightKeys.push({
  107879. frame: 11,
  107880. value: 0
  107881. });
  107882. animationPP.setKeys(vignetteWeightKeys);
  107883. this._postProcessMove.animations.push(animationPP);
  107884. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  107885. var vignetteStretchKeys = [];
  107886. vignetteStretchKeys.push({
  107887. frame: 0,
  107888. value: 0
  107889. });
  107890. vignetteStretchKeys.push({
  107891. frame: 5,
  107892. value: 10
  107893. });
  107894. vignetteStretchKeys.push({
  107895. frame: 11,
  107896. value: 0
  107897. });
  107898. animationPP2.setKeys(vignetteStretchKeys);
  107899. this._postProcessMove.animations.push(animationPP2);
  107900. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  107901. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  107902. this._webVRCamera.attachPostProcess(this._postProcessMove);
  107903. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  107904. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  107905. });
  107906. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  107907. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  107908. });
  107909. this._hideTeleportationTarget();
  107910. };
  107911. VRExperienceHelper.prototype._convertNormalToDirectionOfRay = function (normal, ray) {
  107912. if (normal) {
  107913. var angle = Math.acos(BABYLON.Vector3.Dot(normal, ray.direction));
  107914. if (angle < Math.PI / 2) {
  107915. normal.scaleInPlace(-1);
  107916. }
  107917. }
  107918. return normal;
  107919. };
  107920. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  107921. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  107922. return;
  107923. }
  107924. var ray = gazer._getForwardRay(this._rayLength);
  107925. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  107926. if (hit) {
  107927. // Populate the contrllers mesh that can be used for drag/drop
  107928. if (gazer._laserPointer) {
  107929. hit.originMesh = gazer._laserPointer.parent;
  107930. }
  107931. this._scene.simulatePointerMove(hit, { pointerId: gazer._id });
  107932. }
  107933. gazer._currentHit = hit;
  107934. // Moving the gazeTracker on the mesh face targetted
  107935. if (hit && hit.pickedPoint) {
  107936. if (this._displayGaze) {
  107937. var multiplier = 1;
  107938. gazer._gazeTracker.isVisible = true;
  107939. if (gazer._isActionableMesh) {
  107940. multiplier = 3;
  107941. }
  107942. if (this.updateGazeTrackerScale) {
  107943. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  107944. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  107945. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  107946. }
  107947. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(), ray);
  107948. // To avoid z-fighting
  107949. var deltaFighting = 0.002;
  107950. if (pickNormal) {
  107951. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  107952. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  107953. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  107954. }
  107955. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  107956. if (gazer._gazeTracker.position.x < 0) {
  107957. gazer._gazeTracker.position.x += deltaFighting;
  107958. }
  107959. else {
  107960. gazer._gazeTracker.position.x -= deltaFighting;
  107961. }
  107962. if (gazer._gazeTracker.position.y < 0) {
  107963. gazer._gazeTracker.position.y += deltaFighting;
  107964. }
  107965. else {
  107966. gazer._gazeTracker.position.y -= deltaFighting;
  107967. }
  107968. if (gazer._gazeTracker.position.z < 0) {
  107969. gazer._gazeTracker.position.z += deltaFighting;
  107970. }
  107971. else {
  107972. gazer._gazeTracker.position.z -= deltaFighting;
  107973. }
  107974. }
  107975. // Changing the size of the laser pointer based on the distance from the targetted point
  107976. gazer._updatePointerDistance(hit.distance);
  107977. }
  107978. else {
  107979. gazer._updatePointerDistance();
  107980. gazer._gazeTracker.isVisible = false;
  107981. }
  107982. if (hit && hit.pickedMesh) {
  107983. // The object selected is the floor, we're in a teleportation scenario
  107984. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  107985. // Moving the teleportation area to this targetted point
  107986. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  107987. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  107988. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  107989. }
  107990. gazer._currentMeshSelected = null;
  107991. if (gazer._teleportationRequestInitiated) {
  107992. this._moveTeleportationSelectorTo(hit, gazer, ray);
  107993. }
  107994. return;
  107995. }
  107996. // If not, we're in a selection scenario
  107997. //this._teleportationAllowed = false;
  107998. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  107999. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  108000. this.onNewMeshPicked.notifyObservers(hit);
  108001. gazer._currentMeshSelected = hit.pickedMesh;
  108002. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  108003. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  108004. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  108005. gazer._isActionableMesh = true;
  108006. }
  108007. else {
  108008. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  108009. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  108010. gazer._isActionableMesh = false;
  108011. }
  108012. try {
  108013. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  108014. }
  108015. catch (err) {
  108016. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  108017. }
  108018. }
  108019. else {
  108020. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  108021. gazer._currentMeshSelected = null;
  108022. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  108023. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  108024. }
  108025. }
  108026. }
  108027. else {
  108028. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  108029. gazer._currentMeshSelected = null;
  108030. //this._teleportationAllowed = false;
  108031. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  108032. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  108033. }
  108034. };
  108035. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  108036. if (mesh) {
  108037. this.onSelectedMeshUnselected.notifyObservers(mesh);
  108038. }
  108039. };
  108040. /**
  108041. * Sets the color of the laser ray from the vr controllers.
  108042. * @param color new color for the ray.
  108043. */
  108044. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  108045. if (this._leftController) {
  108046. this._leftController._setLaserPointerColor(color);
  108047. }
  108048. if (this._rightController) {
  108049. this._rightController._setLaserPointerColor(color);
  108050. }
  108051. };
  108052. /**
  108053. * Sets the color of the ray from the vr headsets gaze.
  108054. * @param color new color for the ray.
  108055. */
  108056. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  108057. if (!this._cameraGazer._gazeTracker.material) {
  108058. return;
  108059. }
  108060. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  108061. if (this._leftController) {
  108062. this._leftController._gazeTracker.material.emissiveColor = color;
  108063. }
  108064. if (this._rightController) {
  108065. this._rightController._gazeTracker.material.emissiveColor = color;
  108066. }
  108067. };
  108068. /**
  108069. * Exits VR and disposes of the vr experience helper
  108070. */
  108071. VRExperienceHelper.prototype.dispose = function () {
  108072. if (this.isInVRMode) {
  108073. this.exitVR();
  108074. }
  108075. if (this._postProcessMove) {
  108076. this._postProcessMove.dispose();
  108077. }
  108078. if (this._webVRCamera) {
  108079. this._webVRCamera.dispose();
  108080. }
  108081. if (this._vrDeviceOrientationCamera) {
  108082. this._vrDeviceOrientationCamera.dispose();
  108083. }
  108084. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  108085. document.body.removeChild(this._btnVR);
  108086. }
  108087. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  108088. this._deviceOrientationCamera.dispose();
  108089. }
  108090. if (this._cameraGazer) {
  108091. this._cameraGazer.dispose();
  108092. }
  108093. if (this._leftController) {
  108094. this._leftController.dispose();
  108095. }
  108096. if (this._rightController) {
  108097. this._rightController.dispose();
  108098. }
  108099. if (this._teleportationTarget) {
  108100. this._teleportationTarget.dispose();
  108101. }
  108102. this._floorMeshesCollection = [];
  108103. document.removeEventListener("keydown", this._onKeyDown);
  108104. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  108105. window.removeEventListener("resize", this._onResize);
  108106. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  108107. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  108108. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  108109. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  108110. document.onmsfullscreenchange = null;
  108111. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  108112. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  108113. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  108114. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  108115. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  108116. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  108117. this._scene.unregisterBeforeRender(this.beforeRender);
  108118. };
  108119. /**
  108120. * Gets the name of the VRExperienceHelper class
  108121. * @returns "VRExperienceHelper"
  108122. */
  108123. VRExperienceHelper.prototype.getClassName = function () {
  108124. return "VRExperienceHelper";
  108125. };
  108126. return VRExperienceHelper;
  108127. }());
  108128. BABYLON.VRExperienceHelper = VRExperienceHelper;
  108129. })(BABYLON || (BABYLON = {}));
  108130. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  108131. var BABYLON;
  108132. (function (BABYLON) {
  108133. /**
  108134. * WebXR Camera which holds the views for the xrSession
  108135. * @see https://doc.babylonjs.com/how_to/webxr
  108136. */
  108137. var WebXRCamera = /** @class */ (function (_super) {
  108138. __extends(WebXRCamera, _super);
  108139. /**
  108140. * Creates a new webXRCamera, this should only be set at the camera after it has been updated by the xrSessionManager
  108141. * @param name the name of the camera
  108142. * @param scene the scene to add the camera to
  108143. */
  108144. function WebXRCamera(name, scene) {
  108145. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  108146. // Initial camera configuration
  108147. _this.minZ = 0;
  108148. _this.rotationQuaternion = new BABYLON.Quaternion();
  108149. _this.cameraRigMode = BABYLON.Camera.RIG_MODE_CUSTOM;
  108150. _this.updateUpVectorFromRotation = true;
  108151. _this._updateNumberOfRigCameras(1);
  108152. return _this;
  108153. }
  108154. WebXRCamera.prototype._updateNumberOfRigCameras = function (viewCount) {
  108155. if (viewCount === void 0) { viewCount = 1; }
  108156. while (this.rigCameras.length < viewCount) {
  108157. var newCamera = new BABYLON.TargetCamera("view: " + this.rigCameras.length, BABYLON.Vector3.Zero(), this.getScene());
  108158. newCamera.minZ = 0;
  108159. newCamera.parent = this;
  108160. newCamera.rotationQuaternion = new BABYLON.Quaternion();
  108161. this.rigCameras.push(newCamera);
  108162. }
  108163. while (this.rigCameras.length > viewCount) {
  108164. var removedCamera = this.rigCameras.pop();
  108165. if (removedCamera) {
  108166. removedCamera.dispose();
  108167. }
  108168. }
  108169. };
  108170. /** @hidden */
  108171. WebXRCamera.prototype._updateForDualEyeDebugging = function (pupilDistance) {
  108172. if (pupilDistance === void 0) { pupilDistance = 0.01; }
  108173. // Create initial camera rigs
  108174. this._updateNumberOfRigCameras(2);
  108175. this.rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  108176. this.rigCameras[0].position.x = -pupilDistance / 2;
  108177. this.rigCameras[0].outputRenderTarget = null;
  108178. this.rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  108179. this.rigCameras[1].position.x = pupilDistance / 2;
  108180. this.rigCameras[1].outputRenderTarget = null;
  108181. };
  108182. /**
  108183. * Updates the cameras position from the current pose information of the XR session
  108184. * @param xrSessionManager the session containing pose information
  108185. * @returns true if the camera has been updated, false if the session did not contain pose or frame data
  108186. */
  108187. WebXRCamera.prototype.updateFromXRSessionManager = function (xrSessionManager) {
  108188. var _this = this;
  108189. // Ensure all frame data is available
  108190. if (!xrSessionManager._currentXRFrame || !xrSessionManager._currentXRFrame.getDevicePose) {
  108191. return false;
  108192. }
  108193. var pose = xrSessionManager._currentXRFrame.getDevicePose(xrSessionManager._frameOfReference);
  108194. if (!pose || !pose.poseModelMatrix) {
  108195. return false;
  108196. }
  108197. // Update the parent cameras matrix
  108198. BABYLON.Matrix.FromFloat32ArrayToRefScaled(pose.poseModelMatrix, 0, 1, WebXRCamera._TmpMatrix);
  108199. if (!this._scene.useRightHandedSystem) {
  108200. WebXRCamera._TmpMatrix.toggleModelMatrixHandInPlace();
  108201. }
  108202. WebXRCamera._TmpMatrix.getTranslationToRef(this.position);
  108203. WebXRCamera._TmpMatrix.getRotationMatrixToRef(WebXRCamera._TmpMatrix);
  108204. BABYLON.Quaternion.FromRotationMatrixToRef(WebXRCamera._TmpMatrix, this.rotationQuaternion);
  108205. this.computeWorldMatrix();
  108206. // Update camera rigs
  108207. this._updateNumberOfRigCameras(xrSessionManager._currentXRFrame.views.length);
  108208. xrSessionManager._currentXRFrame.views.forEach(function (view, i) {
  108209. // Update view/projection matrix
  108210. BABYLON.Matrix.FromFloat32ArrayToRefScaled(pose.getViewMatrix(view), 0, 1, _this.rigCameras[i]._computedViewMatrix);
  108211. BABYLON.Matrix.FromFloat32ArrayToRefScaled(view.projectionMatrix, 0, 1, _this.rigCameras[i]._projectionMatrix);
  108212. if (!_this._scene.useRightHandedSystem) {
  108213. _this.rigCameras[i]._computedViewMatrix.toggleModelMatrixHandInPlace();
  108214. _this.rigCameras[i]._projectionMatrix.toggleProjectionMatrixHandInPlace();
  108215. }
  108216. // Update viewport
  108217. var viewport = xrSessionManager._xrSession.baseLayer.getViewport(view);
  108218. var width = xrSessionManager._xrSession.baseLayer.framebufferWidth;
  108219. var height = xrSessionManager._xrSession.baseLayer.framebufferHeight;
  108220. _this.rigCameras[i].viewport.width = viewport.width / width;
  108221. _this.rigCameras[i].viewport.height = viewport.height / height;
  108222. _this.rigCameras[i].viewport.x = viewport.x / width;
  108223. _this.rigCameras[i].viewport.y = viewport.y / height;
  108224. // Set cameras to render to the session's render target
  108225. _this.rigCameras[i].outputRenderTarget = xrSessionManager._sessionRenderTargetTexture;
  108226. });
  108227. return true;
  108228. };
  108229. WebXRCamera._TmpMatrix = new BABYLON.Matrix();
  108230. return WebXRCamera;
  108231. }(BABYLON.FreeCamera));
  108232. BABYLON.WebXRCamera = WebXRCamera;
  108233. })(BABYLON || (BABYLON = {}));
  108234. //# sourceMappingURL=babylon.webXRCamera.js.map
  108235. var BABYLON;
  108236. (function (BABYLON) {
  108237. /**
  108238. * Manages an XRSession
  108239. * @see https://doc.babylonjs.com/how_to/webxr
  108240. */
  108241. var WebXRSessionManager = /** @class */ (function () {
  108242. /**
  108243. * Constructs a WebXRSessionManager, this must be initialized within a user action before usage
  108244. * @param scene The scene which the session should be created for
  108245. */
  108246. function WebXRSessionManager(scene) {
  108247. this.scene = scene;
  108248. /**
  108249. * Fires every time a new xrFrame arrives which can be used to update the camera
  108250. */
  108251. this.onXRFrameObservable = new BABYLON.Observable();
  108252. /**
  108253. * Fires when the xr session is ended either by the device or manually done
  108254. */
  108255. this.onXRSessionEnded = new BABYLON.Observable();
  108256. /** @hidden */
  108257. this._sessionRenderTargetTexture = null;
  108258. this._tmpMatrix = new BABYLON.Matrix();
  108259. }
  108260. /**
  108261. * Initializes the manager
  108262. * After initialization enterXR can be called to start an XR session
  108263. * @returns Promise which resolves after it is initialized
  108264. */
  108265. WebXRSessionManager.prototype.initializeAsync = function () {
  108266. var _this = this;
  108267. BABYLON.Tools.Warn("The WebXR APIs are still under development and are subject to change in the future.");
  108268. // Check if the browser supports webXR
  108269. this._xrNavigator = navigator;
  108270. if (!this._xrNavigator.xr) {
  108271. return Promise.reject("webXR not supported by this browser");
  108272. }
  108273. // Request the webXR device
  108274. return this._xrNavigator.xr.requestDevice().then(function (device) {
  108275. _this._xrDevice = device;
  108276. return _this.scene.getEngine()._gl.setCompatibleXRDevice(_this._xrDevice);
  108277. });
  108278. };
  108279. /**
  108280. * Enters XR with the desired XR session options, this must be done with a user action (eg. button click event)
  108281. * @param sessionCreationOptions xr options to create the session with
  108282. * @param frameOfReferenceType option to configure how the xr pose is expressed
  108283. * @returns Promise which resolves after it enters XR
  108284. */
  108285. WebXRSessionManager.prototype.enterXRAsync = function (sessionCreationOptions, frameOfReferenceType) {
  108286. var _this = this;
  108287. // initialize session
  108288. return this._xrDevice.requestSession(sessionCreationOptions).then(function (session) {
  108289. _this._xrSession = session;
  108290. // handle when the session is ended (By calling session.end or device ends its own session eg. pressing home button on phone)
  108291. _this._xrSession.addEventListener("end", function () {
  108292. // Remove render target texture and notify frame obervers
  108293. _this._sessionRenderTargetTexture = null;
  108294. // Restore frame buffer to avoid clear on xr framebuffer after session end
  108295. _this.scene.getEngine().restoreDefaultFramebuffer();
  108296. // Need to restart render loop as after the session is ended the last request for new frame will never call callback
  108297. _this.scene.getEngine().customAnimationFrameRequester = null;
  108298. _this.onXRSessionEnded.notifyObservers(null);
  108299. _this.scene.getEngine()._renderLoop();
  108300. }, { once: true });
  108301. _this._xrSession.baseLayer = new XRWebGLLayer(_this._xrSession, _this.scene.getEngine()._gl);
  108302. return _this._xrSession.requestFrameOfReference(frameOfReferenceType);
  108303. }).then(function (frameOfRef) {
  108304. _this._frameOfReference = frameOfRef;
  108305. // Tell the engine's render loop to be driven by the xr session's refresh rate and provide xr pose information
  108306. _this.scene.getEngine().customAnimationFrameRequester = {
  108307. requestAnimationFrame: _this._xrSession.requestAnimationFrame.bind(_this._xrSession),
  108308. renderFunction: function (timestamp, xrFrame) {
  108309. // Store the XR frame in the manager to be consumed by the XR camera to update pose
  108310. _this._currentXRFrame = xrFrame;
  108311. _this.onXRFrameObservable.notifyObservers(null);
  108312. _this.scene.getEngine()._renderLoop();
  108313. }
  108314. };
  108315. // Create render target texture from xr's webgl render target
  108316. _this._sessionRenderTargetTexture = WebXRSessionManager._CreateRenderTargetTextureFromSession(_this._xrSession, _this.scene);
  108317. // Stop window's animation frame and trigger sessions animation frame
  108318. window.cancelAnimationFrame(_this.scene.getEngine()._frameHandler);
  108319. _this.scene.getEngine()._renderLoop();
  108320. });
  108321. };
  108322. /**
  108323. * Stops the xrSession and restores the renderloop
  108324. * @returns Promise which resolves after it exits XR
  108325. */
  108326. WebXRSessionManager.prototype.exitXRAsync = function () {
  108327. return this._xrSession.end();
  108328. };
  108329. /**
  108330. * Fires a ray and returns the closest hit in the xr sessions enviornment, useful to place objects in AR
  108331. * @param ray ray to cast into the environment
  108332. * @returns Promise which resolves with a collision point in the environment if it exists
  108333. */
  108334. WebXRSessionManager.prototype.environmentPointHitTestAsync = function (ray) {
  108335. var _this = this;
  108336. return new Promise(function (res, rej) {
  108337. // Compute left handed inputs to request hit test
  108338. var origin = new Float32Array([ray.origin.x, ray.origin.y, ray.origin.z]);
  108339. var direction = new Float32Array([ray.direction.x, ray.direction.y, ray.direction.z]);
  108340. if (!_this.scene.useRightHandedSystem) {
  108341. origin[2] *= -1;
  108342. direction[2] *= -1;
  108343. }
  108344. // Fire hittest
  108345. _this._xrSession.requestHitTest(origin, direction, _this._frameOfReference)
  108346. .then(function (hits) {
  108347. if (hits.length > 0) {
  108348. BABYLON.Matrix.FromFloat32ArrayToRefScaled(hits[0].hitMatrix, 0, 1.0, _this._tmpMatrix);
  108349. var hitPoint = _this._tmpMatrix.getTranslation();
  108350. if (!_this.scene.useRightHandedSystem) {
  108351. hitPoint.z *= -1;
  108352. }
  108353. res(hitPoint);
  108354. }
  108355. else {
  108356. res(null);
  108357. }
  108358. }).catch(function (e) {
  108359. res(null);
  108360. });
  108361. });
  108362. };
  108363. /**
  108364. * Checks if a session would be supported for the creation options specified
  108365. * @param options creation options to check if they are supported
  108366. * @returns true if supported
  108367. */
  108368. WebXRSessionManager.prototype.supportsSessionAsync = function (options) {
  108369. return this._xrDevice.supportsSession(options).then(function () {
  108370. return true;
  108371. }).catch(function (e) {
  108372. return false;
  108373. });
  108374. };
  108375. /**
  108376. * @hidden
  108377. * Converts the render layer of xrSession to a render target
  108378. * @param session session to create render target for
  108379. * @param scene scene the new render target should be created for
  108380. */
  108381. WebXRSessionManager._CreateRenderTargetTextureFromSession = function (session, scene) {
  108382. // Create internal texture
  108383. var internalTexture = new BABYLON.InternalTexture(scene.getEngine(), BABYLON.InternalTexture.DATASOURCE_UNKNOWN, true);
  108384. internalTexture.width = session.baseLayer.framebufferWidth;
  108385. internalTexture.height = session.baseLayer.framebufferHeight;
  108386. internalTexture._framebuffer = session.baseLayer.framebuffer;
  108387. // Create render target texture from the internal texture
  108388. var renderTargetTexture = new BABYLON.RenderTargetTexture("XR renderTargetTexture", { width: internalTexture.width, height: internalTexture.height }, scene, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, true);
  108389. renderTargetTexture._texture = internalTexture;
  108390. return renderTargetTexture;
  108391. };
  108392. /**
  108393. * Disposes of the session manager
  108394. */
  108395. WebXRSessionManager.prototype.dispose = function () {
  108396. this.onXRFrameObservable.clear();
  108397. this.onXRSessionEnded.clear();
  108398. };
  108399. return WebXRSessionManager;
  108400. }());
  108401. BABYLON.WebXRSessionManager = WebXRSessionManager;
  108402. })(BABYLON || (BABYLON = {}));
  108403. //# sourceMappingURL=babylon.webXRSessionManager.js.map
  108404. var BABYLON;
  108405. (function (BABYLON) {
  108406. /**
  108407. * States of the webXR experience
  108408. */
  108409. var WebXRState;
  108410. (function (WebXRState) {
  108411. /**
  108412. * Transitioning to being in XR mode
  108413. */
  108414. WebXRState[WebXRState["ENTERING_XR"] = 0] = "ENTERING_XR";
  108415. /**
  108416. * Transitioning to non XR mode
  108417. */
  108418. WebXRState[WebXRState["EXITING_XR"] = 1] = "EXITING_XR";
  108419. /**
  108420. * In XR mode and presenting
  108421. */
  108422. WebXRState[WebXRState["IN_XR"] = 2] = "IN_XR";
  108423. /**
  108424. * Not entered XR mode
  108425. */
  108426. WebXRState[WebXRState["NOT_IN_XR"] = 3] = "NOT_IN_XR";
  108427. })(WebXRState = BABYLON.WebXRState || (BABYLON.WebXRState = {}));
  108428. /**
  108429. * Helper class used to enable XR
  108430. * @see https://doc.babylonjs.com/how_to/webxr
  108431. */
  108432. var WebXRExperienceHelper = /** @class */ (function () {
  108433. /**
  108434. * Creates a WebXRExperienceHelper
  108435. * @param scene The scene the helper should be created in
  108436. */
  108437. function WebXRExperienceHelper(scene) {
  108438. this.scene = scene;
  108439. /**
  108440. * The current state of the XR experience (eg. transitioning, in XR or not in XR)
  108441. */
  108442. this.state = WebXRState.NOT_IN_XR;
  108443. /**
  108444. * Fires when the state of the experience helper has changed
  108445. */
  108446. this.onStateChangedObservable = new BABYLON.Observable();
  108447. this._nonVRCamera = null;
  108448. this._originalSceneAutoClear = true;
  108449. this._supported = false;
  108450. this.camera = new BABYLON.WebXRCamera("", scene);
  108451. this._sessionManager = new BABYLON.WebXRSessionManager(scene);
  108452. this.container = new BABYLON.AbstractMesh("", scene);
  108453. this.camera.parent = this.container;
  108454. }
  108455. WebXRExperienceHelper.prototype._setState = function (val) {
  108456. this.state = val;
  108457. this.onStateChangedObservable.notifyObservers(this.state);
  108458. };
  108459. /**
  108460. * Creates the experience helper
  108461. * @param scene the scene to attach the experience helper to
  108462. * @returns a promise for the experience helper
  108463. */
  108464. WebXRExperienceHelper.CreateAsync = function (scene) {
  108465. var helper = new WebXRExperienceHelper(scene);
  108466. return helper._sessionManager.initializeAsync().then(function () {
  108467. helper._supported = true;
  108468. return helper;
  108469. }).catch(function () {
  108470. return helper;
  108471. });
  108472. };
  108473. /**
  108474. * Exits XR mode and returns the scene to its original state
  108475. * @returns promise that resolves after xr mode has exited
  108476. */
  108477. WebXRExperienceHelper.prototype.exitXRAsync = function () {
  108478. this._setState(WebXRState.EXITING_XR);
  108479. return this._sessionManager.exitXRAsync();
  108480. };
  108481. /**
  108482. * Enters XR mode (This must be done within a user interaction in most browsers eg. button click)
  108483. * @param sessionCreationOptions options for the XR session
  108484. * @param frameOfReference frame of reference of the XR session
  108485. * @returns promise that resolves after xr mode has entered
  108486. */
  108487. WebXRExperienceHelper.prototype.enterXRAsync = function (sessionCreationOptions, frameOfReference) {
  108488. var _this = this;
  108489. if (!this._supported) {
  108490. throw "XR session not supported by this browser";
  108491. }
  108492. this._setState(WebXRState.ENTERING_XR);
  108493. return this._sessionManager.enterXRAsync(sessionCreationOptions, frameOfReference).then(function () {
  108494. // Cache pre xr scene settings
  108495. _this._originalSceneAutoClear = _this.scene.autoClear;
  108496. _this._nonVRCamera = _this.scene.activeCamera;
  108497. // Overwrite current scene settings
  108498. _this.scene.autoClear = false;
  108499. _this.scene.activeCamera = _this.camera;
  108500. _this._sessionManager.onXRFrameObservable.add(function () {
  108501. _this.camera.updateFromXRSessionManager(_this._sessionManager);
  108502. });
  108503. _this._sessionManager.onXRSessionEnded.addOnce(function () {
  108504. // Reset camera rigs output render target to ensure sessions render target is not drawn after it ends
  108505. _this.camera.rigCameras.forEach(function (c) {
  108506. c.outputRenderTarget = null;
  108507. });
  108508. // Restore scene settings
  108509. _this.scene.autoClear = _this._originalSceneAutoClear;
  108510. _this.scene.activeCamera = _this._nonVRCamera;
  108511. _this._sessionManager.onXRFrameObservable.clear();
  108512. _this._setState(WebXRState.NOT_IN_XR);
  108513. });
  108514. _this._setState(WebXRState.IN_XR);
  108515. });
  108516. };
  108517. /**
  108518. * Fires a ray and returns the closest hit in the xr sessions enviornment, useful to place objects in AR
  108519. * @param ray ray to cast into the environment
  108520. * @returns Promise which resolves with a collision point in the environment if it exists
  108521. */
  108522. WebXRExperienceHelper.prototype.environmentPointHitTestAsync = function (ray) {
  108523. return this._sessionManager.environmentPointHitTestAsync(ray);
  108524. };
  108525. /**
  108526. * Updates the global position of the camera by moving the camera's container
  108527. * This should be used instead of modifying the camera's position as it will be overwritten by an xrSessions's update frame
  108528. * @param position The desired global position of the camera
  108529. */
  108530. WebXRExperienceHelper.prototype.setPositionOfCameraUsingContainer = function (position) {
  108531. this.camera.globalPosition.subtractToRef(position, WebXRExperienceHelper._TmpVector);
  108532. this.container.position.subtractInPlace(WebXRExperienceHelper._TmpVector);
  108533. };
  108534. /**
  108535. * Rotates the xr camera by rotating the camera's container around the camera's position
  108536. * This should be used instead of modifying the camera's rotation as it will be overwritten by an xrSessions's update frame
  108537. * @param rotation the desired quaternion rotation to apply to the camera
  108538. */
  108539. WebXRExperienceHelper.prototype.rotateCameraByQuaternionUsingContainer = function (rotation) {
  108540. if (!this.container.rotationQuaternion) {
  108541. this.container.rotationQuaternion = BABYLON.Quaternion.FromEulerVector(this.container.rotation);
  108542. }
  108543. this.container.rotationQuaternion.multiplyInPlace(rotation);
  108544. this.container.position.rotateByQuaternionAroundPointToRef(rotation, this.camera.globalPosition, this.container.position);
  108545. };
  108546. /**
  108547. * Checks if the creation options are supported by the xr session
  108548. * @param options creation options
  108549. * @returns true if supported
  108550. */
  108551. WebXRExperienceHelper.prototype.supportsSessionAsync = function (options) {
  108552. if (!this._supported) {
  108553. return Promise.resolve(false);
  108554. }
  108555. return this._sessionManager.supportsSessionAsync(options);
  108556. };
  108557. /**
  108558. * Disposes of the experience helper
  108559. */
  108560. WebXRExperienceHelper.prototype.dispose = function () {
  108561. this.camera.dispose();
  108562. this.container.dispose();
  108563. this.onStateChangedObservable.clear();
  108564. this._sessionManager.dispose();
  108565. };
  108566. WebXRExperienceHelper._TmpVector = new BABYLON.Vector3();
  108567. return WebXRExperienceHelper;
  108568. }());
  108569. BABYLON.WebXRExperienceHelper = WebXRExperienceHelper;
  108570. })(BABYLON || (BABYLON = {}));
  108571. //# sourceMappingURL=babylon.webXRExperienceHelper.js.map
  108572. var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
  108573. return new (P || (P = Promise))(function (resolve, reject) {
  108574. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  108575. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  108576. function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
  108577. step((generator = generator.apply(thisArg, _arguments || [])).next());
  108578. });
  108579. };
  108580. var __generator = (this && this.__generator) || function (thisArg, body) {
  108581. var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
  108582. return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
  108583. function verb(n) { return function (v) { return step([n, v]); }; }
  108584. function step(op) {
  108585. if (f) throw new TypeError("Generator is already executing.");
  108586. while (_) try {
  108587. if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
  108588. if (y = 0, t) op = [op[0] & 2, t.value];
  108589. switch (op[0]) {
  108590. case 0: case 1: t = op; break;
  108591. case 4: _.label++; return { value: op[1], done: false };
  108592. case 5: _.label++; y = op[1]; op = [0]; continue;
  108593. case 7: op = _.ops.pop(); _.trys.pop(); continue;
  108594. default:
  108595. if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
  108596. if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
  108597. if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
  108598. if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
  108599. if (t[2]) _.ops.pop();
  108600. _.trys.pop(); continue;
  108601. }
  108602. op = body.call(thisArg, _);
  108603. } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
  108604. if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
  108605. }
  108606. };
  108607. var BABYLON;
  108608. (function (BABYLON) {
  108609. /**
  108610. * Button which can be used to enter a different mode of XR
  108611. */
  108612. var WebXREnterExitUIButton = /** @class */ (function () {
  108613. /**
  108614. * Creates a WebXREnterExitUIButton
  108615. * @param element button element
  108616. * @param initializationOptions XR initialization options for the button
  108617. */
  108618. function WebXREnterExitUIButton(
  108619. /** button element */
  108620. element,
  108621. /** XR initialization options for the button */
  108622. initializationOptions) {
  108623. this.element = element;
  108624. this.initializationOptions = initializationOptions;
  108625. }
  108626. /**
  108627. * Overwritable function which can be used to update the button's visuals when the state changes
  108628. * @param activeButton the current active button in the UI
  108629. */
  108630. WebXREnterExitUIButton.prototype.update = function (activeButton) {
  108631. };
  108632. return WebXREnterExitUIButton;
  108633. }());
  108634. BABYLON.WebXREnterExitUIButton = WebXREnterExitUIButton;
  108635. /**
  108636. * Options to create the webXR UI
  108637. */
  108638. var WebXREnterExitUIOptions = /** @class */ (function () {
  108639. function WebXREnterExitUIOptions() {
  108640. }
  108641. return WebXREnterExitUIOptions;
  108642. }());
  108643. BABYLON.WebXREnterExitUIOptions = WebXREnterExitUIOptions;
  108644. /**
  108645. * UI to allow the user to enter/exit XR mode
  108646. */
  108647. var WebXREnterExitUI = /** @class */ (function () {
  108648. function WebXREnterExitUI(scene, options) {
  108649. var _this = this;
  108650. this.scene = scene;
  108651. this._buttons = [];
  108652. this._activeButton = null;
  108653. /**
  108654. * Fired every time the active button is changed.
  108655. *
  108656. * When xr is entered via a button that launches xr that button will be the callback parameter
  108657. *
  108658. * When exiting xr the callback parameter will be null)
  108659. */
  108660. this.activeButtonChangedObservable = new BABYLON.Observable();
  108661. this._overlay = document.createElement("div");
  108662. this._overlay.style.cssText = "z-index:11;position: absolute; right: 20px;bottom: 50px;";
  108663. if (options.customButtons) {
  108664. this._buttons = options.customButtons;
  108665. }
  108666. else {
  108667. var hmdBtn = document.createElement("button");
  108668. hmdBtn.style.cssText = "color: #868686; border-color: #868686; border-style: solid; margin-left: 10px; height: 50px; width: 80px; background-color: rgba(51,51,51,0.7); background-repeat:no-repeat; background-position: center; outline: none;";
  108669. hmdBtn.innerText = "HMD";
  108670. this._buttons.push(new WebXREnterExitUIButton(hmdBtn, { immersive: true, outputContext: options.outputCanvasContext }));
  108671. this._buttons[this._buttons.length - 1].update = function (activeButton) {
  108672. this.element.style.display = (activeButton === null || activeButton === this) ? "" : "none";
  108673. this.element.innerText = activeButton === this ? "EXIT" : "HMD";
  108674. };
  108675. var windowBtn = document.createElement("button");
  108676. windowBtn.style.cssText = hmdBtn.style.cssText;
  108677. windowBtn.innerText = "Window";
  108678. this._buttons.push(new WebXREnterExitUIButton(windowBtn, { immersive: false, environmentIntegration: true, outputContext: options.outputCanvasContext }));
  108679. this._buttons[this._buttons.length - 1].update = function (activeButton) {
  108680. this.element.style.display = (activeButton === null || activeButton === this) ? "" : "none";
  108681. this.element.innerText = activeButton === this ? "EXIT" : "Window";
  108682. };
  108683. this._updateButtons(null);
  108684. }
  108685. var renderCanvas = scene.getEngine().getRenderingCanvas();
  108686. if (renderCanvas && renderCanvas.parentNode) {
  108687. renderCanvas.parentNode.appendChild(this._overlay);
  108688. scene.onDisposeObservable.addOnce(function () {
  108689. _this.dispose();
  108690. });
  108691. }
  108692. }
  108693. /**
  108694. * Creates UI to allow the user to enter/exit XR mode
  108695. * @param scene the scene to add the ui to
  108696. * @param helper the xr experience helper to enter/exit xr with
  108697. * @param options options to configure the UI
  108698. * @returns the created ui
  108699. */
  108700. WebXREnterExitUI.CreateAsync = function (scene, helper, options) {
  108701. var _this = this;
  108702. var ui = new WebXREnterExitUI(scene, options);
  108703. var supportedPromises = ui._buttons.map(function (btn) {
  108704. return helper.supportsSessionAsync(btn.initializationOptions);
  108705. });
  108706. helper.onStateChangedObservable.add(function (state) {
  108707. if (state == BABYLON.WebXRState.NOT_IN_XR) {
  108708. ui._updateButtons(null);
  108709. }
  108710. });
  108711. return Promise.all(supportedPromises).then(function (results) {
  108712. results.forEach(function (supported, i) {
  108713. if (supported) {
  108714. ui._overlay.appendChild(ui._buttons[i].element);
  108715. ui._buttons[i].element.onclick = function () { return __awaiter(_this, void 0, void 0, function () {
  108716. return __generator(this, function (_a) {
  108717. switch (_a.label) {
  108718. case 0:
  108719. if (!(helper.state == BABYLON.WebXRState.IN_XR)) return [3 /*break*/, 2];
  108720. ui._updateButtons(null);
  108721. return [4 /*yield*/, helper.exitXRAsync()];
  108722. case 1:
  108723. _a.sent();
  108724. return [2 /*return*/];
  108725. case 2:
  108726. if (!(helper.state == BABYLON.WebXRState.NOT_IN_XR)) return [3 /*break*/, 4];
  108727. ui._updateButtons(ui._buttons[i]);
  108728. return [4 /*yield*/, helper.enterXRAsync(ui._buttons[i].initializationOptions, "eye-level")];
  108729. case 3:
  108730. _a.sent();
  108731. _a.label = 4;
  108732. case 4: return [2 /*return*/];
  108733. }
  108734. });
  108735. }); };
  108736. }
  108737. });
  108738. return ui;
  108739. });
  108740. };
  108741. WebXREnterExitUI.prototype._updateButtons = function (activeButton) {
  108742. var _this = this;
  108743. this._activeButton = activeButton;
  108744. this._buttons.forEach(function (b) {
  108745. b.update(_this._activeButton);
  108746. });
  108747. this.activeButtonChangedObservable.notifyObservers(this._activeButton);
  108748. };
  108749. /**
  108750. * Disposes of the object
  108751. */
  108752. WebXREnterExitUI.prototype.dispose = function () {
  108753. var renderCanvas = this.scene.getEngine().getRenderingCanvas();
  108754. if (renderCanvas && renderCanvas.parentNode && renderCanvas.parentNode.contains(this._overlay)) {
  108755. renderCanvas.parentNode.removeChild(this._overlay);
  108756. }
  108757. this.activeButtonChangedObservable.clear();
  108758. };
  108759. return WebXREnterExitUI;
  108760. }());
  108761. BABYLON.WebXREnterExitUI = WebXREnterExitUI;
  108762. })(BABYLON || (BABYLON = {}));
  108763. //# sourceMappingURL=babylon.webXREnterExitUI.js.map
  108764. var BABYLON;
  108765. (function (BABYLON) {
  108766. /**
  108767. * Creates a canvas that is added/removed from the webpage when entering/exiting XR
  108768. */
  108769. var WebXRManagedOutputCanvas = /** @class */ (function () {
  108770. /**
  108771. * Initializes the canvas to be added/removed upon entering/exiting xr
  108772. * @param helper the xr experience helper used to trigger adding/removing of the canvas
  108773. * @param canvas The canvas to be added/removed (If not specified a full screen canvas will be created)
  108774. */
  108775. function WebXRManagedOutputCanvas(helper, canvas) {
  108776. var _this = this;
  108777. this._canvas = null;
  108778. /**
  108779. * xrpresent context of the canvas which can be used to display/mirror xr content
  108780. */
  108781. this.canvasContext = null;
  108782. if (!canvas) {
  108783. canvas = document.createElement('canvas');
  108784. canvas.style.cssText = "position:absolute; bottom:0px;right:0px;z-index:10;width:100%;height:100%;background-color: #000000;";
  108785. }
  108786. this._setManagedOutputCanvas(canvas);
  108787. helper.onStateChangedObservable.add(function (stateInfo) {
  108788. if (stateInfo == BABYLON.WebXRState.ENTERING_XR) {
  108789. // The canvas is added to the screen before entering XR because currently the xr session must be initialized while the canvas is added render properly
  108790. _this._addCanvas();
  108791. }
  108792. else if (helper.state == BABYLON.WebXRState.NOT_IN_XR) {
  108793. _this._removeCanvas();
  108794. }
  108795. });
  108796. }
  108797. /**
  108798. * Disposes of the object
  108799. */
  108800. WebXRManagedOutputCanvas.prototype.dispose = function () {
  108801. this._removeCanvas();
  108802. this._setManagedOutputCanvas(null);
  108803. };
  108804. WebXRManagedOutputCanvas.prototype._setManagedOutputCanvas = function (canvas) {
  108805. this._removeCanvas();
  108806. if (!canvas) {
  108807. this._canvas = null;
  108808. this.canvasContext = null;
  108809. }
  108810. else {
  108811. this._canvas = canvas;
  108812. this.canvasContext = this._canvas.getContext('xrpresent');
  108813. }
  108814. };
  108815. WebXRManagedOutputCanvas.prototype._addCanvas = function () {
  108816. if (this._canvas) {
  108817. document.body.appendChild(this._canvas);
  108818. }
  108819. };
  108820. WebXRManagedOutputCanvas.prototype._removeCanvas = function () {
  108821. if (this._canvas && document.body.contains(this._canvas)) {
  108822. document.body.removeChild(this._canvas);
  108823. }
  108824. };
  108825. return WebXRManagedOutputCanvas;
  108826. }());
  108827. BABYLON.WebXRManagedOutputCanvas = WebXRManagedOutputCanvas;
  108828. })(BABYLON || (BABYLON = {}));
  108829. //# sourceMappingURL=babylon.webXRManagedOutputCanvas.js.map
  108830. var BABYLON;
  108831. (function (BABYLON) {
  108832. /**
  108833. * Represents an XR input
  108834. */
  108835. var WebXRController = /** @class */ (function () {
  108836. /**
  108837. * Creates the controller
  108838. * @see https://doc.babylonjs.com/how_to/webxr
  108839. * @param scene the scene which the controller should be associated to
  108840. */
  108841. function WebXRController(scene) {
  108842. this.pointer = new BABYLON.AbstractMesh("controllerPointer", scene);
  108843. }
  108844. /**
  108845. * Disposes of the object
  108846. */
  108847. WebXRController.prototype.dispose = function () {
  108848. if (this.grip) {
  108849. this.grip.dispose();
  108850. }
  108851. this.pointer.dispose();
  108852. };
  108853. return WebXRController;
  108854. }());
  108855. BABYLON.WebXRController = WebXRController;
  108856. /**
  108857. * XR input used to track XR inputs such as controllers/rays
  108858. */
  108859. var WebXRInput = /** @class */ (function () {
  108860. /**
  108861. * Initializes the WebXRInput
  108862. * @param helper experience helper which the input should be created for
  108863. */
  108864. function WebXRInput(helper) {
  108865. var _this = this;
  108866. this.helper = helper;
  108867. /**
  108868. * XR controllers being tracked
  108869. */
  108870. this.controllers = [];
  108871. this._tmpMatrix = new BABYLON.Matrix();
  108872. this._frameObserver = helper._sessionManager.onXRFrameObservable.add(function () {
  108873. if (!helper._sessionManager._currentXRFrame || !helper._sessionManager._currentXRFrame.getDevicePose) {
  108874. return;
  108875. }
  108876. var xrFrame = helper._sessionManager._currentXRFrame;
  108877. var inputSources = helper._sessionManager._xrSession.getInputSources();
  108878. inputSources.forEach(function (input, i) {
  108879. var inputPose = xrFrame.getInputPose(input, helper._sessionManager._frameOfReference);
  108880. if (inputPose) {
  108881. if (_this.controllers.length <= i) {
  108882. _this.controllers.push(new WebXRController(helper.container.getScene()));
  108883. }
  108884. var controller = _this.controllers[i];
  108885. // Manage the grip if it exists
  108886. if (inputPose.gripMatrix) {
  108887. if (!controller.grip) {
  108888. controller.grip = new BABYLON.AbstractMesh("controllerGrip", helper.container.getScene());
  108889. }
  108890. BABYLON.Matrix.FromFloat32ArrayToRefScaled(inputPose.gripMatrix, 0, 1, _this._tmpMatrix);
  108891. if (!controller.grip.getScene().useRightHandedSystem) {
  108892. _this._tmpMatrix.toggleModelMatrixHandInPlace();
  108893. }
  108894. if (!controller.grip.rotationQuaternion) {
  108895. controller.grip.rotationQuaternion = new BABYLON.Quaternion();
  108896. }
  108897. _this._tmpMatrix.decompose(controller.grip.scaling, controller.grip.rotationQuaternion, controller.grip.position);
  108898. }
  108899. // Manager pointer of controller
  108900. BABYLON.Matrix.FromFloat32ArrayToRefScaled(inputPose.targetRay.transformMatrix, 0, 1, _this._tmpMatrix);
  108901. if (!controller.pointer.getScene().useRightHandedSystem) {
  108902. _this._tmpMatrix.toggleModelMatrixHandInPlace();
  108903. }
  108904. if (!controller.pointer.rotationQuaternion) {
  108905. controller.pointer.rotationQuaternion = new BABYLON.Quaternion();
  108906. }
  108907. _this._tmpMatrix.decompose(controller.pointer.scaling, controller.pointer.rotationQuaternion, controller.pointer.position);
  108908. }
  108909. });
  108910. });
  108911. }
  108912. /**
  108913. * Disposes of the object
  108914. */
  108915. WebXRInput.prototype.dispose = function () {
  108916. this.controllers.forEach(function (c) {
  108917. c.dispose();
  108918. });
  108919. this.helper._sessionManager.onXRFrameObservable.remove(this._frameObserver);
  108920. };
  108921. return WebXRInput;
  108922. }());
  108923. BABYLON.WebXRInput = WebXRInput;
  108924. })(BABYLON || (BABYLON = {}));
  108925. //# sourceMappingURL=babylon.webXRInput.js.map
  108926. // Mainly based on these 2 articles :
  108927. // 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
  108928. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  108929. var BABYLON;
  108930. (function (BABYLON) {
  108931. /**
  108932. * Defines the potential axis of a Joystick
  108933. */
  108934. var JoystickAxis;
  108935. (function (JoystickAxis) {
  108936. /** X axis */
  108937. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  108938. /** Y axis */
  108939. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  108940. /** Z axis */
  108941. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  108942. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  108943. /**
  108944. * Class used to define virtual joystick (used in touch mode)
  108945. */
  108946. var VirtualJoystick = /** @class */ (function () {
  108947. /**
  108948. * Creates a new virtual joystick
  108949. * @param leftJoystick defines that the joystick is for left hand (false by default)
  108950. */
  108951. function VirtualJoystick(leftJoystick) {
  108952. var _this = this;
  108953. if (leftJoystick) {
  108954. this._leftJoystick = true;
  108955. }
  108956. else {
  108957. this._leftJoystick = false;
  108958. }
  108959. VirtualJoystick._globalJoystickIndex++;
  108960. // By default left & right arrow keys are moving the X
  108961. // and up & down keys are moving the Y
  108962. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  108963. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  108964. this.reverseLeftRight = false;
  108965. this.reverseUpDown = false;
  108966. // collections of pointers
  108967. this._touches = new BABYLON.StringDictionary();
  108968. this.deltaPosition = BABYLON.Vector3.Zero();
  108969. this._joystickSensibility = 25;
  108970. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  108971. this._onResize = function (evt) {
  108972. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  108973. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  108974. if (VirtualJoystick.vjCanvas) {
  108975. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  108976. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  108977. }
  108978. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  108979. };
  108980. // injecting a canvas element on top of the canvas 3D game
  108981. if (!VirtualJoystick.vjCanvas) {
  108982. window.addEventListener("resize", this._onResize, false);
  108983. VirtualJoystick.vjCanvas = document.createElement("canvas");
  108984. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  108985. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  108986. VirtualJoystick.vjCanvas.width = window.innerWidth;
  108987. VirtualJoystick.vjCanvas.height = window.innerHeight;
  108988. VirtualJoystick.vjCanvas.style.width = "100%";
  108989. VirtualJoystick.vjCanvas.style.height = "100%";
  108990. VirtualJoystick.vjCanvas.style.position = "absolute";
  108991. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  108992. VirtualJoystick.vjCanvas.style.top = "0px";
  108993. VirtualJoystick.vjCanvas.style.left = "0px";
  108994. VirtualJoystick.vjCanvas.style.zIndex = "5";
  108995. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  108996. // Support for jQuery PEP polyfill
  108997. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  108998. var context = VirtualJoystick.vjCanvas.getContext('2d');
  108999. if (!context) {
  109000. throw new Error("Unable to create canvas for virtual joystick");
  109001. }
  109002. VirtualJoystick.vjCanvasContext = context;
  109003. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  109004. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  109005. document.body.appendChild(VirtualJoystick.vjCanvas);
  109006. }
  109007. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  109008. this.pressed = false;
  109009. // default joystick color
  109010. this._joystickColor = "cyan";
  109011. this._joystickPointerID = -1;
  109012. // current joystick position
  109013. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  109014. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  109015. // origin joystick position
  109016. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  109017. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  109018. this._onPointerDownHandlerRef = function (evt) {
  109019. _this._onPointerDown(evt);
  109020. };
  109021. this._onPointerMoveHandlerRef = function (evt) {
  109022. _this._onPointerMove(evt);
  109023. };
  109024. this._onPointerUpHandlerRef = function (evt) {
  109025. _this._onPointerUp(evt);
  109026. };
  109027. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  109028. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  109029. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  109030. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  109031. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  109032. evt.preventDefault(); // Disables system menu
  109033. }, false);
  109034. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  109035. }
  109036. /**
  109037. * Defines joystick sensibility (ie. the ratio beteen a physical move and virtual joystick position change)
  109038. * @param newJoystickSensibility defines the new sensibility
  109039. */
  109040. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  109041. this._joystickSensibility = newJoystickSensibility;
  109042. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  109043. };
  109044. VirtualJoystick.prototype._onPointerDown = function (e) {
  109045. var positionOnScreenCondition;
  109046. e.preventDefault();
  109047. if (this._leftJoystick === true) {
  109048. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  109049. }
  109050. else {
  109051. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  109052. }
  109053. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  109054. // First contact will be dedicated to the virtual joystick
  109055. this._joystickPointerID = e.pointerId;
  109056. this._joystickPointerStartPos.x = e.clientX;
  109057. this._joystickPointerStartPos.y = e.clientY;
  109058. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  109059. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  109060. this._deltaJoystickVector.x = 0;
  109061. this._deltaJoystickVector.y = 0;
  109062. this.pressed = true;
  109063. this._touches.add(e.pointerId.toString(), e);
  109064. }
  109065. else {
  109066. // You can only trigger the action buttons with a joystick declared
  109067. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  109068. this._action();
  109069. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  109070. }
  109071. }
  109072. };
  109073. VirtualJoystick.prototype._onPointerMove = function (e) {
  109074. // If the current pointer is the one associated to the joystick (first touch contact)
  109075. if (this._joystickPointerID == e.pointerId) {
  109076. this._joystickPointerPos.x = e.clientX;
  109077. this._joystickPointerPos.y = e.clientY;
  109078. this._deltaJoystickVector = this._joystickPointerPos.clone();
  109079. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  109080. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  109081. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  109082. switch (this._axisTargetedByLeftAndRight) {
  109083. case JoystickAxis.X:
  109084. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  109085. break;
  109086. case JoystickAxis.Y:
  109087. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  109088. break;
  109089. case JoystickAxis.Z:
  109090. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  109091. break;
  109092. }
  109093. var directionUpDown = this.reverseUpDown ? 1 : -1;
  109094. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  109095. switch (this._axisTargetedByUpAndDown) {
  109096. case JoystickAxis.X:
  109097. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  109098. break;
  109099. case JoystickAxis.Y:
  109100. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  109101. break;
  109102. case JoystickAxis.Z:
  109103. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  109104. break;
  109105. }
  109106. }
  109107. else {
  109108. var data = this._touches.get(e.pointerId.toString());
  109109. if (data) {
  109110. data.x = e.clientX;
  109111. data.y = e.clientY;
  109112. }
  109113. }
  109114. };
  109115. VirtualJoystick.prototype._onPointerUp = function (e) {
  109116. if (this._joystickPointerID == e.pointerId) {
  109117. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  109118. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  109119. this._joystickPointerID = -1;
  109120. this.pressed = false;
  109121. }
  109122. else {
  109123. var touch = this._touches.get(e.pointerId.toString());
  109124. if (touch) {
  109125. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  109126. }
  109127. }
  109128. this._deltaJoystickVector.x = 0;
  109129. this._deltaJoystickVector.y = 0;
  109130. this._touches.remove(e.pointerId.toString());
  109131. };
  109132. /**
  109133. * Change the color of the virtual joystick
  109134. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  109135. */
  109136. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  109137. this._joystickColor = newColor;
  109138. };
  109139. /**
  109140. * Defines a callback to call when the joystick is touched
  109141. * @param action defines the callback
  109142. */
  109143. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  109144. this._action = action;
  109145. };
  109146. /**
  109147. * Defines which axis you'd like to control for left & right
  109148. * @param axis defines the axis to use
  109149. */
  109150. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  109151. switch (axis) {
  109152. case JoystickAxis.X:
  109153. case JoystickAxis.Y:
  109154. case JoystickAxis.Z:
  109155. this._axisTargetedByLeftAndRight = axis;
  109156. break;
  109157. default:
  109158. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  109159. break;
  109160. }
  109161. };
  109162. /**
  109163. * Defines which axis you'd like to control for up & down
  109164. * @param axis defines the axis to use
  109165. */
  109166. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  109167. switch (axis) {
  109168. case JoystickAxis.X:
  109169. case JoystickAxis.Y:
  109170. case JoystickAxis.Z:
  109171. this._axisTargetedByUpAndDown = axis;
  109172. break;
  109173. default:
  109174. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  109175. break;
  109176. }
  109177. };
  109178. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  109179. var _this = this;
  109180. if (this.pressed) {
  109181. this._touches.forEach(function (key, touch) {
  109182. if (touch.pointerId === _this._joystickPointerID) {
  109183. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  109184. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  109185. VirtualJoystick.vjCanvasContext.beginPath();
  109186. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  109187. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  109188. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  109189. VirtualJoystick.vjCanvasContext.stroke();
  109190. VirtualJoystick.vjCanvasContext.closePath();
  109191. VirtualJoystick.vjCanvasContext.beginPath();
  109192. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  109193. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  109194. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  109195. VirtualJoystick.vjCanvasContext.stroke();
  109196. VirtualJoystick.vjCanvasContext.closePath();
  109197. VirtualJoystick.vjCanvasContext.beginPath();
  109198. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  109199. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  109200. VirtualJoystick.vjCanvasContext.stroke();
  109201. VirtualJoystick.vjCanvasContext.closePath();
  109202. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  109203. }
  109204. else {
  109205. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  109206. VirtualJoystick.vjCanvasContext.beginPath();
  109207. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  109208. VirtualJoystick.vjCanvasContext.beginPath();
  109209. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  109210. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  109211. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  109212. VirtualJoystick.vjCanvasContext.stroke();
  109213. VirtualJoystick.vjCanvasContext.closePath();
  109214. touch.prevX = touch.x;
  109215. touch.prevY = touch.y;
  109216. }
  109217. });
  109218. }
  109219. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  109220. };
  109221. /**
  109222. * Release internal HTML canvas
  109223. */
  109224. VirtualJoystick.prototype.releaseCanvas = function () {
  109225. if (VirtualJoystick.vjCanvas) {
  109226. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  109227. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  109228. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  109229. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  109230. window.removeEventListener("resize", this._onResize);
  109231. document.body.removeChild(VirtualJoystick.vjCanvas);
  109232. VirtualJoystick.vjCanvas = null;
  109233. }
  109234. };
  109235. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  109236. VirtualJoystick._globalJoystickIndex = 0;
  109237. return VirtualJoystick;
  109238. }());
  109239. BABYLON.VirtualJoystick = VirtualJoystick;
  109240. })(BABYLON || (BABYLON = {}));
  109241. //# sourceMappingURL=babylon.virtualJoystick.js.map
  109242. var BABYLON;
  109243. (function (BABYLON) {
  109244. BABYLON.Node.AddNodeConstructor("VirtualJoysticksCamera", function (name, scene) {
  109245. return function () { return new VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  109246. });
  109247. /**
  109248. * This represents a free type of camera. It can be usefull in First Person Shooter game for instance.
  109249. * It is identical to the Free Camera and simply adds by default a virtual joystick.
  109250. * Virtual Joysticks are on-screen 2D graphics that are used to control the camera or other scene items.
  109251. * @see http://doc.babylonjs.com/features/cameras#virtual-joysticks-camera
  109252. */
  109253. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  109254. __extends(VirtualJoysticksCamera, _super);
  109255. /**
  109256. * Intantiates a VirtualJoysticksCamera. It can be usefull in First Person Shooter game for instance.
  109257. * It is identical to the Free Camera and simply adds by default a virtual joystick.
  109258. * Virtual Joysticks are on-screen 2D graphics that are used to control the camera or other scene items.
  109259. * @see http://doc.babylonjs.com/features/cameras#virtual-joysticks-camera
  109260. * @param name Define the name of the camera in the scene
  109261. * @param position Define the start position of the camera in the scene
  109262. * @param scene Define the scene the camera belongs to
  109263. */
  109264. function VirtualJoysticksCamera(name, position, scene) {
  109265. var _this = _super.call(this, name, position, scene) || this;
  109266. _this.inputs.addVirtualJoystick();
  109267. return _this;
  109268. }
  109269. /**
  109270. * Gets the current object class name.
  109271. * @return the class name
  109272. */
  109273. VirtualJoysticksCamera.prototype.getClassName = function () {
  109274. return "VirtualJoysticksCamera";
  109275. };
  109276. return VirtualJoysticksCamera;
  109277. }(BABYLON.FreeCamera));
  109278. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  109279. })(BABYLON || (BABYLON = {}));
  109280. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  109281. var BABYLON;
  109282. (function (BABYLON) {
  109283. /**
  109284. * Manage the Virtual Joystick inputs to control the movement of a free camera.
  109285. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  109286. */
  109287. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  109288. function FreeCameraVirtualJoystickInput() {
  109289. }
  109290. /**
  109291. * Gets the left stick of the virtual joystick.
  109292. * @returns The virtual Joystick
  109293. */
  109294. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  109295. return this._leftjoystick;
  109296. };
  109297. /**
  109298. * Gets the right stick of the virtual joystick.
  109299. * @returns The virtual Joystick
  109300. */
  109301. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  109302. return this._rightjoystick;
  109303. };
  109304. /**
  109305. * Update the current camera state depending on the inputs that have been used this frame.
  109306. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  109307. */
  109308. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  109309. if (this._leftjoystick) {
  109310. var camera = this.camera;
  109311. var speed = camera._computeLocalCameraSpeed() * 50;
  109312. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  109313. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  109314. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  109315. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  109316. if (!this._leftjoystick.pressed) {
  109317. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  109318. }
  109319. if (!this._rightjoystick.pressed) {
  109320. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  109321. }
  109322. }
  109323. };
  109324. /**
  109325. * Attach the input controls to a specific dom element to get the input from.
  109326. * @param element Defines the element the controls should be listened from
  109327. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  109328. */
  109329. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  109330. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  109331. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  109332. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  109333. this._leftjoystick.setJoystickSensibility(0.15);
  109334. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  109335. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  109336. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  109337. this._rightjoystick.reverseUpDown = true;
  109338. this._rightjoystick.setJoystickSensibility(0.05);
  109339. this._rightjoystick.setJoystickColor("yellow");
  109340. };
  109341. /**
  109342. * Detach the current controls from the specified dom element.
  109343. * @param element Defines the element to stop listening the inputs from
  109344. */
  109345. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  109346. this._leftjoystick.releaseCanvas();
  109347. this._rightjoystick.releaseCanvas();
  109348. };
  109349. /**
  109350. * Gets the class name of the current intput.
  109351. * @returns the class name
  109352. */
  109353. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  109354. return "FreeCameraVirtualJoystickInput";
  109355. };
  109356. /**
  109357. * Get the friendly name associated with the input class.
  109358. * @returns the input friendly name
  109359. */
  109360. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  109361. return "virtualJoystick";
  109362. };
  109363. return FreeCameraVirtualJoystickInput;
  109364. }());
  109365. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  109366. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  109367. })(BABYLON || (BABYLON = {}));
  109368. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  109369. var BABYLON;
  109370. (function (BABYLON) {
  109371. /**
  109372. * Class used to specify simplification options
  109373. * @see http://doc.babylonjs.com/how_to/in-browser_mesh_simplification
  109374. */
  109375. var SimplificationSettings = /** @class */ (function () {
  109376. /**
  109377. * Creates a SimplificationSettings
  109378. * @param quality expected quality
  109379. * @param distance distance when this optimized version should be used
  109380. * @param optimizeMesh already optimized mesh
  109381. */
  109382. function SimplificationSettings(
  109383. /** expected quality */
  109384. quality,
  109385. /** distance when this optimized version should be used */
  109386. distance,
  109387. /** already optimized mesh */
  109388. optimizeMesh) {
  109389. this.quality = quality;
  109390. this.distance = distance;
  109391. this.optimizeMesh = optimizeMesh;
  109392. }
  109393. return SimplificationSettings;
  109394. }());
  109395. BABYLON.SimplificationSettings = SimplificationSettings;
  109396. /**
  109397. * Queue used to order the simplification tasks
  109398. * @see http://doc.babylonjs.com/how_to/in-browser_mesh_simplification
  109399. */
  109400. var SimplificationQueue = /** @class */ (function () {
  109401. /**
  109402. * Creates a new queue
  109403. */
  109404. function SimplificationQueue() {
  109405. this.running = false;
  109406. this._simplificationArray = [];
  109407. }
  109408. /**
  109409. * Adds a new simplification task
  109410. * @param task defines a task to add
  109411. */
  109412. SimplificationQueue.prototype.addTask = function (task) {
  109413. this._simplificationArray.push(task);
  109414. };
  109415. /**
  109416. * Execute next task
  109417. */
  109418. SimplificationQueue.prototype.executeNext = function () {
  109419. var task = this._simplificationArray.pop();
  109420. if (task) {
  109421. this.running = true;
  109422. this.runSimplification(task);
  109423. }
  109424. else {
  109425. this.running = false;
  109426. }
  109427. };
  109428. /**
  109429. * Execute a simplification task
  109430. * @param task defines the task to run
  109431. */
  109432. SimplificationQueue.prototype.runSimplification = function (task) {
  109433. var _this = this;
  109434. if (task.parallelProcessing) {
  109435. //parallel simplifier
  109436. task.settings.forEach(function (setting) {
  109437. var simplifier = _this.getSimplifier(task);
  109438. simplifier.simplify(setting, function (newMesh) {
  109439. task.mesh.addLODLevel(setting.distance, newMesh);
  109440. newMesh.isVisible = true;
  109441. //check if it is the last
  109442. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  109443. //all done, run the success callback.
  109444. task.successCallback();
  109445. }
  109446. _this.executeNext();
  109447. });
  109448. });
  109449. }
  109450. else {
  109451. //single simplifier.
  109452. var simplifier = this.getSimplifier(task);
  109453. var runDecimation = function (setting, callback) {
  109454. simplifier.simplify(setting, function (newMesh) {
  109455. task.mesh.addLODLevel(setting.distance, newMesh);
  109456. newMesh.isVisible = true;
  109457. //run the next quality level
  109458. callback();
  109459. });
  109460. };
  109461. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  109462. runDecimation(task.settings[loop.index], function () {
  109463. loop.executeNext();
  109464. });
  109465. }, function () {
  109466. //execution ended, run the success callback.
  109467. if (task.successCallback) {
  109468. task.successCallback();
  109469. }
  109470. _this.executeNext();
  109471. });
  109472. }
  109473. };
  109474. SimplificationQueue.prototype.getSimplifier = function (task) {
  109475. switch (task.simplificationType) {
  109476. case SimplificationType.QUADRATIC:
  109477. default:
  109478. return new QuadraticErrorSimplification(task.mesh);
  109479. }
  109480. };
  109481. return SimplificationQueue;
  109482. }());
  109483. BABYLON.SimplificationQueue = SimplificationQueue;
  109484. /**
  109485. * The implemented types of simplification
  109486. * At the moment only Quadratic Error Decimation is implemented
  109487. * @see http://doc.babylonjs.com/how_to/in-browser_mesh_simplification
  109488. */
  109489. var SimplificationType;
  109490. (function (SimplificationType) {
  109491. /** Quadratic error decimation */
  109492. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  109493. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  109494. var DecimationTriangle = /** @class */ (function () {
  109495. function DecimationTriangle(vertices) {
  109496. this.vertices = vertices;
  109497. this.error = new Array(4);
  109498. this.deleted = false;
  109499. this.isDirty = false;
  109500. this.deletePending = false;
  109501. this.borderFactor = 0;
  109502. }
  109503. return DecimationTriangle;
  109504. }());
  109505. var DecimationVertex = /** @class */ (function () {
  109506. function DecimationVertex(position, id) {
  109507. this.position = position;
  109508. this.id = id;
  109509. this.isBorder = true;
  109510. this.q = new QuadraticMatrix();
  109511. this.triangleCount = 0;
  109512. this.triangleStart = 0;
  109513. this.originalOffsets = [];
  109514. }
  109515. DecimationVertex.prototype.updatePosition = function (newPosition) {
  109516. this.position.copyFrom(newPosition);
  109517. };
  109518. return DecimationVertex;
  109519. }());
  109520. var QuadraticMatrix = /** @class */ (function () {
  109521. function QuadraticMatrix(data) {
  109522. this.data = new Array(10);
  109523. for (var i = 0; i < 10; ++i) {
  109524. if (data && data[i]) {
  109525. this.data[i] = data[i];
  109526. }
  109527. else {
  109528. this.data[i] = 0;
  109529. }
  109530. }
  109531. }
  109532. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  109533. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  109534. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  109535. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  109536. return det;
  109537. };
  109538. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  109539. for (var i = 0; i < 10; ++i) {
  109540. this.data[i] += matrix.data[i];
  109541. }
  109542. };
  109543. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  109544. for (var i = 0; i < 10; ++i) {
  109545. this.data[i] += data[i];
  109546. }
  109547. };
  109548. QuadraticMatrix.prototype.add = function (matrix) {
  109549. var m = new QuadraticMatrix();
  109550. for (var i = 0; i < 10; ++i) {
  109551. m.data[i] = this.data[i] + matrix.data[i];
  109552. }
  109553. return m;
  109554. };
  109555. QuadraticMatrix.FromData = function (a, b, c, d) {
  109556. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  109557. };
  109558. //returning an array to avoid garbage collection
  109559. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  109560. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  109561. };
  109562. return QuadraticMatrix;
  109563. }());
  109564. var Reference = /** @class */ (function () {
  109565. function Reference(vertexId, triangleId) {
  109566. this.vertexId = vertexId;
  109567. this.triangleId = triangleId;
  109568. }
  109569. return Reference;
  109570. }());
  109571. /**
  109572. * An implementation of the Quadratic Error simplification algorithm.
  109573. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  109574. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  109575. * @author RaananW
  109576. * @see http://doc.babylonjs.com/how_to/in-browser_mesh_simplification
  109577. */
  109578. var QuadraticErrorSimplification = /** @class */ (function () {
  109579. function QuadraticErrorSimplification(_mesh) {
  109580. this._mesh = _mesh;
  109581. this.syncIterations = 5000;
  109582. this.aggressiveness = 7;
  109583. this.decimationIterations = 100;
  109584. this.boundingBoxEpsilon = BABYLON.Epsilon;
  109585. }
  109586. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  109587. var _this = this;
  109588. this.initDecimatedMesh();
  109589. //iterating through the submeshes array, one after the other.
  109590. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  109591. _this.initWithMesh(loop.index, function () {
  109592. _this.runDecimation(settings, loop.index, function () {
  109593. loop.executeNext();
  109594. });
  109595. }, settings.optimizeMesh);
  109596. }, function () {
  109597. setTimeout(function () {
  109598. successCallback(_this._reconstructedMesh);
  109599. }, 0);
  109600. });
  109601. };
  109602. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  109603. var _this = this;
  109604. var targetCount = ~~(this.triangles.length * settings.quality);
  109605. var deletedTriangles = 0;
  109606. var triangleCount = this.triangles.length;
  109607. var iterationFunction = function (iteration, callback) {
  109608. setTimeout(function () {
  109609. if (iteration % 5 === 0) {
  109610. _this.updateMesh(iteration === 0);
  109611. }
  109612. for (var i = 0; i < _this.triangles.length; ++i) {
  109613. _this.triangles[i].isDirty = false;
  109614. }
  109615. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  109616. var trianglesIterator = function (i) {
  109617. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  109618. var t = _this.triangles[tIdx];
  109619. if (!t) {
  109620. return;
  109621. }
  109622. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  109623. return;
  109624. }
  109625. for (var j = 0; j < 3; ++j) {
  109626. if (t.error[j] < threshold) {
  109627. var deleted0 = [];
  109628. var deleted1 = [];
  109629. var v0 = t.vertices[j];
  109630. var v1 = t.vertices[(j + 1) % 3];
  109631. if (v0.isBorder || v1.isBorder) {
  109632. continue;
  109633. }
  109634. var p = BABYLON.Vector3.Zero();
  109635. var n = BABYLON.Vector3.Zero();
  109636. var uv = BABYLON.Vector2.Zero();
  109637. var color = new BABYLON.Color4(0, 0, 0, 1);
  109638. _this.calculateError(v0, v1, p, n, uv, color);
  109639. var delTr = new Array();
  109640. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr)) {
  109641. continue;
  109642. }
  109643. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr)) {
  109644. continue;
  109645. }
  109646. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0) {
  109647. continue;
  109648. }
  109649. var uniqueArray = new Array();
  109650. delTr.forEach(function (deletedT) {
  109651. if (uniqueArray.indexOf(deletedT) === -1) {
  109652. deletedT.deletePending = true;
  109653. uniqueArray.push(deletedT);
  109654. }
  109655. });
  109656. if (uniqueArray.length % 2 !== 0) {
  109657. continue;
  109658. }
  109659. v0.q = v1.q.add(v0.q);
  109660. v0.updatePosition(p);
  109661. var tStart = _this.references.length;
  109662. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  109663. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  109664. var tCount = _this.references.length - tStart;
  109665. if (tCount <= v0.triangleCount) {
  109666. if (tCount) {
  109667. for (var c = 0; c < tCount; c++) {
  109668. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  109669. }
  109670. }
  109671. }
  109672. else {
  109673. v0.triangleStart = tStart;
  109674. }
  109675. v0.triangleCount = tCount;
  109676. break;
  109677. }
  109678. }
  109679. };
  109680. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  109681. }, 0);
  109682. };
  109683. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  109684. if (triangleCount - deletedTriangles <= targetCount) {
  109685. loop.breakLoop();
  109686. }
  109687. else {
  109688. iterationFunction(loop.index, function () {
  109689. loop.executeNext();
  109690. });
  109691. }
  109692. }, function () {
  109693. setTimeout(function () {
  109694. //reconstruct this part of the mesh
  109695. _this.reconstructMesh(submeshIndex);
  109696. successCallback();
  109697. }, 0);
  109698. });
  109699. };
  109700. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  109701. var _this = this;
  109702. this.vertices = [];
  109703. this.triangles = [];
  109704. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  109705. var indices = this._mesh.getIndices();
  109706. var submesh = this._mesh.subMeshes[submeshIndex];
  109707. var findInVertices = function (positionToSearch) {
  109708. if (optimizeMesh) {
  109709. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  109710. if (_this.vertices[ii].position.equals(positionToSearch)) {
  109711. return _this.vertices[ii];
  109712. }
  109713. }
  109714. }
  109715. return null;
  109716. };
  109717. var vertexReferences = [];
  109718. var vertexInit = function (i) {
  109719. if (!positionData) {
  109720. return;
  109721. }
  109722. var offset = i + submesh.verticesStart;
  109723. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  109724. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  109725. vertex.originalOffsets.push(offset);
  109726. if (vertex.id === _this.vertices.length) {
  109727. _this.vertices.push(vertex);
  109728. }
  109729. vertexReferences.push(vertex.id);
  109730. };
  109731. //var totalVertices = mesh.getTotalVertices();
  109732. var totalVertices = submesh.verticesCount;
  109733. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  109734. var indicesInit = function (i) {
  109735. if (!indices) {
  109736. return;
  109737. }
  109738. var offset = (submesh.indexStart / 3) + i;
  109739. var pos = (offset * 3);
  109740. var i0 = indices[pos + 0];
  109741. var i1 = indices[pos + 1];
  109742. var i2 = indices[pos + 2];
  109743. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  109744. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  109745. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  109746. var triangle = new DecimationTriangle([v0, v1, v2]);
  109747. triangle.originalOffset = pos;
  109748. _this.triangles.push(triangle);
  109749. };
  109750. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  109751. _this.init(callback);
  109752. });
  109753. });
  109754. };
  109755. QuadraticErrorSimplification.prototype.init = function (callback) {
  109756. var _this = this;
  109757. var triangleInit1 = function (i) {
  109758. var t = _this.triangles[i];
  109759. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  109760. for (var j = 0; j < 3; j++) {
  109761. 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))));
  109762. }
  109763. };
  109764. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  109765. var triangleInit2 = function (i) {
  109766. var t = _this.triangles[i];
  109767. for (var j = 0; j < 3; ++j) {
  109768. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  109769. }
  109770. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  109771. };
  109772. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  109773. callback();
  109774. });
  109775. });
  109776. };
  109777. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  109778. var newTriangles = [];
  109779. var i;
  109780. for (i = 0; i < this.vertices.length; ++i) {
  109781. this.vertices[i].triangleCount = 0;
  109782. }
  109783. var t;
  109784. var j;
  109785. for (i = 0; i < this.triangles.length; ++i) {
  109786. if (!this.triangles[i].deleted) {
  109787. t = this.triangles[i];
  109788. for (j = 0; j < 3; ++j) {
  109789. t.vertices[j].triangleCount = 1;
  109790. }
  109791. newTriangles.push(t);
  109792. }
  109793. }
  109794. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  109795. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  109796. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  109797. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  109798. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  109799. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  109800. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  109801. var vertexCount = 0;
  109802. for (i = 0; i < this.vertices.length; ++i) {
  109803. var vertex = this.vertices[i];
  109804. vertex.id = vertexCount;
  109805. if (vertex.triangleCount) {
  109806. vertex.originalOffsets.forEach(function (originalOffset) {
  109807. if (!normalData) {
  109808. return;
  109809. }
  109810. newPositionData.push(vertex.position.x);
  109811. newPositionData.push(vertex.position.y);
  109812. newPositionData.push(vertex.position.z);
  109813. newNormalData.push(normalData[originalOffset * 3]);
  109814. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  109815. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  109816. if (uvs && uvs.length) {
  109817. newUVsData.push(uvs[(originalOffset * 2)]);
  109818. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  109819. }
  109820. else if (colorsData && colorsData.length) {
  109821. newColorsData.push(colorsData[(originalOffset * 4)]);
  109822. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  109823. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  109824. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  109825. }
  109826. ++vertexCount;
  109827. });
  109828. }
  109829. }
  109830. var startingIndex = this._reconstructedMesh.getTotalIndices();
  109831. var startingVertex = this._reconstructedMesh.getTotalVertices();
  109832. var submeshesArray = this._reconstructedMesh.subMeshes;
  109833. this._reconstructedMesh.subMeshes = [];
  109834. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  109835. var originalIndices = this._mesh.getIndices();
  109836. for (i = 0; i < newTriangles.length; ++i) {
  109837. t = newTriangles[i]; //now get the new referencing point for each vertex
  109838. [0, 1, 2].forEach(function (idx) {
  109839. var id = originalIndices[t.originalOffset + idx];
  109840. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  109841. if (offset < 0) {
  109842. offset = 0;
  109843. }
  109844. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  109845. });
  109846. }
  109847. //overwriting the old vertex buffers and indices.
  109848. this._reconstructedMesh.setIndices(newIndicesArray);
  109849. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  109850. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  109851. if (newUVsData.length > 0) {
  109852. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  109853. }
  109854. if (newColorsData.length > 0) {
  109855. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  109856. }
  109857. //create submesh
  109858. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  109859. if (submeshIndex > 0) {
  109860. this._reconstructedMesh.subMeshes = [];
  109861. submeshesArray.forEach(function (submesh) {
  109862. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  109863. });
  109864. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  109865. }
  109866. };
  109867. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  109868. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  109869. this._reconstructedMesh.material = this._mesh.material;
  109870. this._reconstructedMesh.parent = this._mesh.parent;
  109871. this._reconstructedMesh.isVisible = false;
  109872. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  109873. };
  109874. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  109875. for (var i = 0; i < vertex1.triangleCount; ++i) {
  109876. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  109877. if (t.deleted) {
  109878. continue;
  109879. }
  109880. var s = this.references[vertex1.triangleStart + i].vertexId;
  109881. var v1 = t.vertices[(s + 1) % 3];
  109882. var v2 = t.vertices[(s + 2) % 3];
  109883. if ((v1 === vertex2 || v2 === vertex2)) {
  109884. deletedArray[i] = true;
  109885. delTr.push(t);
  109886. continue;
  109887. }
  109888. var d1 = v1.position.subtract(point);
  109889. d1 = d1.normalize();
  109890. var d2 = v2.position.subtract(point);
  109891. d2 = d2.normalize();
  109892. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999) {
  109893. return true;
  109894. }
  109895. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  109896. deletedArray[i] = false;
  109897. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2) {
  109898. return true;
  109899. }
  109900. }
  109901. return false;
  109902. };
  109903. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  109904. var newDeleted = deletedTriangles;
  109905. for (var i = 0; i < vertex.triangleCount; ++i) {
  109906. var ref = this.references[vertex.triangleStart + i];
  109907. var t = this.triangles[ref.triangleId];
  109908. if (t.deleted) {
  109909. continue;
  109910. }
  109911. if (deletedArray[i] && t.deletePending) {
  109912. t.deleted = true;
  109913. newDeleted++;
  109914. continue;
  109915. }
  109916. t.vertices[ref.vertexId] = origVertex;
  109917. t.isDirty = true;
  109918. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  109919. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  109920. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  109921. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  109922. this.references.push(ref);
  109923. }
  109924. return newDeleted;
  109925. };
  109926. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  109927. for (var i = 0; i < this.vertices.length; ++i) {
  109928. var vCount = [];
  109929. var vId = [];
  109930. var v = this.vertices[i];
  109931. var j;
  109932. for (j = 0; j < v.triangleCount; ++j) {
  109933. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  109934. for (var ii = 0; ii < 3; ii++) {
  109935. var ofs = 0;
  109936. var vv = triangle.vertices[ii];
  109937. while (ofs < vCount.length) {
  109938. if (vId[ofs] === vv.id) {
  109939. break;
  109940. }
  109941. ++ofs;
  109942. }
  109943. if (ofs === vCount.length) {
  109944. vCount.push(1);
  109945. vId.push(vv.id);
  109946. }
  109947. else {
  109948. vCount[ofs]++;
  109949. }
  109950. }
  109951. }
  109952. for (j = 0; j < vCount.length; ++j) {
  109953. if (vCount[j] === 1) {
  109954. this.vertices[vId[j]].isBorder = true;
  109955. }
  109956. else {
  109957. this.vertices[vId[j]].isBorder = false;
  109958. }
  109959. }
  109960. }
  109961. };
  109962. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  109963. if (identifyBorders === void 0) { identifyBorders = false; }
  109964. var i;
  109965. if (!identifyBorders) {
  109966. var newTrianglesVector = [];
  109967. for (i = 0; i < this.triangles.length; ++i) {
  109968. if (!this.triangles[i].deleted) {
  109969. newTrianglesVector.push(this.triangles[i]);
  109970. }
  109971. }
  109972. this.triangles = newTrianglesVector;
  109973. }
  109974. for (i = 0; i < this.vertices.length; ++i) {
  109975. this.vertices[i].triangleCount = 0;
  109976. this.vertices[i].triangleStart = 0;
  109977. }
  109978. var t;
  109979. var j;
  109980. var v;
  109981. for (i = 0; i < this.triangles.length; ++i) {
  109982. t = this.triangles[i];
  109983. for (j = 0; j < 3; ++j) {
  109984. v = t.vertices[j];
  109985. v.triangleCount++;
  109986. }
  109987. }
  109988. var tStart = 0;
  109989. for (i = 0; i < this.vertices.length; ++i) {
  109990. this.vertices[i].triangleStart = tStart;
  109991. tStart += this.vertices[i].triangleCount;
  109992. this.vertices[i].triangleCount = 0;
  109993. }
  109994. var newReferences = new Array(this.triangles.length * 3);
  109995. for (i = 0; i < this.triangles.length; ++i) {
  109996. t = this.triangles[i];
  109997. for (j = 0; j < 3; ++j) {
  109998. v = t.vertices[j];
  109999. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  110000. v.triangleCount++;
  110001. }
  110002. }
  110003. this.references = newReferences;
  110004. if (identifyBorders) {
  110005. this.identifyBorder();
  110006. }
  110007. };
  110008. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  110009. var x = point.x;
  110010. var y = point.y;
  110011. var z = point.z;
  110012. 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
  110013. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  110014. };
  110015. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  110016. var q = vertex1.q.add(vertex2.q);
  110017. var border = vertex1.isBorder && vertex2.isBorder;
  110018. var error = 0;
  110019. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  110020. if (qDet !== 0 && !border) {
  110021. if (!pointResult) {
  110022. pointResult = BABYLON.Vector3.Zero();
  110023. }
  110024. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  110025. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  110026. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  110027. error = this.vertexError(q, pointResult);
  110028. }
  110029. else {
  110030. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  110031. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  110032. var error1 = this.vertexError(q, vertex1.position);
  110033. var error2 = this.vertexError(q, vertex2.position);
  110034. var error3 = this.vertexError(q, p3);
  110035. error = Math.min(error1, error2, error3);
  110036. if (error === error1) {
  110037. if (pointResult) {
  110038. pointResult.copyFrom(vertex1.position);
  110039. }
  110040. }
  110041. else if (error === error2) {
  110042. if (pointResult) {
  110043. pointResult.copyFrom(vertex2.position);
  110044. }
  110045. }
  110046. else {
  110047. if (pointResult) {
  110048. pointResult.copyFrom(p3);
  110049. }
  110050. }
  110051. }
  110052. return error;
  110053. };
  110054. return QuadraticErrorSimplification;
  110055. }());
  110056. })(BABYLON || (BABYLON = {}));
  110057. //# sourceMappingURL=babylon.meshSimplification.js.map
  110058. var BABYLON;
  110059. (function (BABYLON) {
  110060. Object.defineProperty(BABYLON.Scene.prototype, "simplificationQueue", {
  110061. get: function () {
  110062. if (!this._simplificationQueue) {
  110063. this._simplificationQueue = new BABYLON.SimplificationQueue();
  110064. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE);
  110065. if (!component) {
  110066. component = new SimplicationQueueSceneComponent(this);
  110067. this._addComponent(component);
  110068. }
  110069. }
  110070. return this._simplificationQueue;
  110071. },
  110072. set: function (value) {
  110073. this._simplificationQueue = value;
  110074. },
  110075. enumerable: true,
  110076. configurable: true
  110077. });
  110078. BABYLON.Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  110079. if (parallelProcessing === void 0) { parallelProcessing = true; }
  110080. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  110081. this.getScene().simplificationQueue.addTask({
  110082. settings: settings,
  110083. parallelProcessing: parallelProcessing,
  110084. mesh: this,
  110085. simplificationType: simplificationType,
  110086. successCallback: successCallback
  110087. });
  110088. return this;
  110089. };
  110090. /**
  110091. * Defines the simplification queue scene component responsible to help scheduling the various simplification task
  110092. * created in a scene
  110093. */
  110094. var SimplicationQueueSceneComponent = /** @class */ (function () {
  110095. /**
  110096. * Creates a new instance of the component for the given scene
  110097. * @param scene Defines the scene to register the component in
  110098. */
  110099. function SimplicationQueueSceneComponent(scene) {
  110100. /**
  110101. * The component name helpfull to identify the component in the list of scene components.
  110102. */
  110103. this.name = BABYLON.SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE;
  110104. this.scene = scene;
  110105. }
  110106. /**
  110107. * Registers the component in a given scene
  110108. */
  110109. SimplicationQueueSceneComponent.prototype.register = function () {
  110110. this.scene._beforeCameraUpdateStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE, this, this._beforeCameraUpdate);
  110111. };
  110112. /**
  110113. * Rebuilds the elements related to this component in case of
  110114. * context lost for instance.
  110115. */
  110116. SimplicationQueueSceneComponent.prototype.rebuild = function () {
  110117. // Nothing to do for this component
  110118. };
  110119. /**
  110120. * Disposes the component and the associated ressources
  110121. */
  110122. SimplicationQueueSceneComponent.prototype.dispose = function () {
  110123. // Nothing to do for this component
  110124. };
  110125. SimplicationQueueSceneComponent.prototype._beforeCameraUpdate = function () {
  110126. if (this.scene._simplificationQueue && !this.scene._simplificationQueue.running) {
  110127. this.scene._simplificationQueue.executeNext();
  110128. }
  110129. };
  110130. return SimplicationQueueSceneComponent;
  110131. }());
  110132. BABYLON.SimplicationQueueSceneComponent = SimplicationQueueSceneComponent;
  110133. })(BABYLON || (BABYLON = {}));
  110134. //# sourceMappingURL=babylon.meshSimplificationSceneComponent.js.map
  110135. var BABYLON;
  110136. (function (BABYLON) {
  110137. /**
  110138. * Class used to represent a specific level of detail of a mesh
  110139. * @see http://doc.babylonjs.com/how_to/how_to_use_lod
  110140. */
  110141. var MeshLODLevel = /** @class */ (function () {
  110142. /**
  110143. * Creates a new LOD level
  110144. * @param distance defines the distance where this level should star being displayed
  110145. * @param mesh defines the mesh to use to render this level
  110146. */
  110147. function MeshLODLevel(
  110148. /** Defines the distance where this level should star being displayed */
  110149. distance,
  110150. /** Defines the mesh to use to render this level */
  110151. mesh) {
  110152. this.distance = distance;
  110153. this.mesh = mesh;
  110154. }
  110155. return MeshLODLevel;
  110156. }());
  110157. BABYLON.MeshLODLevel = MeshLODLevel;
  110158. })(BABYLON || (BABYLON = {}));
  110159. //# sourceMappingURL=babylon.meshLODLevel.js.map
  110160. var BABYLON;
  110161. (function (BABYLON) {
  110162. /**
  110163. * Defines the root class used to create scene optimization to use with SceneOptimizer
  110164. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  110165. */
  110166. var SceneOptimization = /** @class */ (function () {
  110167. /**
  110168. * Creates the SceneOptimization object
  110169. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  110170. * @param desc defines the description associated with the optimization
  110171. */
  110172. function SceneOptimization(
  110173. /**
  110174. * Defines the priority of this optimization (0 by default which means first in the list)
  110175. */
  110176. priority) {
  110177. if (priority === void 0) { priority = 0; }
  110178. this.priority = priority;
  110179. }
  110180. /**
  110181. * Gets a string describing the action executed by the current optimization
  110182. * @returns description string
  110183. */
  110184. SceneOptimization.prototype.getDescription = function () {
  110185. return "";
  110186. };
  110187. /**
  110188. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  110189. * @param scene defines the current scene where to apply this optimization
  110190. * @param optimizer defines the current optimizer
  110191. * @returns true if everything that can be done was applied
  110192. */
  110193. SceneOptimization.prototype.apply = function (scene, optimizer) {
  110194. return true;
  110195. };
  110196. return SceneOptimization;
  110197. }());
  110198. BABYLON.SceneOptimization = SceneOptimization;
  110199. /**
  110200. * Defines an optimization used to reduce the size of render target textures
  110201. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  110202. */
  110203. var TextureOptimization = /** @class */ (function (_super) {
  110204. __extends(TextureOptimization, _super);
  110205. /**
  110206. * Creates the TextureOptimization object
  110207. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  110208. * @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
  110209. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  110210. */
  110211. function TextureOptimization(
  110212. /**
  110213. * Defines the priority of this optimization (0 by default which means first in the list)
  110214. */
  110215. priority,
  110216. /**
  110217. * 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
  110218. */
  110219. maximumSize,
  110220. /**
  110221. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  110222. */
  110223. step) {
  110224. if (priority === void 0) { priority = 0; }
  110225. if (maximumSize === void 0) { maximumSize = 1024; }
  110226. if (step === void 0) { step = 0.5; }
  110227. var _this = _super.call(this, priority) || this;
  110228. _this.priority = priority;
  110229. _this.maximumSize = maximumSize;
  110230. _this.step = step;
  110231. return _this;
  110232. }
  110233. /**
  110234. * Gets a string describing the action executed by the current optimization
  110235. * @returns description string
  110236. */
  110237. TextureOptimization.prototype.getDescription = function () {
  110238. return "Reducing render target texture size to " + this.maximumSize;
  110239. };
  110240. /**
  110241. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  110242. * @param scene defines the current scene where to apply this optimization
  110243. * @param optimizer defines the current optimizer
  110244. * @returns true if everything that can be done was applied
  110245. */
  110246. TextureOptimization.prototype.apply = function (scene, optimizer) {
  110247. var allDone = true;
  110248. for (var index = 0; index < scene.textures.length; index++) {
  110249. var texture = scene.textures[index];
  110250. if (!texture.canRescale || texture.getContext) {
  110251. continue;
  110252. }
  110253. var currentSize = texture.getSize();
  110254. var maxDimension = Math.max(currentSize.width, currentSize.height);
  110255. if (maxDimension > this.maximumSize) {
  110256. texture.scale(this.step);
  110257. allDone = false;
  110258. }
  110259. }
  110260. return allDone;
  110261. };
  110262. return TextureOptimization;
  110263. }(SceneOptimization));
  110264. BABYLON.TextureOptimization = TextureOptimization;
  110265. /**
  110266. * Defines an optimization used to increase or decrease the rendering resolution
  110267. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  110268. */
  110269. var HardwareScalingOptimization = /** @class */ (function (_super) {
  110270. __extends(HardwareScalingOptimization, _super);
  110271. /**
  110272. * Creates the HardwareScalingOptimization object
  110273. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  110274. * @param maximumScale defines the maximum scale to use (2 by default)
  110275. * @param step defines the step to use between two passes (0.5 by default)
  110276. */
  110277. function HardwareScalingOptimization(
  110278. /**
  110279. * Defines the priority of this optimization (0 by default which means first in the list)
  110280. */
  110281. priority,
  110282. /**
  110283. * Defines the maximum scale to use (2 by default)
  110284. */
  110285. maximumScale,
  110286. /**
  110287. * Defines the step to use between two passes (0.5 by default)
  110288. */
  110289. step) {
  110290. if (priority === void 0) { priority = 0; }
  110291. if (maximumScale === void 0) { maximumScale = 2; }
  110292. if (step === void 0) { step = 0.25; }
  110293. var _this = _super.call(this, priority) || this;
  110294. _this.priority = priority;
  110295. _this.maximumScale = maximumScale;
  110296. _this.step = step;
  110297. _this._currentScale = -1;
  110298. _this._directionOffset = 1;
  110299. return _this;
  110300. }
  110301. /**
  110302. * Gets a string describing the action executed by the current optimization
  110303. * @return description string
  110304. */
  110305. HardwareScalingOptimization.prototype.getDescription = function () {
  110306. return "Setting hardware scaling level to " + this._currentScale;
  110307. };
  110308. /**
  110309. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  110310. * @param scene defines the current scene where to apply this optimization
  110311. * @param optimizer defines the current optimizer
  110312. * @returns true if everything that can be done was applied
  110313. */
  110314. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  110315. if (this._currentScale === -1) {
  110316. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  110317. if (this._currentScale > this.maximumScale) {
  110318. this._directionOffset = -1;
  110319. }
  110320. }
  110321. this._currentScale += this._directionOffset * this.step;
  110322. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  110323. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  110324. };
  110325. return HardwareScalingOptimization;
  110326. }(SceneOptimization));
  110327. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  110328. /**
  110329. * Defines an optimization used to remove shadows
  110330. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  110331. */
  110332. var ShadowsOptimization = /** @class */ (function (_super) {
  110333. __extends(ShadowsOptimization, _super);
  110334. function ShadowsOptimization() {
  110335. return _super !== null && _super.apply(this, arguments) || this;
  110336. }
  110337. /**
  110338. * Gets a string describing the action executed by the current optimization
  110339. * @return description string
  110340. */
  110341. ShadowsOptimization.prototype.getDescription = function () {
  110342. return "Turning shadows on/off";
  110343. };
  110344. /**
  110345. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  110346. * @param scene defines the current scene where to apply this optimization
  110347. * @param optimizer defines the current optimizer
  110348. * @returns true if everything that can be done was applied
  110349. */
  110350. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  110351. scene.shadowsEnabled = optimizer.isInImprovementMode;
  110352. return true;
  110353. };
  110354. return ShadowsOptimization;
  110355. }(SceneOptimization));
  110356. BABYLON.ShadowsOptimization = ShadowsOptimization;
  110357. /**
  110358. * Defines an optimization used to turn post-processes off
  110359. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  110360. */
  110361. var PostProcessesOptimization = /** @class */ (function (_super) {
  110362. __extends(PostProcessesOptimization, _super);
  110363. function PostProcessesOptimization() {
  110364. return _super !== null && _super.apply(this, arguments) || this;
  110365. }
  110366. /**
  110367. * Gets a string describing the action executed by the current optimization
  110368. * @return description string
  110369. */
  110370. PostProcessesOptimization.prototype.getDescription = function () {
  110371. return "Turning post-processes on/off";
  110372. };
  110373. /**
  110374. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  110375. * @param scene defines the current scene where to apply this optimization
  110376. * @param optimizer defines the current optimizer
  110377. * @returns true if everything that can be done was applied
  110378. */
  110379. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  110380. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  110381. return true;
  110382. };
  110383. return PostProcessesOptimization;
  110384. }(SceneOptimization));
  110385. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  110386. /**
  110387. * Defines an optimization used to turn lens flares off
  110388. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  110389. */
  110390. var LensFlaresOptimization = /** @class */ (function (_super) {
  110391. __extends(LensFlaresOptimization, _super);
  110392. function LensFlaresOptimization() {
  110393. return _super !== null && _super.apply(this, arguments) || this;
  110394. }
  110395. /**
  110396. * Gets a string describing the action executed by the current optimization
  110397. * @return description string
  110398. */
  110399. LensFlaresOptimization.prototype.getDescription = function () {
  110400. return "Turning lens flares on/off";
  110401. };
  110402. /**
  110403. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  110404. * @param scene defines the current scene where to apply this optimization
  110405. * @param optimizer defines the current optimizer
  110406. * @returns true if everything that can be done was applied
  110407. */
  110408. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  110409. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  110410. return true;
  110411. };
  110412. return LensFlaresOptimization;
  110413. }(SceneOptimization));
  110414. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  110415. /**
  110416. * Defines an optimization based on user defined callback.
  110417. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  110418. */
  110419. var CustomOptimization = /** @class */ (function (_super) {
  110420. __extends(CustomOptimization, _super);
  110421. function CustomOptimization() {
  110422. return _super !== null && _super.apply(this, arguments) || this;
  110423. }
  110424. /**
  110425. * Gets a string describing the action executed by the current optimization
  110426. * @returns description string
  110427. */
  110428. CustomOptimization.prototype.getDescription = function () {
  110429. if (this.onGetDescription) {
  110430. return this.onGetDescription();
  110431. }
  110432. return "Running user defined callback";
  110433. };
  110434. /**
  110435. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  110436. * @param scene defines the current scene where to apply this optimization
  110437. * @param optimizer defines the current optimizer
  110438. * @returns true if everything that can be done was applied
  110439. */
  110440. CustomOptimization.prototype.apply = function (scene, optimizer) {
  110441. if (this.onApply) {
  110442. return this.onApply(scene, optimizer);
  110443. }
  110444. return true;
  110445. };
  110446. return CustomOptimization;
  110447. }(SceneOptimization));
  110448. BABYLON.CustomOptimization = CustomOptimization;
  110449. /**
  110450. * Defines an optimization used to turn particles off
  110451. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  110452. */
  110453. var ParticlesOptimization = /** @class */ (function (_super) {
  110454. __extends(ParticlesOptimization, _super);
  110455. function ParticlesOptimization() {
  110456. return _super !== null && _super.apply(this, arguments) || this;
  110457. }
  110458. /**
  110459. * Gets a string describing the action executed by the current optimization
  110460. * @return description string
  110461. */
  110462. ParticlesOptimization.prototype.getDescription = function () {
  110463. return "Turning particles on/off";
  110464. };
  110465. /**
  110466. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  110467. * @param scene defines the current scene where to apply this optimization
  110468. * @param optimizer defines the current optimizer
  110469. * @returns true if everything that can be done was applied
  110470. */
  110471. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  110472. scene.particlesEnabled = optimizer.isInImprovementMode;
  110473. return true;
  110474. };
  110475. return ParticlesOptimization;
  110476. }(SceneOptimization));
  110477. BABYLON.ParticlesOptimization = ParticlesOptimization;
  110478. /**
  110479. * Defines an optimization used to turn render targets off
  110480. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  110481. */
  110482. var RenderTargetsOptimization = /** @class */ (function (_super) {
  110483. __extends(RenderTargetsOptimization, _super);
  110484. function RenderTargetsOptimization() {
  110485. return _super !== null && _super.apply(this, arguments) || this;
  110486. }
  110487. /**
  110488. * Gets a string describing the action executed by the current optimization
  110489. * @return description string
  110490. */
  110491. RenderTargetsOptimization.prototype.getDescription = function () {
  110492. return "Turning render targets off";
  110493. };
  110494. /**
  110495. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  110496. * @param scene defines the current scene where to apply this optimization
  110497. * @param optimizer defines the current optimizer
  110498. * @returns true if everything that can be done was applied
  110499. */
  110500. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  110501. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  110502. return true;
  110503. };
  110504. return RenderTargetsOptimization;
  110505. }(SceneOptimization));
  110506. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  110507. /**
  110508. * Defines an optimization used to merge meshes with compatible materials
  110509. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  110510. */
  110511. var MergeMeshesOptimization = /** @class */ (function (_super) {
  110512. __extends(MergeMeshesOptimization, _super);
  110513. function MergeMeshesOptimization() {
  110514. var _this = _super !== null && _super.apply(this, arguments) || this;
  110515. _this._canBeMerged = function (abstractMesh) {
  110516. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  110517. return false;
  110518. }
  110519. var mesh = abstractMesh;
  110520. if (mesh.isDisposed()) {
  110521. return false;
  110522. }
  110523. if (!mesh.isVisible || !mesh.isEnabled()) {
  110524. return false;
  110525. }
  110526. if (mesh.instances.length > 0) {
  110527. return false;
  110528. }
  110529. if (mesh.skeleton || mesh.hasLODLevels) {
  110530. return false;
  110531. }
  110532. return true;
  110533. };
  110534. return _this;
  110535. }
  110536. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  110537. /**
  110538. * Gets or sets a boolean which defines if optimization octree has to be updated
  110539. */
  110540. get: function () {
  110541. return MergeMeshesOptimization._UpdateSelectionTree;
  110542. },
  110543. /**
  110544. * Gets or sets a boolean which defines if optimization octree has to be updated
  110545. */
  110546. set: function (value) {
  110547. MergeMeshesOptimization._UpdateSelectionTree = value;
  110548. },
  110549. enumerable: true,
  110550. configurable: true
  110551. });
  110552. /**
  110553. * Gets a string describing the action executed by the current optimization
  110554. * @return description string
  110555. */
  110556. MergeMeshesOptimization.prototype.getDescription = function () {
  110557. return "Merging similar meshes together";
  110558. };
  110559. /**
  110560. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  110561. * @param scene defines the current scene where to apply this optimization
  110562. * @param optimizer defines the current optimizer
  110563. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  110564. * @returns true if everything that can be done was applied
  110565. */
  110566. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  110567. var globalPool = scene.meshes.slice(0);
  110568. var globalLength = globalPool.length;
  110569. for (var index = 0; index < globalLength; index++) {
  110570. var currentPool = new Array();
  110571. var current = globalPool[index];
  110572. // Checks
  110573. if (!this._canBeMerged(current)) {
  110574. continue;
  110575. }
  110576. currentPool.push(current);
  110577. // Find compatible meshes
  110578. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  110579. var otherMesh = globalPool[subIndex];
  110580. if (!this._canBeMerged(otherMesh)) {
  110581. continue;
  110582. }
  110583. if (otherMesh.material !== current.material) {
  110584. continue;
  110585. }
  110586. if (otherMesh.checkCollisions !== current.checkCollisions) {
  110587. continue;
  110588. }
  110589. currentPool.push(otherMesh);
  110590. globalLength--;
  110591. globalPool.splice(subIndex, 1);
  110592. subIndex--;
  110593. }
  110594. if (currentPool.length < 2) {
  110595. continue;
  110596. }
  110597. // Merge meshes
  110598. BABYLON.Mesh.MergeMeshes(currentPool, undefined, true);
  110599. }
  110600. // Call the octree system optimization if it is defined.
  110601. var sceneAsAny = scene;
  110602. if (sceneAsAny.createOrUpdateSelectionOctree) {
  110603. if (updateSelectionTree != undefined) {
  110604. if (updateSelectionTree) {
  110605. sceneAsAny.createOrUpdateSelectionOctree();
  110606. }
  110607. }
  110608. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  110609. sceneAsAny.createOrUpdateSelectionOctree();
  110610. }
  110611. }
  110612. return true;
  110613. };
  110614. MergeMeshesOptimization._UpdateSelectionTree = false;
  110615. return MergeMeshesOptimization;
  110616. }(SceneOptimization));
  110617. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  110618. /**
  110619. * Defines a list of options used by SceneOptimizer
  110620. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  110621. */
  110622. var SceneOptimizerOptions = /** @class */ (function () {
  110623. /**
  110624. * Creates a new list of options used by SceneOptimizer
  110625. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  110626. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  110627. */
  110628. function SceneOptimizerOptions(
  110629. /**
  110630. * Defines the target frame rate to reach (60 by default)
  110631. */
  110632. targetFrameRate,
  110633. /**
  110634. * Defines the interval between two checkes (2000ms by default)
  110635. */
  110636. trackerDuration) {
  110637. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  110638. if (trackerDuration === void 0) { trackerDuration = 2000; }
  110639. this.targetFrameRate = targetFrameRate;
  110640. this.trackerDuration = trackerDuration;
  110641. /**
  110642. * Gets the list of optimizations to apply
  110643. */
  110644. this.optimizations = new Array();
  110645. }
  110646. /**
  110647. * Add a new optimization
  110648. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  110649. * @returns the current SceneOptimizerOptions
  110650. */
  110651. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  110652. this.optimizations.push(optimization);
  110653. return this;
  110654. };
  110655. /**
  110656. * Add a new custom optimization
  110657. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  110658. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  110659. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  110660. * @returns the current SceneOptimizerOptions
  110661. */
  110662. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  110663. if (priority === void 0) { priority = 0; }
  110664. var optimization = new CustomOptimization(priority);
  110665. optimization.onApply = onApply;
  110666. optimization.onGetDescription = onGetDescription;
  110667. this.optimizations.push(optimization);
  110668. return this;
  110669. };
  110670. /**
  110671. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  110672. * @param targetFrameRate defines the target frame rate (60 by default)
  110673. * @returns a SceneOptimizerOptions object
  110674. */
  110675. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  110676. var result = new SceneOptimizerOptions(targetFrameRate);
  110677. var priority = 0;
  110678. result.addOptimization(new MergeMeshesOptimization(priority));
  110679. result.addOptimization(new ShadowsOptimization(priority));
  110680. result.addOptimization(new LensFlaresOptimization(priority));
  110681. // Next priority
  110682. priority++;
  110683. result.addOptimization(new PostProcessesOptimization(priority));
  110684. result.addOptimization(new ParticlesOptimization(priority));
  110685. // Next priority
  110686. priority++;
  110687. result.addOptimization(new TextureOptimization(priority, 1024));
  110688. return result;
  110689. };
  110690. /**
  110691. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  110692. * @param targetFrameRate defines the target frame rate (60 by default)
  110693. * @returns a SceneOptimizerOptions object
  110694. */
  110695. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  110696. var result = new SceneOptimizerOptions(targetFrameRate);
  110697. var priority = 0;
  110698. result.addOptimization(new MergeMeshesOptimization(priority));
  110699. result.addOptimization(new ShadowsOptimization(priority));
  110700. result.addOptimization(new LensFlaresOptimization(priority));
  110701. // Next priority
  110702. priority++;
  110703. result.addOptimization(new PostProcessesOptimization(priority));
  110704. result.addOptimization(new ParticlesOptimization(priority));
  110705. // Next priority
  110706. priority++;
  110707. result.addOptimization(new TextureOptimization(priority, 512));
  110708. // Next priority
  110709. priority++;
  110710. result.addOptimization(new RenderTargetsOptimization(priority));
  110711. // Next priority
  110712. priority++;
  110713. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  110714. return result;
  110715. };
  110716. /**
  110717. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  110718. * @param targetFrameRate defines the target frame rate (60 by default)
  110719. * @returns a SceneOptimizerOptions object
  110720. */
  110721. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  110722. var result = new SceneOptimizerOptions(targetFrameRate);
  110723. var priority = 0;
  110724. result.addOptimization(new MergeMeshesOptimization(priority));
  110725. result.addOptimization(new ShadowsOptimization(priority));
  110726. result.addOptimization(new LensFlaresOptimization(priority));
  110727. // Next priority
  110728. priority++;
  110729. result.addOptimization(new PostProcessesOptimization(priority));
  110730. result.addOptimization(new ParticlesOptimization(priority));
  110731. // Next priority
  110732. priority++;
  110733. result.addOptimization(new TextureOptimization(priority, 256));
  110734. // Next priority
  110735. priority++;
  110736. result.addOptimization(new RenderTargetsOptimization(priority));
  110737. // Next priority
  110738. priority++;
  110739. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  110740. return result;
  110741. };
  110742. return SceneOptimizerOptions;
  110743. }());
  110744. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  110745. /**
  110746. * Class used to run optimizations in order to reach a target frame rate
  110747. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  110748. */
  110749. var SceneOptimizer = /** @class */ (function () {
  110750. /**
  110751. * Creates a new SceneOptimizer
  110752. * @param scene defines the scene to work on
  110753. * @param options defines the options to use with the SceneOptimizer
  110754. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  110755. * @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)
  110756. */
  110757. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  110758. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  110759. if (improvementMode === void 0) { improvementMode = false; }
  110760. var _this = this;
  110761. this._isRunning = false;
  110762. this._currentPriorityLevel = 0;
  110763. this._targetFrameRate = 60;
  110764. this._trackerDuration = 2000;
  110765. this._currentFrameRate = 0;
  110766. this._improvementMode = false;
  110767. /**
  110768. * Defines an observable called when the optimizer reaches the target frame rate
  110769. */
  110770. this.onSuccessObservable = new BABYLON.Observable();
  110771. /**
  110772. * Defines an observable called when the optimizer enables an optimization
  110773. */
  110774. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  110775. /**
  110776. * Defines an observable called when the optimizer is not able to reach the target frame rate
  110777. */
  110778. this.onFailureObservable = new BABYLON.Observable();
  110779. if (!options) {
  110780. this._options = new SceneOptimizerOptions();
  110781. }
  110782. else {
  110783. this._options = options;
  110784. }
  110785. if (this._options.targetFrameRate) {
  110786. this._targetFrameRate = this._options.targetFrameRate;
  110787. }
  110788. if (this._options.trackerDuration) {
  110789. this._trackerDuration = this._options.trackerDuration;
  110790. }
  110791. if (autoGeneratePriorities) {
  110792. var priority = 0;
  110793. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  110794. var optim = _a[_i];
  110795. optim.priority = priority++;
  110796. }
  110797. }
  110798. this._improvementMode = improvementMode;
  110799. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  110800. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  110801. _this._sceneDisposeObserver = null;
  110802. _this.dispose();
  110803. });
  110804. }
  110805. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  110806. /**
  110807. * Gets a boolean indicating if the optimizer is in improvement mode
  110808. */
  110809. get: function () {
  110810. return this._improvementMode;
  110811. },
  110812. enumerable: true,
  110813. configurable: true
  110814. });
  110815. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  110816. /**
  110817. * Gets the current priority level (0 at start)
  110818. */
  110819. get: function () {
  110820. return this._currentPriorityLevel;
  110821. },
  110822. enumerable: true,
  110823. configurable: true
  110824. });
  110825. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  110826. /**
  110827. * Gets the current frame rate checked by the SceneOptimizer
  110828. */
  110829. get: function () {
  110830. return this._currentFrameRate;
  110831. },
  110832. enumerable: true,
  110833. configurable: true
  110834. });
  110835. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  110836. /**
  110837. * Gets or sets the current target frame rate (60 by default)
  110838. */
  110839. get: function () {
  110840. return this._targetFrameRate;
  110841. },
  110842. /**
  110843. * Gets or sets the current target frame rate (60 by default)
  110844. */
  110845. set: function (value) {
  110846. this._targetFrameRate = value;
  110847. },
  110848. enumerable: true,
  110849. configurable: true
  110850. });
  110851. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  110852. /**
  110853. * Gets or sets the current interval between two checks (every 2000ms by default)
  110854. */
  110855. get: function () {
  110856. return this._trackerDuration;
  110857. },
  110858. /**
  110859. * Gets or sets the current interval between two checks (every 2000ms by default)
  110860. */
  110861. set: function (value) {
  110862. this._trackerDuration = value;
  110863. },
  110864. enumerable: true,
  110865. configurable: true
  110866. });
  110867. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  110868. /**
  110869. * Gets the list of active optimizations
  110870. */
  110871. get: function () {
  110872. return this._options.optimizations;
  110873. },
  110874. enumerable: true,
  110875. configurable: true
  110876. });
  110877. /**
  110878. * Stops the current optimizer
  110879. */
  110880. SceneOptimizer.prototype.stop = function () {
  110881. this._isRunning = false;
  110882. };
  110883. /**
  110884. * Reset the optimizer to initial step (current priority level = 0)
  110885. */
  110886. SceneOptimizer.prototype.reset = function () {
  110887. this._currentPriorityLevel = 0;
  110888. };
  110889. /**
  110890. * Start the optimizer. By default it will try to reach a specific framerate
  110891. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  110892. */
  110893. SceneOptimizer.prototype.start = function () {
  110894. var _this = this;
  110895. if (this._isRunning) {
  110896. return;
  110897. }
  110898. this._isRunning = true;
  110899. // Let's wait for the scene to be ready before running our check
  110900. this._scene.executeWhenReady(function () {
  110901. setTimeout(function () {
  110902. _this._checkCurrentState();
  110903. }, _this._trackerDuration);
  110904. });
  110905. };
  110906. SceneOptimizer.prototype._checkCurrentState = function () {
  110907. var _this = this;
  110908. if (!this._isRunning) {
  110909. return;
  110910. }
  110911. var scene = this._scene;
  110912. var options = this._options;
  110913. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  110914. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  110915. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  110916. this._isRunning = false;
  110917. this.onSuccessObservable.notifyObservers(this);
  110918. return;
  110919. }
  110920. // Apply current level of optimizations
  110921. var allDone = true;
  110922. var noOptimizationApplied = true;
  110923. for (var index = 0; index < options.optimizations.length; index++) {
  110924. var optimization = options.optimizations[index];
  110925. if (optimization.priority === this._currentPriorityLevel) {
  110926. noOptimizationApplied = false;
  110927. allDone = allDone && optimization.apply(scene, this);
  110928. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  110929. }
  110930. }
  110931. // If no optimization was applied, this is a failure :(
  110932. if (noOptimizationApplied) {
  110933. this._isRunning = false;
  110934. this.onFailureObservable.notifyObservers(this);
  110935. return;
  110936. }
  110937. // If all optimizations were done, move to next level
  110938. if (allDone) {
  110939. this._currentPriorityLevel++;
  110940. }
  110941. // Let's the system running for a specific amount of time before checking FPS
  110942. scene.executeWhenReady(function () {
  110943. setTimeout(function () {
  110944. _this._checkCurrentState();
  110945. }, _this._trackerDuration);
  110946. });
  110947. };
  110948. /**
  110949. * Release all resources
  110950. */
  110951. SceneOptimizer.prototype.dispose = function () {
  110952. this.stop();
  110953. this.onSuccessObservable.clear();
  110954. this.onFailureObservable.clear();
  110955. this.onNewOptimizationAppliedObservable.clear();
  110956. if (this._sceneDisposeObserver) {
  110957. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  110958. }
  110959. };
  110960. /**
  110961. * Helper function to create a SceneOptimizer with one single line of code
  110962. * @param scene defines the scene to work on
  110963. * @param options defines the options to use with the SceneOptimizer
  110964. * @param onSuccess defines a callback to call on success
  110965. * @param onFailure defines a callback to call on failure
  110966. * @returns the new SceneOptimizer object
  110967. */
  110968. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  110969. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  110970. if (onSuccess) {
  110971. optimizer.onSuccessObservable.add(function () {
  110972. onSuccess();
  110973. });
  110974. }
  110975. if (onFailure) {
  110976. optimizer.onFailureObservable.add(function () {
  110977. onFailure();
  110978. });
  110979. }
  110980. optimizer.start();
  110981. return optimizer;
  110982. };
  110983. return SceneOptimizer;
  110984. }());
  110985. BABYLON.SceneOptimizer = SceneOptimizer;
  110986. })(BABYLON || (BABYLON = {}));
  110987. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  110988. var BABYLON;
  110989. (function (BABYLON) {
  110990. /**
  110991. * Gets the outline renderer associated with the scene
  110992. * @returns a OutlineRenderer
  110993. */
  110994. BABYLON.Scene.prototype.getOutlineRenderer = function () {
  110995. if (!this._outlineRenderer) {
  110996. this._outlineRenderer = new OutlineRenderer(this);
  110997. }
  110998. return this._outlineRenderer;
  110999. };
  111000. Object.defineProperty(BABYLON.AbstractMesh.prototype, "renderOutline", {
  111001. get: function () {
  111002. return this._renderOutline;
  111003. },
  111004. set: function (value) {
  111005. if (value) {
  111006. // Lazy Load the component.
  111007. this.getScene().getOutlineRenderer();
  111008. }
  111009. this._renderOutline = value;
  111010. },
  111011. enumerable: true,
  111012. configurable: true
  111013. });
  111014. Object.defineProperty(BABYLON.AbstractMesh.prototype, "renderOverlay", {
  111015. get: function () {
  111016. return this._renderOverlay;
  111017. },
  111018. set: function (value) {
  111019. if (value) {
  111020. // Lazy Load the component.
  111021. this.getScene().getOutlineRenderer();
  111022. }
  111023. this._renderOverlay = value;
  111024. },
  111025. enumerable: true,
  111026. configurable: true
  111027. });
  111028. /**
  111029. * This class is responsible to draw bothe outline/overlay of meshes.
  111030. * It should not be used directly but through the available method on mesh.
  111031. */
  111032. var OutlineRenderer = /** @class */ (function () {
  111033. /**
  111034. * Instantiates a new outline renderer. (There could be only one per scene).
  111035. * @param scene Defines the scene it belongs to
  111036. */
  111037. function OutlineRenderer(scene) {
  111038. /**
  111039. * The name of the component. Each component must have a unique name.
  111040. */
  111041. this.name = BABYLON.SceneComponentConstants.NAME_OUTLINERENDERER;
  111042. /**
  111043. * Defines a zOffset to prevent zFighting between the overlay and the mesh.
  111044. */
  111045. this.zOffset = 1;
  111046. this.scene = scene;
  111047. this._engine = scene.getEngine();
  111048. this.scene._addComponent(this);
  111049. }
  111050. /**
  111051. * Register the component to one instance of a scene.
  111052. */
  111053. OutlineRenderer.prototype.register = function () {
  111054. this.scene._beforeRenderingMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORERENDERINGMESH_OUTLINE, this, this._beforeRenderingMesh);
  111055. this.scene._afterRenderingMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGMESH_OUTLINE, this, this._afterRenderingMesh);
  111056. };
  111057. /**
  111058. * Rebuilds the elements related to this component in case of
  111059. * context lost for instance.
  111060. */
  111061. OutlineRenderer.prototype.rebuild = function () {
  111062. // Nothing to do here.
  111063. };
  111064. /**
  111065. * Disposes the component and the associated ressources.
  111066. */
  111067. OutlineRenderer.prototype.dispose = function () {
  111068. // Nothing to do here.
  111069. };
  111070. /**
  111071. * Renders the outline in the canvas.
  111072. * @param subMesh Defines the sumesh to render
  111073. * @param batch Defines the batch of meshes in case of instances
  111074. * @param useOverlay Defines if the rendering is for the overlay or the outline
  111075. */
  111076. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  111077. var _this = this;
  111078. if (useOverlay === void 0) { useOverlay = false; }
  111079. var scene = this.scene;
  111080. var engine = scene.getEngine();
  111081. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  111082. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  111083. return;
  111084. }
  111085. var mesh = subMesh.getRenderingMesh();
  111086. var material = subMesh.getMaterial();
  111087. if (!material || !scene.activeCamera) {
  111088. return;
  111089. }
  111090. engine.enableEffect(this._effect);
  111091. // Logarithmic depth
  111092. if (material.useLogarithmicDepth) {
  111093. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  111094. }
  111095. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  111096. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  111097. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  111098. // Bones
  111099. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  111100. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  111101. }
  111102. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  111103. // Alpha test
  111104. if (material && material.needAlphaTesting()) {
  111105. var alphaTexture = material.getAlphaTestTexture();
  111106. if (alphaTexture) {
  111107. this._effect.setTexture("diffuseSampler", alphaTexture);
  111108. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  111109. }
  111110. }
  111111. engine.setZOffset(-this.zOffset);
  111112. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  111113. engine.setZOffset(0);
  111114. };
  111115. /**
  111116. * Returns whether or not the outline renderer is ready for a given submesh.
  111117. * All the dependencies e.g. submeshes, texture, effect... mus be ready
  111118. * @param subMesh Defines the submesh to check readyness for
  111119. * @param useInstances Defines wheter wee are trying to render instances or not
  111120. * @returns true if ready otherwise false
  111121. */
  111122. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  111123. var defines = [];
  111124. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  111125. var mesh = subMesh.getMesh();
  111126. var material = subMesh.getMaterial();
  111127. if (material) {
  111128. // Alpha test
  111129. if (material.needAlphaTesting()) {
  111130. defines.push("#define ALPHATEST");
  111131. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  111132. attribs.push(BABYLON.VertexBuffer.UVKind);
  111133. defines.push("#define UV1");
  111134. }
  111135. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  111136. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  111137. defines.push("#define UV2");
  111138. }
  111139. }
  111140. //Logarithmic depth
  111141. if (material.useLogarithmicDepth) {
  111142. defines.push("#define LOGARITHMICDEPTH");
  111143. }
  111144. }
  111145. // Bones
  111146. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  111147. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  111148. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  111149. if (mesh.numBoneInfluencers > 4) {
  111150. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  111151. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  111152. }
  111153. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  111154. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  111155. }
  111156. else {
  111157. defines.push("#define NUM_BONE_INFLUENCERS 0");
  111158. }
  111159. // Instances
  111160. if (useInstances) {
  111161. defines.push("#define INSTANCES");
  111162. attribs.push("world0");
  111163. attribs.push("world1");
  111164. attribs.push("world2");
  111165. attribs.push("world3");
  111166. }
  111167. // Get correct effect
  111168. var join = defines.join("\n");
  111169. if (this._cachedDefines !== join) {
  111170. this._cachedDefines = join;
  111171. this._effect = this.scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  111172. }
  111173. return this._effect.isReady();
  111174. };
  111175. OutlineRenderer.prototype._beforeRenderingMesh = function (mesh, subMesh, batch) {
  111176. // Outline - step 1
  111177. this._savedDepthWrite = this._engine.getDepthWrite();
  111178. if (mesh.renderOutline) {
  111179. this._engine.setDepthWrite(false);
  111180. this.render(subMesh, batch);
  111181. this._engine.setDepthWrite(this._savedDepthWrite);
  111182. }
  111183. };
  111184. OutlineRenderer.prototype._afterRenderingMesh = function (mesh, subMesh, batch) {
  111185. // Outline - step 2
  111186. if (mesh.renderOutline && this._savedDepthWrite) {
  111187. this._engine.setDepthWrite(true);
  111188. this._engine.setColorWrite(false);
  111189. this.render(subMesh, batch);
  111190. this._engine.setColorWrite(true);
  111191. }
  111192. // Overlay
  111193. if (mesh.renderOverlay) {
  111194. var currentMode = this._engine.getAlphaMode();
  111195. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  111196. this.render(subMesh, batch, true);
  111197. this._engine.setAlphaMode(currentMode);
  111198. }
  111199. };
  111200. return OutlineRenderer;
  111201. }());
  111202. BABYLON.OutlineRenderer = OutlineRenderer;
  111203. })(BABYLON || (BABYLON = {}));
  111204. //# sourceMappingURL=babylon.outlineRenderer.js.map
  111205. var BABYLON;
  111206. (function (BABYLON) {
  111207. BABYLON.AbstractMesh.prototype.disableEdgesRendering = function () {
  111208. if (this._edgesRenderer) {
  111209. this._edgesRenderer.dispose();
  111210. this._edgesRenderer = null;
  111211. }
  111212. return this;
  111213. };
  111214. BABYLON.AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  111215. if (epsilon === void 0) { epsilon = 0.95; }
  111216. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  111217. this.disableEdgesRendering();
  111218. this._edgesRenderer = new EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  111219. return this;
  111220. };
  111221. Object.defineProperty(BABYLON.AbstractMesh.prototype, "edgesRenderer", {
  111222. get: function () {
  111223. return this._edgesRenderer;
  111224. },
  111225. enumerable: true,
  111226. configurable: true
  111227. });
  111228. BABYLON.LinesMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  111229. if (epsilon === void 0) { epsilon = 0.95; }
  111230. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  111231. this.disableEdgesRendering();
  111232. this._edgesRenderer = new BABYLON.LineEdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  111233. return this;
  111234. };
  111235. BABYLON.InstancedLinesMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  111236. if (epsilon === void 0) { epsilon = 0.95; }
  111237. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  111238. BABYLON.LinesMesh.prototype.enableEdgesRendering.apply(this, arguments);
  111239. return this;
  111240. };
  111241. /**
  111242. * FaceAdjacencies Helper class to generate edges
  111243. */
  111244. var FaceAdjacencies = /** @class */ (function () {
  111245. function FaceAdjacencies() {
  111246. this.edges = new Array();
  111247. this.edgesConnectedCount = 0;
  111248. }
  111249. return FaceAdjacencies;
  111250. }());
  111251. /**
  111252. * This class is used to generate edges of the mesh that could then easily be rendered in a scene.
  111253. */
  111254. var EdgesRenderer = /** @class */ (function () {
  111255. /**
  111256. * Creates an instance of the EdgesRenderer. It is primarily use to display edges of a mesh.
  111257. * Beware when you use this class with complex objects as the adjacencies computation can be really long
  111258. * @param source Mesh used to create edges
  111259. * @param epsilon sum of angles in adjacency to check for edge
  111260. * @param checkVerticesInsteadOfIndices
  111261. * @param generateEdgesLines - should generate Lines or only prepare resources.
  111262. */
  111263. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices, generateEdgesLines) {
  111264. if (epsilon === void 0) { epsilon = 0.95; }
  111265. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  111266. if (generateEdgesLines === void 0) { generateEdgesLines = true; }
  111267. var _this = this;
  111268. /**
  111269. * Define the size of the edges with an orthographic camera
  111270. */
  111271. this.edgesWidthScalerForOrthographic = 1000.0;
  111272. /**
  111273. * Define the size of the edges with a perspective camera
  111274. */
  111275. this.edgesWidthScalerForPerspective = 50.0;
  111276. this._linesPositions = new Array();
  111277. this._linesNormals = new Array();
  111278. this._linesIndices = new Array();
  111279. this._buffers = {};
  111280. this._checkVerticesInsteadOfIndices = false;
  111281. /** Gets or sets a boolean indicating if the edgesRenderer is active */
  111282. this.isEnabled = true;
  111283. this._source = source;
  111284. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  111285. this._epsilon = epsilon;
  111286. this._prepareRessources();
  111287. if (generateEdgesLines) {
  111288. this._generateEdgesLines();
  111289. }
  111290. this._meshRebuildObserver = this._source.onRebuildObservable.add(function () {
  111291. _this._rebuild();
  111292. });
  111293. this._meshDisposeObserver = this._source.onDisposeObservable.add(function () {
  111294. _this.dispose();
  111295. });
  111296. }
  111297. EdgesRenderer.prototype._prepareRessources = function () {
  111298. if (this._lineShader) {
  111299. return;
  111300. }
  111301. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  111302. attributes: ["position", "normal"],
  111303. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  111304. });
  111305. this._lineShader.disableDepthWrite = true;
  111306. this._lineShader.backFaceCulling = false;
  111307. };
  111308. /** @hidden */
  111309. EdgesRenderer.prototype._rebuild = function () {
  111310. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  111311. if (buffer) {
  111312. buffer._rebuild();
  111313. }
  111314. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  111315. if (buffer) {
  111316. buffer._rebuild();
  111317. }
  111318. var scene = this._source.getScene();
  111319. var engine = scene.getEngine();
  111320. this._ib = engine.createIndexBuffer(this._linesIndices);
  111321. };
  111322. /**
  111323. * Releases the required resources for the edges renderer
  111324. */
  111325. EdgesRenderer.prototype.dispose = function () {
  111326. this._source.onRebuildObservable.remove(this._meshRebuildObserver);
  111327. this._source.onDisposeObservable.remove(this._meshDisposeObserver);
  111328. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  111329. if (buffer) {
  111330. buffer.dispose();
  111331. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  111332. }
  111333. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  111334. if (buffer) {
  111335. buffer.dispose();
  111336. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  111337. }
  111338. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  111339. this._lineShader.dispose();
  111340. };
  111341. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  111342. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  111343. return 0;
  111344. }
  111345. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  111346. return 1;
  111347. }
  111348. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  111349. return 2;
  111350. }
  111351. return -1;
  111352. };
  111353. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  111354. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  111355. return 0;
  111356. }
  111357. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  111358. return 1;
  111359. }
  111360. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  111361. return 2;
  111362. }
  111363. return -1;
  111364. };
  111365. /**
  111366. * Checks if the pair of p0 and p1 is en edge
  111367. * @param faceIndex
  111368. * @param edge
  111369. * @param faceNormals
  111370. * @param p0
  111371. * @param p1
  111372. * @private
  111373. */
  111374. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  111375. var needToCreateLine;
  111376. if (edge === undefined) {
  111377. needToCreateLine = true;
  111378. }
  111379. else {
  111380. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  111381. needToCreateLine = dotProduct < this._epsilon;
  111382. }
  111383. if (needToCreateLine) {
  111384. this.createLine(p0, p1, this._linesPositions.length / 3);
  111385. }
  111386. };
  111387. /**
  111388. * push line into the position, normal and index buffer
  111389. * @protected
  111390. */
  111391. EdgesRenderer.prototype.createLine = function (p0, p1, offset) {
  111392. // Positions
  111393. this._linesPositions.push(p0.x, p0.y, p0.z, p0.x, p0.y, p0.z, p1.x, p1.y, p1.z, p1.x, p1.y, p1.z);
  111394. // Normals
  111395. this._linesNormals.push(p1.x, p1.y, p1.z, -1, p1.x, p1.y, p1.z, 1, p0.x, p0.y, p0.z, -1, p0.x, p0.y, p0.z, 1);
  111396. // Indices
  111397. this._linesIndices.push(offset, offset + 1, offset + 2, offset, offset + 2, offset + 3);
  111398. };
  111399. /**
  111400. * Generates lines edges from adjacencjes
  111401. * @private
  111402. */
  111403. EdgesRenderer.prototype._generateEdgesLines = function () {
  111404. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  111405. var indices = this._source.getIndices();
  111406. if (!indices || !positions) {
  111407. return;
  111408. }
  111409. // First let's find adjacencies
  111410. var adjacencies = new Array();
  111411. var faceNormals = new Array();
  111412. var index;
  111413. var faceAdjacencies;
  111414. // Prepare faces
  111415. for (index = 0; index < indices.length; index += 3) {
  111416. faceAdjacencies = new FaceAdjacencies();
  111417. var p0Index = indices[index];
  111418. var p1Index = indices[index + 1];
  111419. var p2Index = indices[index + 2];
  111420. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  111421. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  111422. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  111423. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  111424. faceNormal.normalize();
  111425. faceNormals.push(faceNormal);
  111426. adjacencies.push(faceAdjacencies);
  111427. }
  111428. // Scan
  111429. for (index = 0; index < adjacencies.length; index++) {
  111430. faceAdjacencies = adjacencies[index];
  111431. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  111432. var otherFaceAdjacencies = adjacencies[otherIndex];
  111433. if (faceAdjacencies.edgesConnectedCount === 3) { // Full
  111434. break;
  111435. }
  111436. if (otherFaceAdjacencies.edgesConnectedCount === 3) { // Full
  111437. continue;
  111438. }
  111439. var otherP0 = indices[otherIndex * 3];
  111440. var otherP1 = indices[otherIndex * 3 + 1];
  111441. var otherP2 = indices[otherIndex * 3 + 2];
  111442. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  111443. var otherEdgeIndex = 0;
  111444. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  111445. continue;
  111446. }
  111447. switch (edgeIndex) {
  111448. case 0:
  111449. if (this._checkVerticesInsteadOfIndices) {
  111450. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  111451. }
  111452. else {
  111453. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  111454. }
  111455. break;
  111456. case 1:
  111457. if (this._checkVerticesInsteadOfIndices) {
  111458. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  111459. }
  111460. else {
  111461. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  111462. }
  111463. break;
  111464. case 2:
  111465. if (this._checkVerticesInsteadOfIndices) {
  111466. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  111467. }
  111468. else {
  111469. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  111470. }
  111471. break;
  111472. }
  111473. if (otherEdgeIndex === -1) {
  111474. continue;
  111475. }
  111476. faceAdjacencies.edges[edgeIndex] = otherIndex;
  111477. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  111478. faceAdjacencies.edgesConnectedCount++;
  111479. otherFaceAdjacencies.edgesConnectedCount++;
  111480. if (faceAdjacencies.edgesConnectedCount === 3) {
  111481. break;
  111482. }
  111483. }
  111484. }
  111485. }
  111486. // Create lines
  111487. for (index = 0; index < adjacencies.length; index++) {
  111488. // 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
  111489. var current = adjacencies[index];
  111490. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  111491. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  111492. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  111493. }
  111494. // Merge into a single mesh
  111495. var engine = this._source.getScene().getEngine();
  111496. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  111497. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  111498. this._ib = engine.createIndexBuffer(this._linesIndices);
  111499. this._indicesCount = this._linesIndices.length;
  111500. };
  111501. /**
  111502. * Checks wether or not the edges renderer is ready to render.
  111503. * @return true if ready, otherwise false.
  111504. */
  111505. EdgesRenderer.prototype.isReady = function () {
  111506. return this._lineShader.isReady();
  111507. };
  111508. /**
  111509. * Renders the edges of the attached mesh,
  111510. */
  111511. EdgesRenderer.prototype.render = function () {
  111512. var scene = this._source.getScene();
  111513. if (!this.isReady() || !scene.activeCamera) {
  111514. return;
  111515. }
  111516. var engine = scene.getEngine();
  111517. this._lineShader._preBind();
  111518. if (this._source.edgesColor.a !== 1) {
  111519. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  111520. }
  111521. else {
  111522. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  111523. }
  111524. // VBOs
  111525. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  111526. scene.resetCachedMaterial();
  111527. this._lineShader.setColor4("color", this._source.edgesColor);
  111528. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  111529. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  111530. }
  111531. else {
  111532. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  111533. }
  111534. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  111535. this._lineShader.bind(this._source.getWorldMatrix());
  111536. // Draw order
  111537. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  111538. this._lineShader.unbind();
  111539. };
  111540. return EdgesRenderer;
  111541. }());
  111542. BABYLON.EdgesRenderer = EdgesRenderer;
  111543. })(BABYLON || (BABYLON = {}));
  111544. //# sourceMappingURL=babylon.edgesRenderer.js.map
  111545. var BABYLON;
  111546. (function (BABYLON) {
  111547. /**
  111548. * LineEdgesRenderer for LineMeshes to remove unnecessary triangulation
  111549. */
  111550. var LineEdgesRenderer = /** @class */ (function (_super) {
  111551. __extends(LineEdgesRenderer, _super);
  111552. /**
  111553. * This constructor turns off auto generating edges line in Edges Renderer to make it here.
  111554. * @param source LineMesh used to generate edges
  111555. * @param epsilon not important (specified angle for edge detection)
  111556. * @param checkVerticesInsteadOfIndices not important for LineMesh
  111557. */
  111558. function LineEdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  111559. if (epsilon === void 0) { epsilon = 0.95; }
  111560. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  111561. var _this = _super.call(this, source, epsilon, checkVerticesInsteadOfIndices, false) || this;
  111562. _this._generateEdgesLines();
  111563. return _this;
  111564. }
  111565. /**
  111566. * Generate edges for each line in LinesMesh. Every Line should be rendered as edge.
  111567. */
  111568. LineEdgesRenderer.prototype._generateEdgesLines = function () {
  111569. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  111570. var indices = this._source.getIndices();
  111571. if (!indices || !positions) {
  111572. return;
  111573. }
  111574. var p0 = BABYLON.Tmp.Vector3[0];
  111575. var p1 = BABYLON.Tmp.Vector3[1];
  111576. var len = indices.length - 1;
  111577. for (var i = 0, offset = 0; i < len; i += 2, offset += 4) {
  111578. BABYLON.Vector3.FromArrayToRef(positions, 3 * indices[i], p0);
  111579. BABYLON.Vector3.FromArrayToRef(positions, 3 * indices[i + 1], p1);
  111580. this.createLine(p0, p1, offset);
  111581. }
  111582. // Merge into a single mesh
  111583. var engine = this._source.getScene().getEngine();
  111584. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  111585. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  111586. this._ib = engine.createIndexBuffer(this._linesIndices);
  111587. this._indicesCount = this._linesIndices.length;
  111588. };
  111589. return LineEdgesRenderer;
  111590. }(BABYLON.EdgesRenderer));
  111591. BABYLON.LineEdgesRenderer = LineEdgesRenderer;
  111592. })(BABYLON || (BABYLON = {}));
  111593. //# sourceMappingURL=babylon.lineEdgesRenderer.js.map
  111594. var BABYLON;
  111595. (function (BABYLON) {
  111596. // Adds the parser to the scene parsers.
  111597. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER, function (parsedData, scene, container, rootUrl) {
  111598. if (parsedData.effectLayers) {
  111599. if (!container.effectLayers) {
  111600. container.effectLayers = new Array();
  111601. }
  111602. for (var index = 0; index < parsedData.effectLayers.length; index++) {
  111603. var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
  111604. container.effectLayers.push(effectLayer);
  111605. }
  111606. }
  111607. });
  111608. BABYLON.AbstractScene.prototype.removeEffectLayer = function (toRemove) {
  111609. var index = this.effectLayers.indexOf(toRemove);
  111610. if (index !== -1) {
  111611. this.effectLayers.splice(index, 1);
  111612. }
  111613. return index;
  111614. };
  111615. BABYLON.AbstractScene.prototype.addEffectLayer = function (newEffectLayer) {
  111616. this.effectLayers.push(newEffectLayer);
  111617. };
  111618. /**
  111619. * Defines the layer scene component responsible to manage any effect layers
  111620. * in a given scene.
  111621. */
  111622. var EffectLayerSceneComponent = /** @class */ (function () {
  111623. /**
  111624. * Creates a new instance of the component for the given scene
  111625. * @param scene Defines the scene to register the component in
  111626. */
  111627. function EffectLayerSceneComponent(scene) {
  111628. /**
  111629. * The component name helpfull to identify the component in the list of scene components.
  111630. */
  111631. this.name = BABYLON.SceneComponentConstants.NAME_EFFECTLAYER;
  111632. this._renderEffects = false;
  111633. this._needStencil = false;
  111634. this._previousStencilState = false;
  111635. this.scene = scene;
  111636. this._engine = scene.getEngine();
  111637. scene.effectLayers = new Array();
  111638. }
  111639. /**
  111640. * Registers the component in a given scene
  111641. */
  111642. EffectLayerSceneComponent.prototype.register = function () {
  111643. this.scene._isReadyForMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER, this, this._isReadyForMesh);
  111644. this.scene._cameraDrawRenderTargetStage.registerStep(BABYLON.SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER, this, this._renderMainTexture);
  111645. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER, this, this._setStencil);
  111646. this.scene._afterRenderingGroupDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW, this, this._drawRenderingGroup);
  111647. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER, this, this._setStencilBack);
  111648. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW, this, this._drawCamera);
  111649. };
  111650. /**
  111651. * Rebuilds the elements related to this component in case of
  111652. * context lost for instance.
  111653. */
  111654. EffectLayerSceneComponent.prototype.rebuild = function () {
  111655. var layers = this.scene.effectLayers;
  111656. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  111657. var effectLayer = layers_1[_i];
  111658. effectLayer._rebuild();
  111659. }
  111660. };
  111661. /**
  111662. * Serializes the component data to the specified json object
  111663. * @param serializationObject The object to serialize to
  111664. */
  111665. EffectLayerSceneComponent.prototype.serialize = function (serializationObject) {
  111666. // Effect layers
  111667. serializationObject.effectLayers = [];
  111668. var layers = this.scene.effectLayers;
  111669. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  111670. var effectLayer = layers_2[_i];
  111671. if (effectLayer.serialize) {
  111672. serializationObject.effectLayers.push(effectLayer.serialize());
  111673. }
  111674. }
  111675. };
  111676. /**
  111677. * Adds all the element from the container to the scene
  111678. * @param container the container holding the elements
  111679. */
  111680. EffectLayerSceneComponent.prototype.addFromContainer = function (container) {
  111681. var _this = this;
  111682. if (!container.effectLayers) {
  111683. return;
  111684. }
  111685. container.effectLayers.forEach(function (o) {
  111686. _this.scene.addEffectLayer(o);
  111687. });
  111688. };
  111689. /**
  111690. * Removes all the elements in the container from the scene
  111691. * @param container contains the elements to remove
  111692. */
  111693. EffectLayerSceneComponent.prototype.removeFromContainer = function (container) {
  111694. var _this = this;
  111695. if (!container.effectLayers) {
  111696. return;
  111697. }
  111698. container.effectLayers.forEach(function (o) {
  111699. _this.scene.removeEffectLayer(o);
  111700. });
  111701. };
  111702. /**
  111703. * Disposes the component and the associated ressources.
  111704. */
  111705. EffectLayerSceneComponent.prototype.dispose = function () {
  111706. var layers = this.scene.effectLayers;
  111707. while (layers.length) {
  111708. layers[0].dispose();
  111709. }
  111710. };
  111711. EffectLayerSceneComponent.prototype._isReadyForMesh = function (mesh, hardwareInstancedRendering) {
  111712. var layers = this.scene.effectLayers;
  111713. for (var _i = 0, layers_3 = layers; _i < layers_3.length; _i++) {
  111714. var layer = layers_3[_i];
  111715. if (!layer.hasMesh(mesh)) {
  111716. continue;
  111717. }
  111718. for (var _a = 0, _b = mesh.subMeshes; _a < _b.length; _a++) {
  111719. var subMesh = _b[_a];
  111720. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  111721. return false;
  111722. }
  111723. }
  111724. }
  111725. return true;
  111726. };
  111727. EffectLayerSceneComponent.prototype._renderMainTexture = function (camera) {
  111728. this._renderEffects = false;
  111729. this._needStencil = false;
  111730. var layers = this.scene.effectLayers;
  111731. if (layers && layers.length > 0) {
  111732. this._previousStencilState = this._engine.getStencilBuffer();
  111733. for (var _i = 0, layers_4 = layers; _i < layers_4.length; _i++) {
  111734. var effectLayer = layers_4[_i];
  111735. if (effectLayer.shouldRender() &&
  111736. (!effectLayer.camera ||
  111737. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  111738. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  111739. this._renderEffects = true;
  111740. this._needStencil = this._needStencil || effectLayer.needStencil();
  111741. var renderTarget = effectLayer._mainTexture;
  111742. if (renderTarget._shouldRender()) {
  111743. this.scene.incrementRenderId();
  111744. renderTarget.render(false, false);
  111745. }
  111746. }
  111747. }
  111748. this.scene.incrementRenderId();
  111749. }
  111750. };
  111751. EffectLayerSceneComponent.prototype._setStencil = function (camera) {
  111752. // Activate effect Layer stencil
  111753. if (this._needStencil) {
  111754. this._engine.setStencilBuffer(true);
  111755. }
  111756. };
  111757. EffectLayerSceneComponent.prototype._setStencilBack = function (camera) {
  111758. // Restore effect Layer stencil
  111759. if (this._needStencil) {
  111760. this._engine.setStencilBuffer(this._previousStencilState);
  111761. }
  111762. };
  111763. EffectLayerSceneComponent.prototype._draw = function (renderingGroupId) {
  111764. if (this._renderEffects) {
  111765. this._engine.setDepthBuffer(false);
  111766. var layers = this.scene.effectLayers;
  111767. for (var i = 0; i < layers.length; i++) {
  111768. var effectLayer = layers[i];
  111769. if (effectLayer.renderingGroupId === renderingGroupId) {
  111770. if (effectLayer.shouldRender()) {
  111771. effectLayer.render();
  111772. }
  111773. }
  111774. }
  111775. this._engine.setDepthBuffer(true);
  111776. }
  111777. };
  111778. EffectLayerSceneComponent.prototype._drawCamera = function (camera) {
  111779. if (this._renderEffects) {
  111780. this._draw(-1);
  111781. }
  111782. };
  111783. EffectLayerSceneComponent.prototype._drawRenderingGroup = function (index) {
  111784. if (!this.scene._isInIntermediateRendering() && this._renderEffects) {
  111785. this._draw(index);
  111786. }
  111787. };
  111788. return EffectLayerSceneComponent;
  111789. }());
  111790. BABYLON.EffectLayerSceneComponent = EffectLayerSceneComponent;
  111791. })(BABYLON || (BABYLON = {}));
  111792. //# sourceMappingURL=babylon.effectLayerSceneComponent.js.map
  111793. var __assign = (this && this.__assign) || function () {
  111794. __assign = Object.assign || function(t) {
  111795. for (var s, i = 1, n = arguments.length; i < n; i++) {
  111796. s = arguments[i];
  111797. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  111798. t[p] = s[p];
  111799. }
  111800. return t;
  111801. };
  111802. return __assign.apply(this, arguments);
  111803. };
  111804. var BABYLON;
  111805. (function (BABYLON) {
  111806. /**
  111807. * The effect layer Helps adding post process effect blended with the main pass.
  111808. *
  111809. * This can be for instance use to generate glow or higlight effects on the scene.
  111810. *
  111811. * The effect layer class can not be used directly and is intented to inherited from to be
  111812. * customized per effects.
  111813. */
  111814. var EffectLayer = /** @class */ (function () {
  111815. /**
  111816. * Instantiates a new effect Layer and references it in the scene.
  111817. * @param name The name of the layer
  111818. * @param scene The scene to use the layer in
  111819. */
  111820. function EffectLayer(
  111821. /** The Friendly of the effect in the scene */
  111822. name, scene) {
  111823. this._vertexBuffers = {};
  111824. this._maxSize = 0;
  111825. this._mainTextureDesiredSize = { width: 0, height: 0 };
  111826. this._shouldRender = true;
  111827. this._postProcesses = [];
  111828. this._textures = [];
  111829. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  111830. /**
  111831. * The clear color of the texture used to generate the glow map.
  111832. */
  111833. this.neutralColor = new BABYLON.Color4();
  111834. /**
  111835. * Specifies wether the highlight layer is enabled or not.
  111836. */
  111837. this.isEnabled = true;
  111838. /**
  111839. * An event triggered when the effect layer has been disposed.
  111840. */
  111841. this.onDisposeObservable = new BABYLON.Observable();
  111842. /**
  111843. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  111844. */
  111845. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  111846. /**
  111847. * An event triggered when the generated texture is being merged in the scene.
  111848. */
  111849. this.onBeforeComposeObservable = new BABYLON.Observable();
  111850. /**
  111851. * An event triggered when the generated texture has been merged in the scene.
  111852. */
  111853. this.onAfterComposeObservable = new BABYLON.Observable();
  111854. /**
  111855. * An event triggered when the efffect layer changes its size.
  111856. */
  111857. this.onSizeChangedObservable = new BABYLON.Observable();
  111858. this.name = name;
  111859. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  111860. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER);
  111861. if (!component) {
  111862. component = new BABYLON.EffectLayerSceneComponent(this._scene);
  111863. this._scene._addComponent(component);
  111864. }
  111865. this._engine = this._scene.getEngine();
  111866. this._maxSize = this._engine.getCaps().maxTextureSize;
  111867. this._scene.effectLayers.push(this);
  111868. // Generate Buffers
  111869. this._generateIndexBuffer();
  111870. this._genrateVertexBuffer();
  111871. }
  111872. Object.defineProperty(EffectLayer.prototype, "camera", {
  111873. /**
  111874. * Gets the camera attached to the layer.
  111875. */
  111876. get: function () {
  111877. return this._effectLayerOptions.camera;
  111878. },
  111879. enumerable: true,
  111880. configurable: true
  111881. });
  111882. Object.defineProperty(EffectLayer.prototype, "renderingGroupId", {
  111883. /**
  111884. * Gets the rendering group id the layer should render in.
  111885. */
  111886. get: function () {
  111887. return this._effectLayerOptions.renderingGroupId;
  111888. },
  111889. enumerable: true,
  111890. configurable: true
  111891. });
  111892. /**
  111893. * Initializes the effect layer with the required options.
  111894. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  111895. */
  111896. EffectLayer.prototype._init = function (options) {
  111897. // Adapt options
  111898. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null, renderingGroupId: -1 }, options);
  111899. this._setMainTextureSize();
  111900. this._createMainTexture();
  111901. this._createTextureAndPostProcesses();
  111902. this._mergeEffect = this._createMergeEffect();
  111903. };
  111904. /**
  111905. * Generates the index buffer of the full screen quad blending to the main canvas.
  111906. */
  111907. EffectLayer.prototype._generateIndexBuffer = function () {
  111908. // Indices
  111909. var indices = [];
  111910. indices.push(0);
  111911. indices.push(1);
  111912. indices.push(2);
  111913. indices.push(0);
  111914. indices.push(2);
  111915. indices.push(3);
  111916. this._indexBuffer = this._engine.createIndexBuffer(indices);
  111917. };
  111918. /**
  111919. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  111920. */
  111921. EffectLayer.prototype._genrateVertexBuffer = function () {
  111922. // VBO
  111923. var vertices = [];
  111924. vertices.push(1, 1);
  111925. vertices.push(-1, 1);
  111926. vertices.push(-1, -1);
  111927. vertices.push(1, -1);
  111928. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  111929. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  111930. };
  111931. /**
  111932. * Sets the main texture desired size which is the closest power of two
  111933. * of the engine canvas size.
  111934. */
  111935. EffectLayer.prototype._setMainTextureSize = function () {
  111936. if (this._effectLayerOptions.mainTextureFixedSize) {
  111937. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  111938. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  111939. }
  111940. else {
  111941. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  111942. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  111943. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  111944. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  111945. }
  111946. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  111947. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  111948. };
  111949. /**
  111950. * Creates the main texture for the effect layer.
  111951. */
  111952. EffectLayer.prototype._createMainTexture = function () {
  111953. var _this = this;
  111954. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  111955. width: this._mainTextureDesiredSize.width,
  111956. height: this._mainTextureDesiredSize.height
  111957. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  111958. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  111959. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  111960. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  111961. this._mainTexture.anisotropicFilteringLevel = 1;
  111962. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  111963. this._mainTexture.renderParticles = false;
  111964. this._mainTexture.renderList = null;
  111965. this._mainTexture.ignoreCameraViewport = true;
  111966. // Custom render function
  111967. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  111968. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  111969. var index;
  111970. var engine = _this._scene.getEngine();
  111971. if (depthOnlySubMeshes.length) {
  111972. engine.setColorWrite(false);
  111973. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  111974. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  111975. }
  111976. engine.setColorWrite(true);
  111977. }
  111978. for (index = 0; index < opaqueSubMeshes.length; index++) {
  111979. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  111980. }
  111981. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  111982. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  111983. }
  111984. for (index = 0; index < transparentSubMeshes.length; index++) {
  111985. _this._renderSubMesh(transparentSubMeshes.data[index]);
  111986. }
  111987. };
  111988. this._mainTexture.onClearObservable.add(function (engine) {
  111989. engine.clear(_this.neutralColor, true, true, true);
  111990. });
  111991. };
  111992. /**
  111993. * Checks for the readiness of the element composing the layer.
  111994. * @param subMesh the mesh to check for
  111995. * @param useInstances specify wether or not to use instances to render the mesh
  111996. * @param emissiveTexture the associated emissive texture used to generate the glow
  111997. * @return true if ready otherwise, false
  111998. */
  111999. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  112000. var material = subMesh.getMaterial();
  112001. if (!material) {
  112002. return false;
  112003. }
  112004. if (!material.isReadyForSubMesh(subMesh.getMesh(), subMesh, useInstances)) {
  112005. return false;
  112006. }
  112007. var defines = [];
  112008. var attribs = [BABYLON.VertexBuffer.PositionKind];
  112009. var mesh = subMesh.getMesh();
  112010. var uv1 = false;
  112011. var uv2 = false;
  112012. // Alpha test
  112013. if (material && material.needAlphaTesting()) {
  112014. var alphaTexture = material.getAlphaTestTexture();
  112015. if (alphaTexture) {
  112016. defines.push("#define ALPHATEST");
  112017. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  112018. alphaTexture.coordinatesIndex === 1) {
  112019. defines.push("#define DIFFUSEUV2");
  112020. uv2 = true;
  112021. }
  112022. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  112023. defines.push("#define DIFFUSEUV1");
  112024. uv1 = true;
  112025. }
  112026. }
  112027. }
  112028. // Emissive
  112029. if (emissiveTexture) {
  112030. defines.push("#define EMISSIVE");
  112031. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  112032. emissiveTexture.coordinatesIndex === 1) {
  112033. defines.push("#define EMISSIVEUV2");
  112034. uv2 = true;
  112035. }
  112036. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  112037. defines.push("#define EMISSIVEUV1");
  112038. uv1 = true;
  112039. }
  112040. }
  112041. if (uv1) {
  112042. attribs.push(BABYLON.VertexBuffer.UVKind);
  112043. defines.push("#define UV1");
  112044. }
  112045. if (uv2) {
  112046. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  112047. defines.push("#define UV2");
  112048. }
  112049. // Bones
  112050. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  112051. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  112052. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  112053. if (mesh.numBoneInfluencers > 4) {
  112054. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  112055. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  112056. }
  112057. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  112058. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  112059. }
  112060. else {
  112061. defines.push("#define NUM_BONE_INFLUENCERS 0");
  112062. }
  112063. // Morph targets
  112064. var manager = mesh.morphTargetManager;
  112065. var morphInfluencers = 0;
  112066. if (manager) {
  112067. if (manager.numInfluencers > 0) {
  112068. defines.push("#define MORPHTARGETS");
  112069. morphInfluencers = manager.numInfluencers;
  112070. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  112071. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  112072. }
  112073. }
  112074. // Instances
  112075. if (useInstances) {
  112076. defines.push("#define INSTANCES");
  112077. attribs.push("world0");
  112078. attribs.push("world1");
  112079. attribs.push("world2");
  112080. attribs.push("world3");
  112081. }
  112082. // Get correct effect
  112083. var join = defines.join("\n");
  112084. if (this._cachedDefines !== join) {
  112085. this._cachedDefines = join;
  112086. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  112087. }
  112088. return this._effectLayerMapGenerationEffect.isReady();
  112089. };
  112090. /**
  112091. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  112092. */
  112093. EffectLayer.prototype.render = function () {
  112094. var currentEffect = this._mergeEffect;
  112095. // Check
  112096. if (!currentEffect.isReady()) {
  112097. return;
  112098. }
  112099. for (var i = 0; i < this._postProcesses.length; i++) {
  112100. if (!this._postProcesses[i].isReady()) {
  112101. return;
  112102. }
  112103. }
  112104. var engine = this._scene.getEngine();
  112105. this.onBeforeComposeObservable.notifyObservers(this);
  112106. // Render
  112107. engine.enableEffect(currentEffect);
  112108. engine.setState(false);
  112109. // VBOs
  112110. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  112111. // Cache
  112112. var previousAlphaMode = engine.getAlphaMode();
  112113. // Go Blend.
  112114. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  112115. // Blends the map on the main canvas.
  112116. this._internalRender(currentEffect);
  112117. // Restore Alpha
  112118. engine.setAlphaMode(previousAlphaMode);
  112119. this.onAfterComposeObservable.notifyObservers(this);
  112120. // Handle size changes.
  112121. var size = this._mainTexture.getSize();
  112122. this._setMainTextureSize();
  112123. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  112124. // Recreate RTT and post processes on size change.
  112125. this.onSizeChangedObservable.notifyObservers(this);
  112126. this._disposeTextureAndPostProcesses();
  112127. this._createMainTexture();
  112128. this._createTextureAndPostProcesses();
  112129. }
  112130. };
  112131. /**
  112132. * Determine if a given mesh will be used in the current effect.
  112133. * @param mesh mesh to test
  112134. * @returns true if the mesh will be used
  112135. */
  112136. EffectLayer.prototype.hasMesh = function (mesh) {
  112137. if (this.renderingGroupId === -1 || mesh.renderingGroupId === this.renderingGroupId) {
  112138. return true;
  112139. }
  112140. return false;
  112141. };
  112142. /**
  112143. * Returns true if the layer contains information to display, otherwise false.
  112144. * @returns true if the glow layer should be rendered
  112145. */
  112146. EffectLayer.prototype.shouldRender = function () {
  112147. return this.isEnabled && this._shouldRender;
  112148. };
  112149. /**
  112150. * Returns true if the mesh should render, otherwise false.
  112151. * @param mesh The mesh to render
  112152. * @returns true if it should render otherwise false
  112153. */
  112154. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  112155. return true;
  112156. };
  112157. /**
  112158. * Returns true if the mesh should render, otherwise false.
  112159. * @param mesh The mesh to render
  112160. * @returns true if it should render otherwise false
  112161. */
  112162. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  112163. return true;
  112164. };
  112165. /**
  112166. * Renders the submesh passed in parameter to the generation map.
  112167. */
  112168. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  112169. var _this = this;
  112170. if (!this.shouldRender()) {
  112171. return;
  112172. }
  112173. var material = subMesh.getMaterial();
  112174. var mesh = subMesh.getRenderingMesh();
  112175. var scene = this._scene;
  112176. var engine = scene.getEngine();
  112177. if (!material) {
  112178. return;
  112179. }
  112180. // Do not block in blend mode.
  112181. if (material.needAlphaBlendingForMesh(mesh)) {
  112182. return;
  112183. }
  112184. // Culling
  112185. engine.setState(material.backFaceCulling);
  112186. // Managing instances
  112187. var batch = mesh._getInstancesRenderList(subMesh._id);
  112188. if (batch.mustReturn) {
  112189. return;
  112190. }
  112191. // Early Exit per mesh
  112192. if (!this._shouldRenderMesh(mesh)) {
  112193. return;
  112194. }
  112195. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  112196. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  112197. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  112198. engine.enableEffect(this._effectLayerMapGenerationEffect);
  112199. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  112200. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  112201. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  112202. // Alpha test
  112203. if (material && material.needAlphaTesting()) {
  112204. var alphaTexture = material.getAlphaTestTexture();
  112205. if (alphaTexture) {
  112206. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  112207. var textureMatrix = alphaTexture.getTextureMatrix();
  112208. if (textureMatrix) {
  112209. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  112210. }
  112211. }
  112212. }
  112213. // Glow emissive only
  112214. if (this._emissiveTextureAndColor.texture) {
  112215. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  112216. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  112217. }
  112218. // Bones
  112219. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  112220. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  112221. }
  112222. // Morph targets
  112223. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  112224. // Draw
  112225. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  112226. }
  112227. else {
  112228. // Need to reset refresh rate of the main map
  112229. this._mainTexture.resetRefreshCounter();
  112230. }
  112231. };
  112232. /**
  112233. * Rebuild the required buffers.
  112234. * @hidden Internal use only.
  112235. */
  112236. EffectLayer.prototype._rebuild = function () {
  112237. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  112238. if (vb) {
  112239. vb._rebuild();
  112240. }
  112241. this._generateIndexBuffer();
  112242. };
  112243. /**
  112244. * Dispose only the render target textures and post process.
  112245. */
  112246. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  112247. this._mainTexture.dispose();
  112248. for (var i = 0; i < this._postProcesses.length; i++) {
  112249. if (this._postProcesses[i]) {
  112250. this._postProcesses[i].dispose();
  112251. }
  112252. }
  112253. this._postProcesses = [];
  112254. for (var i = 0; i < this._textures.length; i++) {
  112255. if (this._textures[i]) {
  112256. this._textures[i].dispose();
  112257. }
  112258. }
  112259. this._textures = [];
  112260. };
  112261. /**
  112262. * Dispose the highlight layer and free resources.
  112263. */
  112264. EffectLayer.prototype.dispose = function () {
  112265. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  112266. if (vertexBuffer) {
  112267. vertexBuffer.dispose();
  112268. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  112269. }
  112270. if (this._indexBuffer) {
  112271. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  112272. this._indexBuffer = null;
  112273. }
  112274. // Clean textures and post processes
  112275. this._disposeTextureAndPostProcesses();
  112276. // Remove from scene
  112277. var index = this._scene.effectLayers.indexOf(this, 0);
  112278. if (index > -1) {
  112279. this._scene.effectLayers.splice(index, 1);
  112280. }
  112281. // Callback
  112282. this.onDisposeObservable.notifyObservers(this);
  112283. this.onDisposeObservable.clear();
  112284. this.onBeforeRenderMainTextureObservable.clear();
  112285. this.onBeforeComposeObservable.clear();
  112286. this.onAfterComposeObservable.clear();
  112287. this.onSizeChangedObservable.clear();
  112288. };
  112289. /**
  112290. * Gets the class name of the effect layer
  112291. * @returns the string with the class name of the effect layer
  112292. */
  112293. EffectLayer.prototype.getClassName = function () {
  112294. return "EffectLayer";
  112295. };
  112296. /**
  112297. * Creates an effect layer from parsed effect layer data
  112298. * @param parsedEffectLayer defines effect layer data
  112299. * @param scene defines the current scene
  112300. * @param rootUrl defines the root URL containing the effect layer information
  112301. * @returns a parsed effect Layer
  112302. */
  112303. EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
  112304. var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
  112305. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  112306. };
  112307. __decorate([
  112308. BABYLON.serialize()
  112309. ], EffectLayer.prototype, "name", void 0);
  112310. __decorate([
  112311. BABYLON.serializeAsColor4()
  112312. ], EffectLayer.prototype, "neutralColor", void 0);
  112313. __decorate([
  112314. BABYLON.serialize()
  112315. ], EffectLayer.prototype, "isEnabled", void 0);
  112316. __decorate([
  112317. BABYLON.serializeAsCameraReference()
  112318. ], EffectLayer.prototype, "camera", null);
  112319. __decorate([
  112320. BABYLON.serialize()
  112321. ], EffectLayer.prototype, "renderingGroupId", null);
  112322. return EffectLayer;
  112323. }());
  112324. BABYLON.EffectLayer = EffectLayer;
  112325. })(BABYLON || (BABYLON = {}));
  112326. //# sourceMappingURL=babylon.effectLayer.js.map
  112327. var BABYLON;
  112328. (function (BABYLON) {
  112329. BABYLON.AbstractScene.prototype.getHighlightLayerByName = function (name) {
  112330. for (var index = 0; index < this.effectLayers.length; index++) {
  112331. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === HighlightLayer.EffectName) {
  112332. return this.effectLayers[index];
  112333. }
  112334. }
  112335. return null;
  112336. };
  112337. /**
  112338. * Special Glow Blur post process only blurring the alpha channel
  112339. * It enforces keeping the most luminous color in the color channel.
  112340. */
  112341. var GlowBlurPostProcess = /** @class */ (function (_super) {
  112342. __extends(GlowBlurPostProcess, _super);
  112343. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  112344. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  112345. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  112346. _this.direction = direction;
  112347. _this.kernel = kernel;
  112348. _this.onApplyObservable.add(function (effect) {
  112349. effect.setFloat2("screenSize", _this.width, _this.height);
  112350. effect.setVector2("direction", _this.direction);
  112351. effect.setFloat("blurWidth", _this.kernel);
  112352. });
  112353. return _this;
  112354. }
  112355. return GlowBlurPostProcess;
  112356. }(BABYLON.PostProcess));
  112357. /**
  112358. * The highlight layer Helps adding a glow effect around a mesh.
  112359. *
  112360. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  112361. * glowy meshes to your scene.
  112362. *
  112363. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  112364. */
  112365. var HighlightLayer = /** @class */ (function (_super) {
  112366. __extends(HighlightLayer, _super);
  112367. /**
  112368. * Instantiates a new highlight Layer and references it to the scene..
  112369. * @param name The name of the layer
  112370. * @param scene The scene to use the layer in
  112371. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  112372. */
  112373. function HighlightLayer(name, scene, options) {
  112374. var _this = _super.call(this, name, scene) || this;
  112375. _this.name = name;
  112376. /**
  112377. * Specifies whether or not the inner glow is ACTIVE in the layer.
  112378. */
  112379. _this.innerGlow = true;
  112380. /**
  112381. * Specifies whether or not the outer glow is ACTIVE in the layer.
  112382. */
  112383. _this.outerGlow = true;
  112384. /**
  112385. * An event triggered when the highlight layer is being blurred.
  112386. */
  112387. _this.onBeforeBlurObservable = new BABYLON.Observable();
  112388. /**
  112389. * An event triggered when the highlight layer has been blurred.
  112390. */
  112391. _this.onAfterBlurObservable = new BABYLON.Observable();
  112392. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  112393. _this._meshes = {};
  112394. _this._excludedMeshes = {};
  112395. _this.neutralColor = HighlightLayer.NeutralColor;
  112396. // Warn on stencil
  112397. if (!_this._engine.isStencilEnable) {
  112398. 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 }");
  112399. }
  112400. // Adapt options
  112401. _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);
  112402. // Initialize the layer
  112403. _this._init({
  112404. alphaBlendingMode: _this._options.alphaBlendingMode,
  112405. camera: _this._options.camera,
  112406. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  112407. mainTextureRatio: _this._options.mainTextureRatio,
  112408. renderingGroupId: _this._options.renderingGroupId
  112409. });
  112410. // Do not render as long as no meshes have been added
  112411. _this._shouldRender = false;
  112412. return _this;
  112413. }
  112414. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  112415. /**
  112416. * Gets the horizontal size of the blur.
  112417. */
  112418. get: function () {
  112419. return this._horizontalBlurPostprocess.kernel;
  112420. },
  112421. /**
  112422. * Specifies the horizontal size of the blur.
  112423. */
  112424. set: function (value) {
  112425. this._horizontalBlurPostprocess.kernel = value;
  112426. },
  112427. enumerable: true,
  112428. configurable: true
  112429. });
  112430. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  112431. /**
  112432. * Gets the vertical size of the blur.
  112433. */
  112434. get: function () {
  112435. return this._verticalBlurPostprocess.kernel;
  112436. },
  112437. /**
  112438. * Specifies the vertical size of the blur.
  112439. */
  112440. set: function (value) {
  112441. this._verticalBlurPostprocess.kernel = value;
  112442. },
  112443. enumerable: true,
  112444. configurable: true
  112445. });
  112446. /**
  112447. * Get the effect name of the layer.
  112448. * @return The effect name
  112449. */
  112450. HighlightLayer.prototype.getEffectName = function () {
  112451. return HighlightLayer.EffectName;
  112452. };
  112453. /**
  112454. * Create the merge effect. This is the shader use to blit the information back
  112455. * to the main canvas at the end of the scene rendering.
  112456. */
  112457. HighlightLayer.prototype._createMergeEffect = function () {
  112458. // Effect
  112459. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  112460. };
  112461. /**
  112462. * Creates the render target textures and post processes used in the highlight layer.
  112463. */
  112464. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  112465. var _this = this;
  112466. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  112467. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  112468. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  112469. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  112470. var textureType = 0;
  112471. if (this._engine.getCaps().textureHalfFloatRender) {
  112472. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  112473. }
  112474. else {
  112475. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  112476. }
  112477. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  112478. width: blurTextureWidth,
  112479. height: blurTextureHeight
  112480. }, this._scene, false, true, textureType);
  112481. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  112482. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  112483. this._blurTexture.anisotropicFilteringLevel = 16;
  112484. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  112485. this._blurTexture.renderParticles = false;
  112486. this._blurTexture.ignoreCameraViewport = true;
  112487. this._textures = [this._blurTexture];
  112488. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  112489. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  112490. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  112491. effect.setTexture("textureSampler", _this._mainTexture);
  112492. });
  112493. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  112494. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  112495. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  112496. });
  112497. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  112498. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  112499. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  112500. });
  112501. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  112502. }
  112503. else {
  112504. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  112505. width: blurTextureWidth,
  112506. height: blurTextureHeight
  112507. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  112508. this._horizontalBlurPostprocess.width = blurTextureWidth;
  112509. this._horizontalBlurPostprocess.height = blurTextureHeight;
  112510. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  112511. effect.setTexture("textureSampler", _this._mainTexture);
  112512. });
  112513. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  112514. width: blurTextureWidth,
  112515. height: blurTextureHeight
  112516. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  112517. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  112518. }
  112519. this._mainTexture.onAfterUnbindObservable.add(function () {
  112520. _this.onBeforeBlurObservable.notifyObservers(_this);
  112521. var internalTexture = _this._blurTexture.getInternalTexture();
  112522. if (internalTexture) {
  112523. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  112524. }
  112525. _this.onAfterBlurObservable.notifyObservers(_this);
  112526. });
  112527. // Prevent autoClear.
  112528. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  112529. };
  112530. /**
  112531. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  112532. */
  112533. HighlightLayer.prototype.needStencil = function () {
  112534. return true;
  112535. };
  112536. /**
  112537. * Checks for the readiness of the element composing the layer.
  112538. * @param subMesh the mesh to check for
  112539. * @param useInstances specify wether or not to use instances to render the mesh
  112540. * @param emissiveTexture the associated emissive texture used to generate the glow
  112541. * @return true if ready otherwise, false
  112542. */
  112543. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  112544. var material = subMesh.getMaterial();
  112545. var mesh = subMesh.getRenderingMesh();
  112546. if (!material || !mesh || !this._meshes) {
  112547. return false;
  112548. }
  112549. var emissiveTexture = null;
  112550. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  112551. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  112552. emissiveTexture = material.emissiveTexture;
  112553. }
  112554. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  112555. };
  112556. /**
  112557. * Implementation specific of rendering the generating effect on the main canvas.
  112558. * @param effect The effect used to render through
  112559. */
  112560. HighlightLayer.prototype._internalRender = function (effect) {
  112561. // Texture
  112562. effect.setTexture("textureSampler", this._blurTexture);
  112563. // Cache
  112564. var engine = this._engine;
  112565. var previousStencilBuffer = engine.getStencilBuffer();
  112566. var previousStencilFunction = engine.getStencilFunction();
  112567. var previousStencilMask = engine.getStencilMask();
  112568. var previousStencilOperationPass = engine.getStencilOperationPass();
  112569. var previousStencilOperationFail = engine.getStencilOperationFail();
  112570. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  112571. var previousStencilReference = engine.getStencilFunctionReference();
  112572. // Stencil operations
  112573. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  112574. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  112575. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  112576. // Draw order
  112577. engine.setStencilMask(0x00);
  112578. engine.setStencilBuffer(true);
  112579. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  112580. // 2 passes inner outer
  112581. if (this.outerGlow) {
  112582. effect.setFloat("offset", 0);
  112583. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  112584. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  112585. }
  112586. if (this.innerGlow) {
  112587. effect.setFloat("offset", 1);
  112588. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  112589. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  112590. }
  112591. // Restore Cache
  112592. engine.setStencilFunction(previousStencilFunction);
  112593. engine.setStencilMask(previousStencilMask);
  112594. engine.setStencilBuffer(previousStencilBuffer);
  112595. engine.setStencilOperationPass(previousStencilOperationPass);
  112596. engine.setStencilOperationFail(previousStencilOperationFail);
  112597. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  112598. engine.setStencilFunctionReference(previousStencilReference);
  112599. };
  112600. /**
  112601. * Returns true if the layer contains information to display, otherwise false.
  112602. */
  112603. HighlightLayer.prototype.shouldRender = function () {
  112604. if (_super.prototype.shouldRender.call(this)) {
  112605. return this._meshes ? true : false;
  112606. }
  112607. return false;
  112608. };
  112609. /**
  112610. * Returns true if the mesh should render, otherwise false.
  112611. * @param mesh The mesh to render
  112612. * @returns true if it should render otherwise false
  112613. */
  112614. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  112615. // Excluded Mesh
  112616. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  112617. return false;
  112618. }
  112619. if (!_super.prototype.hasMesh.call(this, mesh)) {
  112620. return false;
  112621. }
  112622. return true;
  112623. };
  112624. /**
  112625. * Sets the required values for both the emissive texture and and the main color.
  112626. */
  112627. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  112628. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  112629. if (highlightLayerMesh) {
  112630. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  112631. }
  112632. else {
  112633. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  112634. }
  112635. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  112636. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  112637. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  112638. }
  112639. else {
  112640. this._emissiveTextureAndColor.texture = null;
  112641. }
  112642. };
  112643. /**
  112644. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  112645. * @param mesh The mesh to exclude from the highlight layer
  112646. */
  112647. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  112648. if (!this._excludedMeshes) {
  112649. return;
  112650. }
  112651. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  112652. if (!meshExcluded) {
  112653. this._excludedMeshes[mesh.uniqueId] = {
  112654. mesh: mesh,
  112655. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  112656. mesh.getEngine().setStencilBuffer(false);
  112657. }),
  112658. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  112659. mesh.getEngine().setStencilBuffer(true);
  112660. }),
  112661. };
  112662. }
  112663. };
  112664. /**
  112665. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  112666. * @param mesh The mesh to highlight
  112667. */
  112668. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  112669. if (!this._excludedMeshes) {
  112670. return;
  112671. }
  112672. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  112673. if (meshExcluded) {
  112674. if (meshExcluded.beforeRender) {
  112675. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  112676. }
  112677. if (meshExcluded.afterRender) {
  112678. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  112679. }
  112680. }
  112681. this._excludedMeshes[mesh.uniqueId] = null;
  112682. };
  112683. /**
  112684. * Determine if a given mesh will be highlighted by the current HighlightLayer
  112685. * @param mesh mesh to test
  112686. * @returns true if the mesh will be highlighted by the current HighlightLayer
  112687. */
  112688. HighlightLayer.prototype.hasMesh = function (mesh) {
  112689. if (!this._meshes) {
  112690. return false;
  112691. }
  112692. if (!_super.prototype.hasMesh.call(this, mesh)) {
  112693. return false;
  112694. }
  112695. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  112696. };
  112697. /**
  112698. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  112699. * @param mesh The mesh to highlight
  112700. * @param color The color of the highlight
  112701. * @param glowEmissiveOnly Extract the glow from the emissive texture
  112702. */
  112703. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  112704. var _this = this;
  112705. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  112706. if (!this._meshes) {
  112707. return;
  112708. }
  112709. var meshHighlight = this._meshes[mesh.uniqueId];
  112710. if (meshHighlight) {
  112711. meshHighlight.color = color;
  112712. }
  112713. else {
  112714. this._meshes[mesh.uniqueId] = {
  112715. mesh: mesh,
  112716. color: color,
  112717. // Lambda required for capture due to Observable this context
  112718. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  112719. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  112720. _this._defaultStencilReference(mesh);
  112721. }
  112722. else {
  112723. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  112724. }
  112725. }),
  112726. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  112727. glowEmissiveOnly: glowEmissiveOnly
  112728. };
  112729. mesh.onDisposeObservable.add(function () {
  112730. _this._disposeMesh(mesh);
  112731. });
  112732. }
  112733. this._shouldRender = true;
  112734. };
  112735. /**
  112736. * Remove a mesh from the highlight layer in order to make it stop glowing.
  112737. * @param mesh The mesh to highlight
  112738. */
  112739. HighlightLayer.prototype.removeMesh = function (mesh) {
  112740. if (!this._meshes) {
  112741. return;
  112742. }
  112743. var meshHighlight = this._meshes[mesh.uniqueId];
  112744. if (meshHighlight) {
  112745. if (meshHighlight.observerHighlight) {
  112746. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  112747. }
  112748. if (meshHighlight.observerDefault) {
  112749. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  112750. }
  112751. delete this._meshes[mesh.uniqueId];
  112752. }
  112753. this._shouldRender = false;
  112754. for (var meshHighlightToCheck in this._meshes) {
  112755. if (this._meshes[meshHighlightToCheck]) {
  112756. this._shouldRender = true;
  112757. break;
  112758. }
  112759. }
  112760. };
  112761. /**
  112762. * Force the stencil to the normal expected value for none glowing parts
  112763. */
  112764. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  112765. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  112766. };
  112767. /**
  112768. * Free any resources and references associated to a mesh.
  112769. * Internal use
  112770. * @param mesh The mesh to free.
  112771. * @hidden
  112772. */
  112773. HighlightLayer.prototype._disposeMesh = function (mesh) {
  112774. this.removeMesh(mesh);
  112775. this.removeExcludedMesh(mesh);
  112776. };
  112777. /**
  112778. * Dispose the highlight layer and free resources.
  112779. */
  112780. HighlightLayer.prototype.dispose = function () {
  112781. if (this._meshes) {
  112782. // Clean mesh references
  112783. for (var id in this._meshes) {
  112784. var meshHighlight = this._meshes[id];
  112785. if (meshHighlight && meshHighlight.mesh) {
  112786. if (meshHighlight.observerHighlight) {
  112787. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  112788. }
  112789. if (meshHighlight.observerDefault) {
  112790. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  112791. }
  112792. }
  112793. }
  112794. this._meshes = null;
  112795. }
  112796. if (this._excludedMeshes) {
  112797. for (var id in this._excludedMeshes) {
  112798. var meshHighlight = this._excludedMeshes[id];
  112799. if (meshHighlight) {
  112800. if (meshHighlight.beforeRender) {
  112801. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  112802. }
  112803. if (meshHighlight.afterRender) {
  112804. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  112805. }
  112806. }
  112807. }
  112808. this._excludedMeshes = null;
  112809. }
  112810. _super.prototype.dispose.call(this);
  112811. };
  112812. /**
  112813. * Gets the class name of the effect layer
  112814. * @returns the string with the class name of the effect layer
  112815. */
  112816. HighlightLayer.prototype.getClassName = function () {
  112817. return "HighlightLayer";
  112818. };
  112819. /**
  112820. * Serializes this Highlight layer
  112821. * @returns a serialized Highlight layer object
  112822. */
  112823. HighlightLayer.prototype.serialize = function () {
  112824. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  112825. serializationObject.customType = "BABYLON.HighlightLayer";
  112826. // Highlighted meshes
  112827. serializationObject.meshes = [];
  112828. if (this._meshes) {
  112829. for (var m in this._meshes) {
  112830. var mesh = this._meshes[m];
  112831. if (mesh) {
  112832. serializationObject.meshes.push({
  112833. glowEmissiveOnly: mesh.glowEmissiveOnly,
  112834. color: mesh.color.asArray(),
  112835. meshId: mesh.mesh.id
  112836. });
  112837. }
  112838. }
  112839. }
  112840. // Excluded meshes
  112841. serializationObject.excludedMeshes = [];
  112842. if (this._excludedMeshes) {
  112843. for (var e in this._excludedMeshes) {
  112844. var excludedMesh = this._excludedMeshes[e];
  112845. if (excludedMesh) {
  112846. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  112847. }
  112848. }
  112849. }
  112850. return serializationObject;
  112851. };
  112852. /**
  112853. * Creates a Highlight layer from parsed Highlight layer data
  112854. * @param parsedHightlightLayer defines the Highlight layer data
  112855. * @param scene defines the current scene
  112856. * @param rootUrl defines the root URL containing the Highlight layer information
  112857. * @returns a parsed Highlight layer
  112858. */
  112859. HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
  112860. var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
  112861. var index;
  112862. // Excluded meshes
  112863. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  112864. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  112865. if (mesh) {
  112866. hl.addExcludedMesh(mesh);
  112867. }
  112868. }
  112869. // Included meshes
  112870. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  112871. var highlightedMesh = parsedHightlightLayer.meshes[index];
  112872. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  112873. if (mesh) {
  112874. hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  112875. }
  112876. }
  112877. return hl;
  112878. };
  112879. /**
  112880. * Effect Name of the highlight layer.
  112881. */
  112882. HighlightLayer.EffectName = "HighlightLayer";
  112883. /**
  112884. * The neutral color used during the preparation of the glow effect.
  112885. * This is black by default as the blend operation is a blend operation.
  112886. */
  112887. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  112888. /**
  112889. * Stencil value used for glowing meshes.
  112890. */
  112891. HighlightLayer.GlowingMeshStencilReference = 0x02;
  112892. /**
  112893. * Stencil value used for the other meshes in the scene.
  112894. */
  112895. HighlightLayer.NormalMeshStencilReference = 0x01;
  112896. __decorate([
  112897. BABYLON.serialize()
  112898. ], HighlightLayer.prototype, "innerGlow", void 0);
  112899. __decorate([
  112900. BABYLON.serialize()
  112901. ], HighlightLayer.prototype, "outerGlow", void 0);
  112902. __decorate([
  112903. BABYLON.serialize()
  112904. ], HighlightLayer.prototype, "blurHorizontalSize", null);
  112905. __decorate([
  112906. BABYLON.serialize()
  112907. ], HighlightLayer.prototype, "blurVerticalSize", null);
  112908. __decorate([
  112909. BABYLON.serialize("options")
  112910. ], HighlightLayer.prototype, "_options", void 0);
  112911. return HighlightLayer;
  112912. }(BABYLON.EffectLayer));
  112913. BABYLON.HighlightLayer = HighlightLayer;
  112914. })(BABYLON || (BABYLON = {}));
  112915. //# sourceMappingURL=babylon.highlightLayer.js.map
  112916. var BABYLON;
  112917. (function (BABYLON) {
  112918. BABYLON.AbstractScene.prototype.getGlowLayerByName = function (name) {
  112919. for (var index = 0; index < this.effectLayers.length; index++) {
  112920. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === GlowLayer.EffectName) {
  112921. return this.effectLayers[index];
  112922. }
  112923. }
  112924. return null;
  112925. };
  112926. /**
  112927. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  112928. *
  112929. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  112930. * glowy meshes to your scene.
  112931. *
  112932. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  112933. */
  112934. var GlowLayer = /** @class */ (function (_super) {
  112935. __extends(GlowLayer, _super);
  112936. /**
  112937. * Instantiates a new glow Layer and references it to the scene.
  112938. * @param name The name of the layer
  112939. * @param scene The scene to use the layer in
  112940. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  112941. */
  112942. function GlowLayer(name, scene, options) {
  112943. var _this = _super.call(this, name, scene) || this;
  112944. _this._intensity = 1.0;
  112945. _this._includedOnlyMeshes = [];
  112946. _this._excludedMeshes = [];
  112947. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  112948. // Adapt options
  112949. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1, renderingGroupId: -1 }, options);
  112950. // Initialize the layer
  112951. _this._init({
  112952. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  112953. camera: _this._options.camera,
  112954. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  112955. mainTextureRatio: _this._options.mainTextureRatio,
  112956. renderingGroupId: _this._options.renderingGroupId
  112957. });
  112958. return _this;
  112959. }
  112960. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  112961. /**
  112962. * Gets the kernel size of the blur.
  112963. */
  112964. get: function () {
  112965. return this._horizontalBlurPostprocess1.kernel;
  112966. },
  112967. /**
  112968. * Sets the kernel size of the blur.
  112969. */
  112970. set: function (value) {
  112971. this._horizontalBlurPostprocess1.kernel = value;
  112972. this._verticalBlurPostprocess1.kernel = value;
  112973. this._horizontalBlurPostprocess2.kernel = value;
  112974. this._verticalBlurPostprocess2.kernel = value;
  112975. },
  112976. enumerable: true,
  112977. configurable: true
  112978. });
  112979. Object.defineProperty(GlowLayer.prototype, "intensity", {
  112980. /**
  112981. * Gets the glow intensity.
  112982. */
  112983. get: function () {
  112984. return this._intensity;
  112985. },
  112986. /**
  112987. * Sets the glow intensity.
  112988. */
  112989. set: function (value) {
  112990. this._intensity = value;
  112991. },
  112992. enumerable: true,
  112993. configurable: true
  112994. });
  112995. /**
  112996. * Get the effect name of the layer.
  112997. * @return The effect name
  112998. */
  112999. GlowLayer.prototype.getEffectName = function () {
  113000. return GlowLayer.EffectName;
  113001. };
  113002. /**
  113003. * Create the merge effect. This is the shader use to blit the information back
  113004. * to the main canvas at the end of the scene rendering.
  113005. */
  113006. GlowLayer.prototype._createMergeEffect = function () {
  113007. // Effect
  113008. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  113009. };
  113010. /**
  113011. * Creates the render target textures and post processes used in the glow layer.
  113012. */
  113013. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  113014. var _this = this;
  113015. var blurTextureWidth = this._mainTextureDesiredSize.width;
  113016. var blurTextureHeight = this._mainTextureDesiredSize.height;
  113017. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  113018. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  113019. var textureType = 0;
  113020. if (this._engine.getCaps().textureHalfFloatRender) {
  113021. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  113022. }
  113023. else {
  113024. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  113025. }
  113026. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  113027. width: blurTextureWidth,
  113028. height: blurTextureHeight
  113029. }, this._scene, false, true, textureType);
  113030. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  113031. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  113032. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  113033. this._blurTexture1.renderParticles = false;
  113034. this._blurTexture1.ignoreCameraViewport = true;
  113035. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  113036. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  113037. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  113038. width: blurTextureWidth2,
  113039. height: blurTextureHeight2
  113040. }, this._scene, false, true, textureType);
  113041. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  113042. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  113043. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  113044. this._blurTexture2.renderParticles = false;
  113045. this._blurTexture2.ignoreCameraViewport = true;
  113046. this._textures = [this._blurTexture1, this._blurTexture2];
  113047. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  113048. width: blurTextureWidth,
  113049. height: blurTextureHeight
  113050. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  113051. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  113052. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  113053. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  113054. effect.setTexture("textureSampler", _this._mainTexture);
  113055. });
  113056. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  113057. width: blurTextureWidth,
  113058. height: blurTextureHeight
  113059. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  113060. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  113061. width: blurTextureWidth2,
  113062. height: blurTextureHeight2
  113063. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  113064. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  113065. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  113066. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  113067. effect.setTexture("textureSampler", _this._blurTexture1);
  113068. });
  113069. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  113070. width: blurTextureWidth2,
  113071. height: blurTextureHeight2
  113072. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  113073. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  113074. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  113075. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  113076. this._mainTexture.samples = this._options.mainTextureSamples;
  113077. this._mainTexture.onAfterUnbindObservable.add(function () {
  113078. var internalTexture = _this._blurTexture1.getInternalTexture();
  113079. if (internalTexture) {
  113080. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  113081. internalTexture = _this._blurTexture2.getInternalTexture();
  113082. if (internalTexture) {
  113083. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  113084. }
  113085. }
  113086. });
  113087. // Prevent autoClear.
  113088. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  113089. };
  113090. /**
  113091. * Checks for the readiness of the element composing the layer.
  113092. * @param subMesh the mesh to check for
  113093. * @param useInstances specify wether or not to use instances to render the mesh
  113094. * @param emissiveTexture the associated emissive texture used to generate the glow
  113095. * @return true if ready otherwise, false
  113096. */
  113097. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  113098. var material = subMesh.getMaterial();
  113099. var mesh = subMesh.getRenderingMesh();
  113100. if (!material || !mesh) {
  113101. return false;
  113102. }
  113103. var emissiveTexture = material.emissiveTexture;
  113104. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  113105. };
  113106. /**
  113107. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  113108. */
  113109. GlowLayer.prototype.needStencil = function () {
  113110. return false;
  113111. };
  113112. /**
  113113. * Implementation specific of rendering the generating effect on the main canvas.
  113114. * @param effect The effect used to render through
  113115. */
  113116. GlowLayer.prototype._internalRender = function (effect) {
  113117. // Texture
  113118. effect.setTexture("textureSampler", this._blurTexture1);
  113119. effect.setTexture("textureSampler2", this._blurTexture2);
  113120. effect.setFloat("offset", this._intensity);
  113121. // Cache
  113122. var engine = this._engine;
  113123. var previousStencilBuffer = engine.getStencilBuffer();
  113124. // Draw order
  113125. engine.setStencilBuffer(false);
  113126. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  113127. // Draw order
  113128. engine.setStencilBuffer(previousStencilBuffer);
  113129. };
  113130. /**
  113131. * Sets the required values for both the emissive texture and and the main color.
  113132. */
  113133. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  113134. var textureLevel = 1.0;
  113135. if (this.customEmissiveTextureSelector) {
  113136. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  113137. }
  113138. else {
  113139. if (material) {
  113140. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  113141. if (this._emissiveTextureAndColor.texture) {
  113142. textureLevel = this._emissiveTextureAndColor.texture.level;
  113143. }
  113144. }
  113145. else {
  113146. this._emissiveTextureAndColor.texture = null;
  113147. }
  113148. }
  113149. if (this.customEmissiveColorSelector) {
  113150. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  113151. }
  113152. else {
  113153. if (material.emissiveColor) {
  113154. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  113155. }
  113156. else {
  113157. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  113158. }
  113159. }
  113160. };
  113161. /**
  113162. * Returns true if the mesh should render, otherwise false.
  113163. * @param mesh The mesh to render
  113164. * @returns true if it should render otherwise false
  113165. */
  113166. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  113167. return this.hasMesh(mesh);
  113168. };
  113169. /**
  113170. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  113171. * @param mesh The mesh to exclude from the glow layer
  113172. */
  113173. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  113174. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  113175. this._excludedMeshes.push(mesh.uniqueId);
  113176. }
  113177. };
  113178. /**
  113179. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  113180. * @param mesh The mesh to remove
  113181. */
  113182. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  113183. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  113184. if (index !== -1) {
  113185. this._excludedMeshes.splice(index, 1);
  113186. }
  113187. };
  113188. /**
  113189. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  113190. * @param mesh The mesh to include in the glow layer
  113191. */
  113192. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  113193. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  113194. this._includedOnlyMeshes.push(mesh.uniqueId);
  113195. }
  113196. };
  113197. /**
  113198. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  113199. * @param mesh The mesh to remove
  113200. */
  113201. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  113202. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  113203. if (index !== -1) {
  113204. this._includedOnlyMeshes.splice(index, 1);
  113205. }
  113206. };
  113207. /**
  113208. * Determine if a given mesh will be used in the glow layer
  113209. * @param mesh The mesh to test
  113210. * @returns true if the mesh will be highlighted by the current glow layer
  113211. */
  113212. GlowLayer.prototype.hasMesh = function (mesh) {
  113213. if (!_super.prototype.hasMesh.call(this, mesh)) {
  113214. return false;
  113215. }
  113216. // Included Mesh
  113217. if (this._includedOnlyMeshes.length) {
  113218. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  113219. }
  113220. // Excluded Mesh
  113221. if (this._excludedMeshes.length) {
  113222. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  113223. }
  113224. return true;
  113225. };
  113226. /**
  113227. * Free any resources and references associated to a mesh.
  113228. * Internal use
  113229. * @param mesh The mesh to free.
  113230. * @hidden
  113231. */
  113232. GlowLayer.prototype._disposeMesh = function (mesh) {
  113233. this.removeIncludedOnlyMesh(mesh);
  113234. this.removeExcludedMesh(mesh);
  113235. };
  113236. /**
  113237. * Gets the class name of the effect layer
  113238. * @returns the string with the class name of the effect layer
  113239. */
  113240. GlowLayer.prototype.getClassName = function () {
  113241. return "GlowLayer";
  113242. };
  113243. /**
  113244. * Serializes this glow layer
  113245. * @returns a serialized glow layer object
  113246. */
  113247. GlowLayer.prototype.serialize = function () {
  113248. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  113249. serializationObject.customType = "BABYLON.GlowLayer";
  113250. var index;
  113251. // Included meshes
  113252. serializationObject.includedMeshes = [];
  113253. if (this._includedOnlyMeshes.length) {
  113254. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  113255. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  113256. if (mesh) {
  113257. serializationObject.includedMeshes.push(mesh.id);
  113258. }
  113259. }
  113260. }
  113261. // Excluded meshes
  113262. serializationObject.excludedMeshes = [];
  113263. if (this._excludedMeshes.length) {
  113264. for (index = 0; index < this._excludedMeshes.length; index++) {
  113265. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  113266. if (mesh) {
  113267. serializationObject.excludedMeshes.push(mesh.id);
  113268. }
  113269. }
  113270. }
  113271. return serializationObject;
  113272. };
  113273. /**
  113274. * Creates a Glow Layer from parsed glow layer data
  113275. * @param parsedGlowLayer defines glow layer data
  113276. * @param scene defines the current scene
  113277. * @param rootUrl defines the root URL containing the glow layer information
  113278. * @returns a parsed Glow Layer
  113279. */
  113280. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  113281. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  113282. var index;
  113283. // Excluded meshes
  113284. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  113285. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  113286. if (mesh) {
  113287. gl.addExcludedMesh(mesh);
  113288. }
  113289. }
  113290. // Included meshes
  113291. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  113292. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  113293. if (mesh) {
  113294. gl.addIncludedOnlyMesh(mesh);
  113295. }
  113296. }
  113297. return gl;
  113298. };
  113299. /**
  113300. * Effect Name of the layer.
  113301. */
  113302. GlowLayer.EffectName = "GlowLayer";
  113303. /**
  113304. * The default blur kernel size used for the glow.
  113305. */
  113306. GlowLayer.DefaultBlurKernelSize = 32;
  113307. /**
  113308. * The default texture size ratio used for the glow.
  113309. */
  113310. GlowLayer.DefaultTextureRatio = 0.5;
  113311. __decorate([
  113312. BABYLON.serialize()
  113313. ], GlowLayer.prototype, "blurKernelSize", null);
  113314. __decorate([
  113315. BABYLON.serialize()
  113316. ], GlowLayer.prototype, "intensity", null);
  113317. __decorate([
  113318. BABYLON.serialize("options")
  113319. ], GlowLayer.prototype, "_options", void 0);
  113320. return GlowLayer;
  113321. }(BABYLON.EffectLayer));
  113322. BABYLON.GlowLayer = GlowLayer;
  113323. })(BABYLON || (BABYLON = {}));
  113324. //# sourceMappingURL=babylon.glowLayer.js.map
  113325. var BABYLON;
  113326. (function (BABYLON) {
  113327. /**
  113328. * Defines the list of states available for a task inside a AssetsManager
  113329. */
  113330. var AssetTaskState;
  113331. (function (AssetTaskState) {
  113332. /**
  113333. * Initialization
  113334. */
  113335. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  113336. /**
  113337. * Running
  113338. */
  113339. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  113340. /**
  113341. * Done
  113342. */
  113343. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  113344. /**
  113345. * Error
  113346. */
  113347. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  113348. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  113349. /**
  113350. * Define an abstract asset task used with a AssetsManager class to load assets into a scene
  113351. */
  113352. var AbstractAssetTask = /** @class */ (function () {
  113353. /**
  113354. * Creates a new AssetsManager
  113355. * @param name defines the name of the task
  113356. */
  113357. function AbstractAssetTask(
  113358. /**
  113359. * Task name
  113360. */ name) {
  113361. this.name = name;
  113362. this._isCompleted = false;
  113363. this._taskState = AssetTaskState.INIT;
  113364. }
  113365. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  113366. /**
  113367. * Get if the task is completed
  113368. */
  113369. get: function () {
  113370. return this._isCompleted;
  113371. },
  113372. enumerable: true,
  113373. configurable: true
  113374. });
  113375. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  113376. /**
  113377. * Gets the current state of the task
  113378. */
  113379. get: function () {
  113380. return this._taskState;
  113381. },
  113382. enumerable: true,
  113383. configurable: true
  113384. });
  113385. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  113386. /**
  113387. * Gets the current error object (if task is in error)
  113388. */
  113389. get: function () {
  113390. return this._errorObject;
  113391. },
  113392. enumerable: true,
  113393. configurable: true
  113394. });
  113395. /**
  113396. * Internal only
  113397. * @hidden
  113398. */
  113399. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  113400. if (this._errorObject) {
  113401. return;
  113402. }
  113403. this._errorObject = {
  113404. message: message,
  113405. exception: exception
  113406. };
  113407. };
  113408. /**
  113409. * Execute the current task
  113410. * @param scene defines the scene where you want your assets to be loaded
  113411. * @param onSuccess is a callback called when the task is successfully executed
  113412. * @param onError is a callback called if an error occurs
  113413. */
  113414. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  113415. var _this = this;
  113416. this._taskState = AssetTaskState.RUNNING;
  113417. this.runTask(scene, function () {
  113418. _this.onDoneCallback(onSuccess, onError);
  113419. }, function (msg, exception) {
  113420. _this.onErrorCallback(onError, msg, exception);
  113421. });
  113422. };
  113423. /**
  113424. * Execute the current task
  113425. * @param scene defines the scene where you want your assets to be loaded
  113426. * @param onSuccess is a callback called when the task is successfully executed
  113427. * @param onError is a callback called if an error occurs
  113428. */
  113429. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  113430. throw new Error("runTask is not implemented");
  113431. };
  113432. /**
  113433. * Reset will set the task state back to INIT, so the next load call of the assets manager will execute this task again.
  113434. * This can be used with failed tasks that have the reason for failure fixed.
  113435. */
  113436. AbstractAssetTask.prototype.reset = function () {
  113437. this._taskState = AssetTaskState.INIT;
  113438. };
  113439. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  113440. this._taskState = AssetTaskState.ERROR;
  113441. this._errorObject = {
  113442. message: message,
  113443. exception: exception
  113444. };
  113445. if (this.onError) {
  113446. this.onError(this, message, exception);
  113447. }
  113448. onError();
  113449. };
  113450. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  113451. try {
  113452. this._taskState = AssetTaskState.DONE;
  113453. this._isCompleted = true;
  113454. if (this.onSuccess) {
  113455. this.onSuccess(this);
  113456. }
  113457. onSuccess();
  113458. }
  113459. catch (e) {
  113460. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  113461. }
  113462. };
  113463. return AbstractAssetTask;
  113464. }());
  113465. BABYLON.AbstractAssetTask = AbstractAssetTask;
  113466. /**
  113467. * Class used to share progress information about assets loading
  113468. */
  113469. var AssetsProgressEvent = /** @class */ (function () {
  113470. /**
  113471. * Creates a AssetsProgressEvent
  113472. * @param remainingCount defines the number of remaining tasks to process
  113473. * @param totalCount defines the total number of tasks
  113474. * @param task defines the task that was just processed
  113475. */
  113476. function AssetsProgressEvent(remainingCount, totalCount, task) {
  113477. this.remainingCount = remainingCount;
  113478. this.totalCount = totalCount;
  113479. this.task = task;
  113480. }
  113481. return AssetsProgressEvent;
  113482. }());
  113483. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  113484. /**
  113485. * Define a task used by AssetsManager to load meshes
  113486. */
  113487. var MeshAssetTask = /** @class */ (function (_super) {
  113488. __extends(MeshAssetTask, _super);
  113489. /**
  113490. * Creates a new MeshAssetTask
  113491. * @param name defines the name of the task
  113492. * @param meshesNames defines the list of mesh's names you want to load
  113493. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  113494. * @param sceneFilename defines the filename of the scene to load from
  113495. */
  113496. function MeshAssetTask(
  113497. /**
  113498. * Defines the name of the task
  113499. */
  113500. name,
  113501. /**
  113502. * Defines the list of mesh's names you want to load
  113503. */
  113504. meshesNames,
  113505. /**
  113506. * Defines the root url to use as a base to load your meshes and associated resources
  113507. */
  113508. rootUrl,
  113509. /**
  113510. * Defines the filename of the scene to load from
  113511. */
  113512. sceneFilename) {
  113513. var _this = _super.call(this, name) || this;
  113514. _this.name = name;
  113515. _this.meshesNames = meshesNames;
  113516. _this.rootUrl = rootUrl;
  113517. _this.sceneFilename = sceneFilename;
  113518. return _this;
  113519. }
  113520. /**
  113521. * Execute the current task
  113522. * @param scene defines the scene where you want your assets to be loaded
  113523. * @param onSuccess is a callback called when the task is successfully executed
  113524. * @param onError is a callback called if an error occurs
  113525. */
  113526. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  113527. var _this = this;
  113528. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  113529. _this.loadedMeshes = meshes;
  113530. _this.loadedParticleSystems = particleSystems;
  113531. _this.loadedSkeletons = skeletons;
  113532. onSuccess();
  113533. }, null, function (scene, message, exception) {
  113534. onError(message, exception);
  113535. });
  113536. };
  113537. return MeshAssetTask;
  113538. }(AbstractAssetTask));
  113539. BABYLON.MeshAssetTask = MeshAssetTask;
  113540. /**
  113541. * Define a task used by AssetsManager to load text content
  113542. */
  113543. var TextFileAssetTask = /** @class */ (function (_super) {
  113544. __extends(TextFileAssetTask, _super);
  113545. /**
  113546. * Creates a new TextFileAssetTask object
  113547. * @param name defines the name of the task
  113548. * @param url defines the location of the file to load
  113549. */
  113550. function TextFileAssetTask(
  113551. /**
  113552. * Defines the name of the task
  113553. */
  113554. name,
  113555. /**
  113556. * Defines the location of the file to load
  113557. */
  113558. url) {
  113559. var _this = _super.call(this, name) || this;
  113560. _this.name = name;
  113561. _this.url = url;
  113562. return _this;
  113563. }
  113564. /**
  113565. * Execute the current task
  113566. * @param scene defines the scene where you want your assets to be loaded
  113567. * @param onSuccess is a callback called when the task is successfully executed
  113568. * @param onError is a callback called if an error occurs
  113569. */
  113570. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  113571. var _this = this;
  113572. scene._loadFile(this.url, function (data) {
  113573. _this.text = data;
  113574. onSuccess();
  113575. }, undefined, false, false, function (request, exception) {
  113576. if (request) {
  113577. onError(request.status + " " + request.statusText, exception);
  113578. }
  113579. });
  113580. };
  113581. return TextFileAssetTask;
  113582. }(AbstractAssetTask));
  113583. BABYLON.TextFileAssetTask = TextFileAssetTask;
  113584. /**
  113585. * Define a task used by AssetsManager to load binary data
  113586. */
  113587. var BinaryFileAssetTask = /** @class */ (function (_super) {
  113588. __extends(BinaryFileAssetTask, _super);
  113589. /**
  113590. * Creates a new BinaryFileAssetTask object
  113591. * @param name defines the name of the new task
  113592. * @param url defines the location of the file to load
  113593. */
  113594. function BinaryFileAssetTask(
  113595. /**
  113596. * Defines the name of the task
  113597. */
  113598. name,
  113599. /**
  113600. * Defines the location of the file to load
  113601. */
  113602. url) {
  113603. var _this = _super.call(this, name) || this;
  113604. _this.name = name;
  113605. _this.url = url;
  113606. return _this;
  113607. }
  113608. /**
  113609. * Execute the current task
  113610. * @param scene defines the scene where you want your assets to be loaded
  113611. * @param onSuccess is a callback called when the task is successfully executed
  113612. * @param onError is a callback called if an error occurs
  113613. */
  113614. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  113615. var _this = this;
  113616. scene._loadFile(this.url, function (data) {
  113617. _this.data = data;
  113618. onSuccess();
  113619. }, undefined, true, true, function (request, exception) {
  113620. if (request) {
  113621. onError(request.status + " " + request.statusText, exception);
  113622. }
  113623. });
  113624. };
  113625. return BinaryFileAssetTask;
  113626. }(AbstractAssetTask));
  113627. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  113628. /**
  113629. * Define a task used by AssetsManager to load images
  113630. */
  113631. var ImageAssetTask = /** @class */ (function (_super) {
  113632. __extends(ImageAssetTask, _super);
  113633. /**
  113634. * Creates a new ImageAssetTask
  113635. * @param name defines the name of the task
  113636. * @param url defines the location of the image to load
  113637. */
  113638. function ImageAssetTask(
  113639. /**
  113640. * Defines the name of the task
  113641. */
  113642. name,
  113643. /**
  113644. * Defines the location of the image to load
  113645. */
  113646. url) {
  113647. var _this = _super.call(this, name) || this;
  113648. _this.name = name;
  113649. _this.url = url;
  113650. return _this;
  113651. }
  113652. /**
  113653. * Execute the current task
  113654. * @param scene defines the scene where you want your assets to be loaded
  113655. * @param onSuccess is a callback called when the task is successfully executed
  113656. * @param onError is a callback called if an error occurs
  113657. */
  113658. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  113659. var _this = this;
  113660. var img = new Image();
  113661. BABYLON.Tools.SetCorsBehavior(this.url, img);
  113662. img.onload = function () {
  113663. _this.image = img;
  113664. onSuccess();
  113665. };
  113666. img.onerror = function (err) {
  113667. onError("Error loading image", err);
  113668. };
  113669. img.src = this.url;
  113670. };
  113671. return ImageAssetTask;
  113672. }(AbstractAssetTask));
  113673. BABYLON.ImageAssetTask = ImageAssetTask;
  113674. /**
  113675. * Define a task used by AssetsManager to load 2D textures
  113676. */
  113677. var TextureAssetTask = /** @class */ (function (_super) {
  113678. __extends(TextureAssetTask, _super);
  113679. /**
  113680. * Creates a new TextureAssetTask object
  113681. * @param name defines the name of the task
  113682. * @param url defines the location of the file to load
  113683. * @param noMipmap defines if mipmap should not be generated (default is false)
  113684. * @param invertY defines if texture must be inverted on Y axis (default is false)
  113685. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  113686. */
  113687. function TextureAssetTask(
  113688. /**
  113689. * Defines the name of the task
  113690. */
  113691. name,
  113692. /**
  113693. * Defines the location of the file to load
  113694. */
  113695. url,
  113696. /**
  113697. * Defines if mipmap should not be generated (default is false)
  113698. */
  113699. noMipmap,
  113700. /**
  113701. * Defines if texture must be inverted on Y axis (default is false)
  113702. */
  113703. invertY,
  113704. /**
  113705. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  113706. */
  113707. samplingMode) {
  113708. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  113709. var _this = _super.call(this, name) || this;
  113710. _this.name = name;
  113711. _this.url = url;
  113712. _this.noMipmap = noMipmap;
  113713. _this.invertY = invertY;
  113714. _this.samplingMode = samplingMode;
  113715. return _this;
  113716. }
  113717. /**
  113718. * Execute the current task
  113719. * @param scene defines the scene where you want your assets to be loaded
  113720. * @param onSuccess is a callback called when the task is successfully executed
  113721. * @param onError is a callback called if an error occurs
  113722. */
  113723. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  113724. var onload = function () {
  113725. onSuccess();
  113726. };
  113727. var onerror = function (message, exception) {
  113728. onError(message, exception);
  113729. };
  113730. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  113731. };
  113732. return TextureAssetTask;
  113733. }(AbstractAssetTask));
  113734. BABYLON.TextureAssetTask = TextureAssetTask;
  113735. /**
  113736. * Define a task used by AssetsManager to load cube textures
  113737. */
  113738. var CubeTextureAssetTask = /** @class */ (function (_super) {
  113739. __extends(CubeTextureAssetTask, _super);
  113740. /**
  113741. * Creates a new CubeTextureAssetTask
  113742. * @param name defines the name of the task
  113743. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  113744. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  113745. * @param noMipmap defines if mipmaps should not be generated (default is false)
  113746. * @param files defines the explicit list of files (undefined by default)
  113747. */
  113748. function CubeTextureAssetTask(
  113749. /**
  113750. * Defines the name of the task
  113751. */
  113752. name,
  113753. /**
  113754. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  113755. */
  113756. url,
  113757. /**
  113758. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  113759. */
  113760. extensions,
  113761. /**
  113762. * Defines if mipmaps should not be generated (default is false)
  113763. */
  113764. noMipmap,
  113765. /**
  113766. * Defines the explicit list of files (undefined by default)
  113767. */
  113768. files) {
  113769. var _this = _super.call(this, name) || this;
  113770. _this.name = name;
  113771. _this.url = url;
  113772. _this.extensions = extensions;
  113773. _this.noMipmap = noMipmap;
  113774. _this.files = files;
  113775. return _this;
  113776. }
  113777. /**
  113778. * Execute the current task
  113779. * @param scene defines the scene where you want your assets to be loaded
  113780. * @param onSuccess is a callback called when the task is successfully executed
  113781. * @param onError is a callback called if an error occurs
  113782. */
  113783. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  113784. var onload = function () {
  113785. onSuccess();
  113786. };
  113787. var onerror = function (message, exception) {
  113788. onError(message, exception);
  113789. };
  113790. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  113791. };
  113792. return CubeTextureAssetTask;
  113793. }(AbstractAssetTask));
  113794. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  113795. /**
  113796. * Define a task used by AssetsManager to load HDR cube textures
  113797. */
  113798. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  113799. __extends(HDRCubeTextureAssetTask, _super);
  113800. /**
  113801. * Creates a new HDRCubeTextureAssetTask object
  113802. * @param name defines the name of the task
  113803. * @param url defines the location of the file to load
  113804. * @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.
  113805. * @param noMipmap defines if mipmaps should not be generated (default is false)
  113806. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  113807. * @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)
  113808. * @param reserved Internal use only
  113809. */
  113810. function HDRCubeTextureAssetTask(
  113811. /**
  113812. * Defines the name of the task
  113813. */
  113814. name,
  113815. /**
  113816. * Defines the location of the file to load
  113817. */
  113818. url,
  113819. /**
  113820. * Defines the desired size (the more it increases the longer the generation will be)
  113821. */
  113822. size,
  113823. /**
  113824. * Defines if mipmaps should not be generated (default is false)
  113825. */
  113826. noMipmap,
  113827. /**
  113828. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  113829. */
  113830. generateHarmonics,
  113831. /**
  113832. * 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)
  113833. */
  113834. gammaSpace,
  113835. /**
  113836. * Internal Use Only
  113837. */
  113838. reserved) {
  113839. if (noMipmap === void 0) { noMipmap = false; }
  113840. if (generateHarmonics === void 0) { generateHarmonics = true; }
  113841. if (gammaSpace === void 0) { gammaSpace = false; }
  113842. if (reserved === void 0) { reserved = false; }
  113843. var _this = _super.call(this, name) || this;
  113844. _this.name = name;
  113845. _this.url = url;
  113846. _this.size = size;
  113847. _this.noMipmap = noMipmap;
  113848. _this.generateHarmonics = generateHarmonics;
  113849. _this.gammaSpace = gammaSpace;
  113850. _this.reserved = reserved;
  113851. return _this;
  113852. }
  113853. /**
  113854. * Execute the current task
  113855. * @param scene defines the scene where you want your assets to be loaded
  113856. * @param onSuccess is a callback called when the task is successfully executed
  113857. * @param onError is a callback called if an error occurs
  113858. */
  113859. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  113860. var onload = function () {
  113861. onSuccess();
  113862. };
  113863. var onerror = function (message, exception) {
  113864. onError(message, exception);
  113865. };
  113866. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.gammaSpace, this.reserved, onload, onerror);
  113867. };
  113868. return HDRCubeTextureAssetTask;
  113869. }(AbstractAssetTask));
  113870. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  113871. /**
  113872. * This class can be used to easily import assets into a scene
  113873. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  113874. */
  113875. var AssetsManager = /** @class */ (function () {
  113876. /**
  113877. * Creates a new AssetsManager
  113878. * @param scene defines the scene to work on
  113879. */
  113880. function AssetsManager(scene) {
  113881. this._isLoading = false;
  113882. this._tasks = new Array();
  113883. this._waitingTasksCount = 0;
  113884. this._totalTasksCount = 0;
  113885. /**
  113886. * Observable called when all tasks are processed
  113887. */
  113888. this.onTaskSuccessObservable = new BABYLON.Observable();
  113889. /**
  113890. * Observable called when a task had an error
  113891. */
  113892. this.onTaskErrorObservable = new BABYLON.Observable();
  113893. /**
  113894. * Observable called when a task is successful
  113895. */
  113896. this.onTasksDoneObservable = new BABYLON.Observable();
  113897. /**
  113898. * Observable called when a task is done (whatever the result is)
  113899. */
  113900. this.onProgressObservable = new BABYLON.Observable();
  113901. /**
  113902. * Gets or sets a boolean defining if the AssetsManager should use the default loading screen
  113903. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  113904. */
  113905. this.useDefaultLoadingScreen = true;
  113906. this._scene = scene;
  113907. }
  113908. /**
  113909. * Add a MeshAssetTask to the list of active tasks
  113910. * @param taskName defines the name of the new task
  113911. * @param meshesNames defines the name of meshes to load
  113912. * @param rootUrl defines the root url to use to locate files
  113913. * @param sceneFilename defines the filename of the scene file
  113914. * @returns a new MeshAssetTask object
  113915. */
  113916. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  113917. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  113918. this._tasks.push(task);
  113919. return task;
  113920. };
  113921. /**
  113922. * Add a TextFileAssetTask to the list of active tasks
  113923. * @param taskName defines the name of the new task
  113924. * @param url defines the url of the file to load
  113925. * @returns a new TextFileAssetTask object
  113926. */
  113927. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  113928. var task = new TextFileAssetTask(taskName, url);
  113929. this._tasks.push(task);
  113930. return task;
  113931. };
  113932. /**
  113933. * Add a BinaryFileAssetTask to the list of active tasks
  113934. * @param taskName defines the name of the new task
  113935. * @param url defines the url of the file to load
  113936. * @returns a new BinaryFileAssetTask object
  113937. */
  113938. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  113939. var task = new BinaryFileAssetTask(taskName, url);
  113940. this._tasks.push(task);
  113941. return task;
  113942. };
  113943. /**
  113944. * Add a ImageAssetTask to the list of active tasks
  113945. * @param taskName defines the name of the new task
  113946. * @param url defines the url of the file to load
  113947. * @returns a new ImageAssetTask object
  113948. */
  113949. AssetsManager.prototype.addImageTask = function (taskName, url) {
  113950. var task = new ImageAssetTask(taskName, url);
  113951. this._tasks.push(task);
  113952. return task;
  113953. };
  113954. /**
  113955. * Add a TextureAssetTask to the list of active tasks
  113956. * @param taskName defines the name of the new task
  113957. * @param url defines the url of the file to load
  113958. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  113959. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  113960. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  113961. * @returns a new TextureAssetTask object
  113962. */
  113963. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  113964. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  113965. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  113966. this._tasks.push(task);
  113967. return task;
  113968. };
  113969. /**
  113970. * Add a CubeTextureAssetTask to the list of active tasks
  113971. * @param taskName defines the name of the new task
  113972. * @param url defines the url of the file to load
  113973. * @param extensions defines the extension to use to load the cube map (can be null)
  113974. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  113975. * @param files defines the list of files to load (can be null)
  113976. * @returns a new CubeTextureAssetTask object
  113977. */
  113978. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  113979. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  113980. this._tasks.push(task);
  113981. return task;
  113982. };
  113983. /**
  113984. *
  113985. * Add a HDRCubeTextureAssetTask to the list of active tasks
  113986. * @param taskName defines the name of the new task
  113987. * @param url defines the url of the file to load
  113988. * @param size defines the size you want for the cubemap (can be null)
  113989. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  113990. * @param generateHarmonics defines if you want to automatically generate (true by default)
  113991. * @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)
  113992. * @param reserved Internal use only
  113993. * @returns a new HDRCubeTextureAssetTask object
  113994. */
  113995. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved) {
  113996. if (noMipmap === void 0) { noMipmap = false; }
  113997. if (generateHarmonics === void 0) { generateHarmonics = true; }
  113998. if (gammaSpace === void 0) { gammaSpace = false; }
  113999. if (reserved === void 0) { reserved = false; }
  114000. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved);
  114001. this._tasks.push(task);
  114002. return task;
  114003. };
  114004. /**
  114005. * Remove a task from the assets manager.
  114006. * @param task the task to remove
  114007. */
  114008. AssetsManager.prototype.removeTask = function (task) {
  114009. var index = this._tasks.indexOf(task);
  114010. if (index > -1) {
  114011. this._tasks.splice(index, 1);
  114012. }
  114013. };
  114014. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  114015. this._waitingTasksCount--;
  114016. try {
  114017. if (this.onProgress) {
  114018. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  114019. }
  114020. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  114021. }
  114022. catch (e) {
  114023. BABYLON.Tools.Error("Error running progress callbacks.");
  114024. console.log(e);
  114025. }
  114026. if (this._waitingTasksCount === 0) {
  114027. try {
  114028. if (this.onFinish) {
  114029. this.onFinish(this._tasks);
  114030. }
  114031. // Let's remove successfull tasks
  114032. var currentTasks = this._tasks.slice();
  114033. for (var _i = 0, currentTasks_1 = currentTasks; _i < currentTasks_1.length; _i++) {
  114034. var task = currentTasks_1[_i];
  114035. if (task.taskState === AssetTaskState.DONE) {
  114036. var index = this._tasks.indexOf(task);
  114037. if (index > -1) {
  114038. this._tasks.splice(index, 1);
  114039. }
  114040. }
  114041. }
  114042. this.onTasksDoneObservable.notifyObservers(this._tasks);
  114043. }
  114044. catch (e) {
  114045. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  114046. console.log(e);
  114047. }
  114048. this._isLoading = false;
  114049. this._scene.getEngine().hideLoadingUI();
  114050. }
  114051. };
  114052. AssetsManager.prototype._runTask = function (task) {
  114053. var _this = this;
  114054. var done = function () {
  114055. try {
  114056. if (_this.onTaskSuccess) {
  114057. _this.onTaskSuccess(task);
  114058. }
  114059. _this.onTaskSuccessObservable.notifyObservers(task);
  114060. _this._decreaseWaitingTasksCount(task);
  114061. }
  114062. catch (e) {
  114063. error("Error executing task success callbacks", e);
  114064. }
  114065. };
  114066. var error = function (message, exception) {
  114067. task._setErrorObject(message, exception);
  114068. if (_this.onTaskError) {
  114069. _this.onTaskError(task);
  114070. }
  114071. _this.onTaskErrorObservable.notifyObservers(task);
  114072. _this._decreaseWaitingTasksCount(task);
  114073. };
  114074. task.run(this._scene, done, error);
  114075. };
  114076. /**
  114077. * Reset the AssetsManager and remove all tasks
  114078. * @return the current instance of the AssetsManager
  114079. */
  114080. AssetsManager.prototype.reset = function () {
  114081. this._isLoading = false;
  114082. this._tasks = new Array();
  114083. return this;
  114084. };
  114085. /**
  114086. * Start the loading process
  114087. * @return the current instance of the AssetsManager
  114088. */
  114089. AssetsManager.prototype.load = function () {
  114090. if (this._isLoading) {
  114091. return this;
  114092. }
  114093. this._isLoading = true;
  114094. this._waitingTasksCount = this._tasks.length;
  114095. this._totalTasksCount = this._tasks.length;
  114096. if (this._waitingTasksCount === 0) {
  114097. this._isLoading = false;
  114098. if (this.onFinish) {
  114099. this.onFinish(this._tasks);
  114100. }
  114101. this.onTasksDoneObservable.notifyObservers(this._tasks);
  114102. return this;
  114103. }
  114104. if (this.useDefaultLoadingScreen) {
  114105. this._scene.getEngine().displayLoadingUI();
  114106. }
  114107. for (var index = 0; index < this._tasks.length; index++) {
  114108. var task = this._tasks[index];
  114109. if (task.taskState === AssetTaskState.INIT) {
  114110. this._runTask(task);
  114111. }
  114112. }
  114113. return this;
  114114. };
  114115. return AssetsManager;
  114116. }());
  114117. BABYLON.AssetsManager = AssetsManager;
  114118. })(BABYLON || (BABYLON = {}));
  114119. //# sourceMappingURL=babylon.assetsManager.js.map
  114120. var BABYLON;
  114121. (function (BABYLON) {
  114122. var serializedGeometries = [];
  114123. var serializeGeometry = function (geometry, serializationGeometries) {
  114124. if (serializedGeometries[geometry.id]) {
  114125. return;
  114126. }
  114127. if (geometry.doNotSerialize) {
  114128. return;
  114129. }
  114130. if (geometry instanceof BABYLON.BoxGeometry) {
  114131. serializationGeometries.boxes.push(geometry.serialize());
  114132. }
  114133. else if (geometry instanceof BABYLON.SphereGeometry) {
  114134. serializationGeometries.spheres.push(geometry.serialize());
  114135. }
  114136. else if (geometry instanceof BABYLON.CylinderGeometry) {
  114137. serializationGeometries.cylinders.push(geometry.serialize());
  114138. }
  114139. else if (geometry instanceof BABYLON.TorusGeometry) {
  114140. serializationGeometries.toruses.push(geometry.serialize());
  114141. }
  114142. else if (geometry instanceof BABYLON.GroundGeometry) {
  114143. serializationGeometries.grounds.push(geometry.serialize());
  114144. }
  114145. else if (geometry instanceof BABYLON.Plane) {
  114146. serializationGeometries.planes.push(geometry.serialize());
  114147. }
  114148. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  114149. serializationGeometries.torusKnots.push(geometry.serialize());
  114150. }
  114151. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  114152. throw new Error("Unknown primitive type");
  114153. }
  114154. else {
  114155. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  114156. }
  114157. serializedGeometries[geometry.id] = true;
  114158. };
  114159. var serializeMesh = function (mesh, serializationScene) {
  114160. var serializationObject = {};
  114161. // Geometry
  114162. var geometry = mesh._geometry;
  114163. if (geometry) {
  114164. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  114165. // 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
  114166. serializeGeometry(geometry, serializationScene.geometries);
  114167. }
  114168. }
  114169. // Custom
  114170. if (mesh.serialize) {
  114171. mesh.serialize(serializationObject);
  114172. }
  114173. return serializationObject;
  114174. };
  114175. var finalizeSingleMesh = function (mesh, serializationObject) {
  114176. //only works if the mesh is already loaded
  114177. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  114178. //serialize material
  114179. if (mesh.material) {
  114180. if (mesh.material instanceof BABYLON.MultiMaterial) {
  114181. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  114182. serializationObject.materials = serializationObject.materials || [];
  114183. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  114184. serializationObject.multiMaterials.push(mesh.material.serialize());
  114185. var _loop_1 = function (submaterial) {
  114186. if (submaterial) {
  114187. if (!serializationObject.materials.some(function (mat) { return (mat.id === submaterial.id); })) {
  114188. serializationObject.materials.push(submaterial.serialize());
  114189. }
  114190. }
  114191. };
  114192. for (var _i = 0, _a = mesh.material.subMaterials; _i < _a.length; _i++) {
  114193. var submaterial = _a[_i];
  114194. _loop_1(submaterial);
  114195. }
  114196. }
  114197. }
  114198. else {
  114199. serializationObject.materials = serializationObject.materials || [];
  114200. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  114201. serializationObject.materials.push(mesh.material.serialize());
  114202. }
  114203. }
  114204. }
  114205. //serialize geometry
  114206. var geometry = mesh._geometry;
  114207. if (geometry) {
  114208. if (!serializationObject.geometries) {
  114209. serializationObject.geometries = {};
  114210. serializationObject.geometries.boxes = [];
  114211. serializationObject.geometries.spheres = [];
  114212. serializationObject.geometries.cylinders = [];
  114213. serializationObject.geometries.toruses = [];
  114214. serializationObject.geometries.grounds = [];
  114215. serializationObject.geometries.planes = [];
  114216. serializationObject.geometries.torusKnots = [];
  114217. serializationObject.geometries.vertexData = [];
  114218. }
  114219. serializeGeometry(geometry, serializationObject.geometries);
  114220. }
  114221. // Skeletons
  114222. if (mesh.skeleton) {
  114223. serializationObject.skeletons = serializationObject.skeletons || [];
  114224. serializationObject.skeletons.push(mesh.skeleton.serialize());
  114225. }
  114226. //serialize the actual mesh
  114227. serializationObject.meshes = serializationObject.meshes || [];
  114228. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  114229. }
  114230. };
  114231. /**
  114232. * Class used to serialize a scene into a string
  114233. */
  114234. var SceneSerializer = /** @class */ (function () {
  114235. function SceneSerializer() {
  114236. }
  114237. /**
  114238. * Clear cache used by a previous serialization
  114239. */
  114240. SceneSerializer.ClearCache = function () {
  114241. serializedGeometries = [];
  114242. };
  114243. /**
  114244. * Serialize a scene into a JSON compatible object
  114245. * @param scene defines the scene to serialize
  114246. * @returns a JSON compatible object
  114247. */
  114248. SceneSerializer.Serialize = function (scene) {
  114249. var serializationObject = {};
  114250. SceneSerializer.ClearCache();
  114251. // Scene
  114252. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  114253. serializationObject.autoClear = scene.autoClear;
  114254. serializationObject.clearColor = scene.clearColor.asArray();
  114255. serializationObject.ambientColor = scene.ambientColor.asArray();
  114256. serializationObject.gravity = scene.gravity.asArray();
  114257. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  114258. serializationObject.workerCollisions = scene.workerCollisions;
  114259. // Fog
  114260. if (scene.fogMode && scene.fogMode !== 0) {
  114261. serializationObject.fogMode = scene.fogMode;
  114262. serializationObject.fogColor = scene.fogColor.asArray();
  114263. serializationObject.fogStart = scene.fogStart;
  114264. serializationObject.fogEnd = scene.fogEnd;
  114265. serializationObject.fogDensity = scene.fogDensity;
  114266. }
  114267. //Physics
  114268. if (scene.isPhysicsEnabled()) {
  114269. var physicEngine = scene.getPhysicsEngine();
  114270. if (physicEngine) {
  114271. serializationObject.physicsEnabled = true;
  114272. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  114273. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  114274. }
  114275. }
  114276. // Metadata
  114277. if (scene.metadata) {
  114278. serializationObject.metadata = scene.metadata;
  114279. }
  114280. // Morph targets
  114281. serializationObject.morphTargetManagers = [];
  114282. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  114283. var abstractMesh = _a[_i];
  114284. var manager = abstractMesh.morphTargetManager;
  114285. if (manager) {
  114286. serializationObject.morphTargetManagers.push(manager.serialize());
  114287. }
  114288. }
  114289. // Lights
  114290. serializationObject.lights = [];
  114291. var index;
  114292. var light;
  114293. for (index = 0; index < scene.lights.length; index++) {
  114294. light = scene.lights[index];
  114295. if (!light.doNotSerialize) {
  114296. serializationObject.lights.push(light.serialize());
  114297. }
  114298. }
  114299. // Cameras
  114300. serializationObject.cameras = [];
  114301. for (index = 0; index < scene.cameras.length; index++) {
  114302. var camera = scene.cameras[index];
  114303. if (!camera.doNotSerialize) {
  114304. serializationObject.cameras.push(camera.serialize());
  114305. }
  114306. }
  114307. if (scene.activeCamera) {
  114308. serializationObject.activeCameraID = scene.activeCamera.id;
  114309. }
  114310. // Animations
  114311. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  114312. // Materials
  114313. serializationObject.materials = [];
  114314. serializationObject.multiMaterials = [];
  114315. var material;
  114316. for (index = 0; index < scene.materials.length; index++) {
  114317. material = scene.materials[index];
  114318. if (!material.doNotSerialize) {
  114319. serializationObject.materials.push(material.serialize());
  114320. }
  114321. }
  114322. // MultiMaterials
  114323. serializationObject.multiMaterials = [];
  114324. for (index = 0; index < scene.multiMaterials.length; index++) {
  114325. var multiMaterial = scene.multiMaterials[index];
  114326. serializationObject.multiMaterials.push(multiMaterial.serialize());
  114327. }
  114328. // Environment texture
  114329. if (scene.environmentTexture) {
  114330. serializationObject.environmentTexture = scene.environmentTexture.name;
  114331. }
  114332. // Skeletons
  114333. serializationObject.skeletons = [];
  114334. for (index = 0; index < scene.skeletons.length; index++) {
  114335. var skeleton = scene.skeletons[index];
  114336. if (!skeleton.doNotSerialize) {
  114337. serializationObject.skeletons.push(skeleton.serialize());
  114338. }
  114339. }
  114340. // Transform nodes
  114341. serializationObject.transformNodes = [];
  114342. for (index = 0; index < scene.transformNodes.length; index++) {
  114343. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  114344. }
  114345. // Geometries
  114346. serializationObject.geometries = {};
  114347. serializationObject.geometries.boxes = [];
  114348. serializationObject.geometries.spheres = [];
  114349. serializationObject.geometries.cylinders = [];
  114350. serializationObject.geometries.toruses = [];
  114351. serializationObject.geometries.grounds = [];
  114352. serializationObject.geometries.planes = [];
  114353. serializationObject.geometries.torusKnots = [];
  114354. serializationObject.geometries.vertexData = [];
  114355. serializedGeometries = [];
  114356. var geometries = scene.getGeometries();
  114357. for (index = 0; index < geometries.length; index++) {
  114358. var geometry = geometries[index];
  114359. if (geometry.isReady()) {
  114360. serializeGeometry(geometry, serializationObject.geometries);
  114361. }
  114362. }
  114363. // Meshes
  114364. serializationObject.meshes = [];
  114365. for (index = 0; index < scene.meshes.length; index++) {
  114366. var abstractMesh = scene.meshes[index];
  114367. if (abstractMesh instanceof BABYLON.Mesh) {
  114368. var mesh = abstractMesh;
  114369. if (!mesh.doNotSerialize) {
  114370. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  114371. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  114372. }
  114373. }
  114374. }
  114375. }
  114376. // Particles Systems
  114377. serializationObject.particleSystems = [];
  114378. for (index = 0; index < scene.particleSystems.length; index++) {
  114379. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  114380. }
  114381. // Action Manager
  114382. if (scene.actionManager) {
  114383. serializationObject.actions = scene.actionManager.serialize("scene");
  114384. }
  114385. // Components
  114386. for (var _b = 0, _c = scene._serializableComponents; _b < _c.length; _b++) {
  114387. var component = _c[_b];
  114388. component.serialize(serializationObject);
  114389. }
  114390. return serializationObject;
  114391. };
  114392. /**
  114393. * Serialize a mesh into a JSON compatible object
  114394. * @param toSerialize defines the mesh to serialize
  114395. * @param withParents defines if parents must be serialized as well
  114396. * @param withChildren defines if children must be serialized as well
  114397. * @returns a JSON compatible object
  114398. */
  114399. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  114400. if (withParents === void 0) { withParents = false; }
  114401. if (withChildren === void 0) { withChildren = false; }
  114402. var serializationObject = {};
  114403. SceneSerializer.ClearCache();
  114404. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  114405. if (withParents || withChildren) {
  114406. //deliberate for loop! not for each, appended should be processed as well.
  114407. for (var i = 0; i < toSerialize.length; ++i) {
  114408. if (withChildren) {
  114409. toSerialize[i].getDescendants().forEach(function (node) {
  114410. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  114411. toSerialize.push(node);
  114412. }
  114413. });
  114414. }
  114415. //make sure the array doesn't contain the object already
  114416. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  114417. toSerialize.push(toSerialize[i].parent);
  114418. }
  114419. }
  114420. }
  114421. toSerialize.forEach(function (mesh) {
  114422. finalizeSingleMesh(mesh, serializationObject);
  114423. });
  114424. return serializationObject;
  114425. };
  114426. return SceneSerializer;
  114427. }());
  114428. BABYLON.SceneSerializer = SceneSerializer;
  114429. })(BABYLON || (BABYLON = {}));
  114430. //# sourceMappingURL=babylon.sceneSerializer.js.map
  114431. var BABYLON;
  114432. (function (BABYLON) {
  114433. /**
  114434. * Class used to generate realtime reflection / refraction cube textures
  114435. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  114436. */
  114437. var ReflectionProbe = /** @class */ (function () {
  114438. /**
  114439. * Creates a new reflection probe
  114440. * @param name defines the name of the probe
  114441. * @param size defines the texture resolution (for each face)
  114442. * @param scene defines the hosting scene
  114443. * @param generateMipMaps defines if mip maps should be generated automatically (true by default)
  114444. * @param useFloat defines if HDR data (flaot data) should be used to store colors (false by default)
  114445. */
  114446. function ReflectionProbe(
  114447. /** defines the name of the probe */
  114448. name, size, scene, generateMipMaps, useFloat) {
  114449. if (generateMipMaps === void 0) { generateMipMaps = true; }
  114450. if (useFloat === void 0) { useFloat = false; }
  114451. var _this = this;
  114452. this.name = name;
  114453. this._viewMatrix = BABYLON.Matrix.Identity();
  114454. this._target = BABYLON.Vector3.Zero();
  114455. this._add = BABYLON.Vector3.Zero();
  114456. this._invertYAxis = false;
  114457. /** Gets or sets probe position (center of the cube map) */
  114458. this.position = BABYLON.Vector3.Zero();
  114459. this._scene = scene;
  114460. // Create the scene field if not exist.
  114461. if (!this._scene.reflectionProbes) {
  114462. this._scene.reflectionProbes = new Array();
  114463. }
  114464. this._scene.reflectionProbes.push(this);
  114465. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, useFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  114466. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  114467. switch (faceIndex) {
  114468. case 0:
  114469. _this._add.copyFromFloats(1, 0, 0);
  114470. break;
  114471. case 1:
  114472. _this._add.copyFromFloats(-1, 0, 0);
  114473. break;
  114474. case 2:
  114475. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  114476. break;
  114477. case 3:
  114478. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  114479. break;
  114480. case 4:
  114481. _this._add.copyFromFloats(0, 0, 1);
  114482. break;
  114483. case 5:
  114484. _this._add.copyFromFloats(0, 0, -1);
  114485. break;
  114486. }
  114487. if (_this._attachedMesh) {
  114488. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  114489. }
  114490. _this.position.addToRef(_this._add, _this._target);
  114491. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  114492. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  114493. scene._forcedViewPosition = _this.position;
  114494. });
  114495. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  114496. scene._forcedViewPosition = null;
  114497. scene.updateTransformMatrix(true);
  114498. });
  114499. if (scene.activeCamera) {
  114500. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  114501. }
  114502. }
  114503. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  114504. /** Gets or sets the number of samples to use for multi-sampling (0 by default). Required WebGL2 */
  114505. get: function () {
  114506. return this._renderTargetTexture.samples;
  114507. },
  114508. set: function (value) {
  114509. this._renderTargetTexture.samples = value;
  114510. },
  114511. enumerable: true,
  114512. configurable: true
  114513. });
  114514. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  114515. /** Gets or sets the refresh rate to use (on every frame by default) */
  114516. get: function () {
  114517. return this._renderTargetTexture.refreshRate;
  114518. },
  114519. set: function (value) {
  114520. this._renderTargetTexture.refreshRate = value;
  114521. },
  114522. enumerable: true,
  114523. configurable: true
  114524. });
  114525. /**
  114526. * Gets the hosting scene
  114527. * @returns a Scene
  114528. */
  114529. ReflectionProbe.prototype.getScene = function () {
  114530. return this._scene;
  114531. };
  114532. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  114533. /** Gets the internal CubeTexture used to render to */
  114534. get: function () {
  114535. return this._renderTargetTexture;
  114536. },
  114537. enumerable: true,
  114538. configurable: true
  114539. });
  114540. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  114541. /** Gets the list of meshes to render */
  114542. get: function () {
  114543. return this._renderTargetTexture.renderList;
  114544. },
  114545. enumerable: true,
  114546. configurable: true
  114547. });
  114548. /**
  114549. * Attach the probe to a specific mesh (Rendering will be done from attached mesh's position)
  114550. * @param mesh defines the mesh to attach to
  114551. */
  114552. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  114553. this._attachedMesh = mesh;
  114554. };
  114555. /**
  114556. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups
  114557. * @param renderingGroupId The rendering group id corresponding to its index
  114558. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  114559. */
  114560. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  114561. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  114562. };
  114563. /**
  114564. * Clean all associated resources
  114565. */
  114566. ReflectionProbe.prototype.dispose = function () {
  114567. var index = this._scene.reflectionProbes.indexOf(this);
  114568. if (index !== -1) {
  114569. // Remove from the scene if found
  114570. this._scene.reflectionProbes.splice(index, 1);
  114571. }
  114572. if (this._renderTargetTexture) {
  114573. this._renderTargetTexture.dispose();
  114574. this._renderTargetTexture = null;
  114575. }
  114576. };
  114577. return ReflectionProbe;
  114578. }());
  114579. BABYLON.ReflectionProbe = ReflectionProbe;
  114580. })(BABYLON || (BABYLON = {}));
  114581. //# sourceMappingURL=babylon.reflectionProbe.js.map
  114582. var BABYLON;
  114583. (function (BABYLON) {
  114584. /**
  114585. * Defines the layer scene component responsible to manage any layers
  114586. * in a given scene.
  114587. */
  114588. var LayerSceneComponent = /** @class */ (function () {
  114589. /**
  114590. * Creates a new instance of the component for the given scene
  114591. * @param scene Defines the scene to register the component in
  114592. */
  114593. function LayerSceneComponent(scene) {
  114594. /**
  114595. * The component name helpfull to identify the component in the list of scene components.
  114596. */
  114597. this.name = BABYLON.SceneComponentConstants.NAME_LAYER;
  114598. this.scene = scene;
  114599. this._engine = scene.getEngine();
  114600. scene.layers = new Array();
  114601. }
  114602. /**
  114603. * Registers the component in a given scene
  114604. */
  114605. LayerSceneComponent.prototype.register = function () {
  114606. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER, this, this._drawCameraBackground);
  114607. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER, this, this._drawCameraForeground);
  114608. this.scene._beforeRenderTargetDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORERENDERTARGETDRAW_LAYER, this, this._drawRenderTargetBackground);
  114609. this.scene._afterRenderTargetDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERTARGETDRAW_LAYER, this, this._drawRenderTargetForeground);
  114610. };
  114611. /**
  114612. * Rebuilds the elements related to this component in case of
  114613. * context lost for instance.
  114614. */
  114615. LayerSceneComponent.prototype.rebuild = function () {
  114616. var layers = this.scene.layers;
  114617. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  114618. var layer = layers_1[_i];
  114619. layer._rebuild();
  114620. }
  114621. };
  114622. /**
  114623. * Disposes the component and the associated ressources.
  114624. */
  114625. LayerSceneComponent.prototype.dispose = function () {
  114626. var layers = this.scene.layers;
  114627. while (layers.length) {
  114628. layers[0].dispose();
  114629. }
  114630. };
  114631. LayerSceneComponent.prototype._draw = function (predicate) {
  114632. var layers = this.scene.layers;
  114633. if (layers.length) {
  114634. this._engine.setDepthBuffer(false);
  114635. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  114636. var layer = layers_2[_i];
  114637. if (predicate(layer)) {
  114638. layer.render();
  114639. }
  114640. }
  114641. this._engine.setDepthBuffer(true);
  114642. }
  114643. };
  114644. LayerSceneComponent.prototype._drawCameraPredicate = function (layer, isBackground, cameraLayerMask) {
  114645. return !layer.renderOnlyInRenderTargetTextures &&
  114646. layer.isBackground === isBackground &&
  114647. ((layer.layerMask & cameraLayerMask) !== 0);
  114648. };
  114649. LayerSceneComponent.prototype._drawCameraBackground = function (camera) {
  114650. var _this = this;
  114651. this._draw(function (layer) {
  114652. return _this._drawCameraPredicate(layer, true, camera.layerMask);
  114653. });
  114654. };
  114655. LayerSceneComponent.prototype._drawCameraForeground = function (camera) {
  114656. var _this = this;
  114657. this._draw(function (layer) {
  114658. return _this._drawCameraPredicate(layer, false, camera.layerMask);
  114659. });
  114660. };
  114661. LayerSceneComponent.prototype._drawRenderTargetPredicate = function (layer, isBackground, cameraLayerMask, renderTargetTexture) {
  114662. return (layer.renderTargetTextures.length > 0) &&
  114663. layer.isBackground === isBackground &&
  114664. (layer.renderTargetTextures.indexOf(renderTargetTexture) > -1) &&
  114665. ((layer.layerMask & cameraLayerMask) !== 0);
  114666. };
  114667. LayerSceneComponent.prototype._drawRenderTargetBackground = function (renderTarget) {
  114668. var _this = this;
  114669. this._draw(function (layer) {
  114670. return _this._drawRenderTargetPredicate(layer, true, _this.scene.activeCamera.layerMask, renderTarget);
  114671. });
  114672. };
  114673. LayerSceneComponent.prototype._drawRenderTargetForeground = function (renderTarget) {
  114674. var _this = this;
  114675. this._draw(function (layer) {
  114676. return _this._drawRenderTargetPredicate(layer, false, _this.scene.activeCamera.layerMask, renderTarget);
  114677. });
  114678. };
  114679. return LayerSceneComponent;
  114680. }());
  114681. BABYLON.LayerSceneComponent = LayerSceneComponent;
  114682. })(BABYLON || (BABYLON = {}));
  114683. //# sourceMappingURL=babylon.layerSceneComponent.js.map
  114684. var BABYLON;
  114685. (function (BABYLON) {
  114686. /**
  114687. * This represents a full screen 2d layer.
  114688. * This can be usefull to display a picture in the background of your scene for instance.
  114689. * @see https://www.babylonjs-playground.com/#08A2BS#1
  114690. */
  114691. var Layer = /** @class */ (function () {
  114692. /**
  114693. * Instantiates a new layer.
  114694. * This represents a full screen 2d layer.
  114695. * This can be usefull to display a picture in the background of your scene for instance.
  114696. * @see https://www.babylonjs-playground.com/#08A2BS#1
  114697. * @param name Define the name of the layer in the scene
  114698. * @param imgUrl Define the url of the texture to display in the layer
  114699. * @param scene Define the scene the layer belongs to
  114700. * @param isBackground Defines whether the layer is displayed in front or behind the scene
  114701. * @param color Defines a color for the layer
  114702. */
  114703. function Layer(
  114704. /**
  114705. * Define the name of the layer.
  114706. */
  114707. name, imgUrl, scene, isBackground, color) {
  114708. this.name = name;
  114709. /**
  114710. * Define the scale of the layer in order to zoom in out of the texture.
  114711. */
  114712. this.scale = new BABYLON.Vector2(1, 1);
  114713. /**
  114714. * Define an offset for the layer in order to shift the texture.
  114715. */
  114716. this.offset = new BABYLON.Vector2(0, 0);
  114717. /**
  114718. * Define the alpha blending mode used in the layer in case the texture or color has an alpha.
  114719. */
  114720. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  114721. /**
  114722. * Define a mask to restrict the layer to only some of the scene cameras.
  114723. */
  114724. this.layerMask = 0x0FFFFFFF;
  114725. /**
  114726. * Define the list of render target the layer is visible into.
  114727. */
  114728. this.renderTargetTextures = [];
  114729. /**
  114730. * Define if the layer is only used in renderTarget or if it also
  114731. * renders in the main frame buffer of the canvas.
  114732. */
  114733. this.renderOnlyInRenderTargetTextures = false;
  114734. this._vertexBuffers = {};
  114735. /**
  114736. * An event triggered when the layer is disposed.
  114737. */
  114738. this.onDisposeObservable = new BABYLON.Observable();
  114739. /**
  114740. * An event triggered before rendering the scene
  114741. */
  114742. this.onBeforeRenderObservable = new BABYLON.Observable();
  114743. /**
  114744. * An event triggered after rendering the scene
  114745. */
  114746. this.onAfterRenderObservable = new BABYLON.Observable();
  114747. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  114748. this.isBackground = isBackground === undefined ? true : isBackground;
  114749. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  114750. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  114751. var layerComponent = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LAYER);
  114752. if (!layerComponent) {
  114753. layerComponent = new BABYLON.LayerSceneComponent(this._scene);
  114754. this._scene._addComponent(layerComponent);
  114755. }
  114756. this._scene.layers.push(this);
  114757. var engine = this._scene.getEngine();
  114758. // VBO
  114759. var vertices = [];
  114760. vertices.push(1, 1);
  114761. vertices.push(-1, 1);
  114762. vertices.push(-1, -1);
  114763. vertices.push(1, -1);
  114764. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  114765. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  114766. this._createIndexBuffer();
  114767. // Effects
  114768. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  114769. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  114770. }
  114771. Object.defineProperty(Layer.prototype, "onDispose", {
  114772. /**
  114773. * Back compatibility with callback before the onDisposeObservable existed.
  114774. * The set callback will be triggered when the layer has been disposed.
  114775. */
  114776. set: function (callback) {
  114777. if (this._onDisposeObserver) {
  114778. this.onDisposeObservable.remove(this._onDisposeObserver);
  114779. }
  114780. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  114781. },
  114782. enumerable: true,
  114783. configurable: true
  114784. });
  114785. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  114786. /**
  114787. * Back compatibility with callback before the onBeforeRenderObservable existed.
  114788. * The set callback will be triggered just before rendering the layer.
  114789. */
  114790. set: function (callback) {
  114791. if (this._onBeforeRenderObserver) {
  114792. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  114793. }
  114794. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  114795. },
  114796. enumerable: true,
  114797. configurable: true
  114798. });
  114799. Object.defineProperty(Layer.prototype, "onAfterRender", {
  114800. /**
  114801. * Back compatibility with callback before the onAfterRenderObservable existed.
  114802. * The set callback will be triggered just after rendering the layer.
  114803. */
  114804. set: function (callback) {
  114805. if (this._onAfterRenderObserver) {
  114806. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  114807. }
  114808. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  114809. },
  114810. enumerable: true,
  114811. configurable: true
  114812. });
  114813. Layer.prototype._createIndexBuffer = function () {
  114814. var engine = this._scene.getEngine();
  114815. // Indices
  114816. var indices = [];
  114817. indices.push(0);
  114818. indices.push(1);
  114819. indices.push(2);
  114820. indices.push(0);
  114821. indices.push(2);
  114822. indices.push(3);
  114823. this._indexBuffer = engine.createIndexBuffer(indices);
  114824. };
  114825. /** @hidden */
  114826. Layer.prototype._rebuild = function () {
  114827. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  114828. if (vb) {
  114829. vb._rebuild();
  114830. }
  114831. this._createIndexBuffer();
  114832. };
  114833. /**
  114834. * Renders the layer in the scene.
  114835. */
  114836. Layer.prototype.render = function () {
  114837. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  114838. // Check
  114839. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady()) {
  114840. return;
  114841. }
  114842. var engine = this._scene.getEngine();
  114843. this.onBeforeRenderObservable.notifyObservers(this);
  114844. // Render
  114845. engine.enableEffect(currentEffect);
  114846. engine.setState(false);
  114847. // Texture
  114848. currentEffect.setTexture("textureSampler", this.texture);
  114849. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  114850. // Color
  114851. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  114852. // Scale / offset
  114853. currentEffect.setVector2("offset", this.offset);
  114854. currentEffect.setVector2("scale", this.scale);
  114855. // VBOs
  114856. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  114857. // Draw order
  114858. if (!this.alphaTest) {
  114859. engine.setAlphaMode(this.alphaBlendingMode);
  114860. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  114861. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  114862. }
  114863. else {
  114864. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  114865. }
  114866. this.onAfterRenderObservable.notifyObservers(this);
  114867. };
  114868. /**
  114869. * Disposes and releases the associated ressources.
  114870. */
  114871. Layer.prototype.dispose = function () {
  114872. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  114873. if (vertexBuffer) {
  114874. vertexBuffer.dispose();
  114875. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  114876. }
  114877. if (this._indexBuffer) {
  114878. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  114879. this._indexBuffer = null;
  114880. }
  114881. if (this.texture) {
  114882. this.texture.dispose();
  114883. this.texture = null;
  114884. }
  114885. // Clean RTT list
  114886. this.renderTargetTextures = [];
  114887. // Remove from scene
  114888. var index = this._scene.layers.indexOf(this);
  114889. this._scene.layers.splice(index, 1);
  114890. // Callback
  114891. this.onDisposeObservable.notifyObservers(this);
  114892. this.onDisposeObservable.clear();
  114893. this.onAfterRenderObservable.clear();
  114894. this.onBeforeRenderObservable.clear();
  114895. };
  114896. return Layer;
  114897. }());
  114898. BABYLON.Layer = Layer;
  114899. })(BABYLON || (BABYLON = {}));
  114900. //# sourceMappingURL=babylon.layer.js.map
  114901. var BABYLON;
  114902. (function (BABYLON) {
  114903. /**
  114904. * Class used to host texture specific utilities
  114905. */
  114906. var TextureTools = /** @class */ (function () {
  114907. function TextureTools() {
  114908. }
  114909. /**
  114910. * Uses the GPU to create a copy texture rescaled at a given size
  114911. * @param texture Texture to copy from
  114912. * @param width defines the desired width
  114913. * @param height defines the desired height
  114914. * @param useBilinearMode defines if bilinear mode has to be used
  114915. * @return the generated texture
  114916. */
  114917. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  114918. if (useBilinearMode === void 0) { useBilinearMode = true; }
  114919. var scene = texture.getScene();
  114920. var engine = scene.getEngine();
  114921. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  114922. rtt.wrapU = texture.wrapU;
  114923. rtt.wrapV = texture.wrapV;
  114924. rtt.uOffset = texture.uOffset;
  114925. rtt.vOffset = texture.vOffset;
  114926. rtt.uScale = texture.uScale;
  114927. rtt.vScale = texture.vScale;
  114928. rtt.uAng = texture.uAng;
  114929. rtt.vAng = texture.vAng;
  114930. rtt.wAng = texture.wAng;
  114931. rtt.coordinatesIndex = texture.coordinatesIndex;
  114932. rtt.level = texture.level;
  114933. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  114934. rtt._texture.isReady = false;
  114935. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  114936. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  114937. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  114938. passPostProcess.getEffect().executeWhenCompiled(function () {
  114939. passPostProcess.onApply = function (effect) {
  114940. effect.setTexture("textureSampler", texture);
  114941. };
  114942. var internalTexture = rtt.getInternalTexture();
  114943. if (internalTexture) {
  114944. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  114945. engine.unBindFramebuffer(internalTexture);
  114946. rtt.disposeFramebufferObjects();
  114947. passPostProcess.dispose();
  114948. internalTexture.isReady = true;
  114949. }
  114950. });
  114951. return rtt;
  114952. };
  114953. /**
  114954. * Gets an environment BRDF texture for a given scene
  114955. * @param scene defines the hosting scene
  114956. * @returns the environment BRDF texture
  114957. */
  114958. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  114959. if (!scene._environmentBRDFTexture) {
  114960. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  114961. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  114962. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  114963. scene._environmentBRDFTexture = texture;
  114964. }
  114965. return scene._environmentBRDFTexture;
  114966. };
  114967. 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=";
  114968. return TextureTools;
  114969. }());
  114970. BABYLON.TextureTools = TextureTools;
  114971. })(BABYLON || (BABYLON = {}));
  114972. //# sourceMappingURL=babylon.textureTools.js.map
  114973. var BABYLON;
  114974. (function (BABYLON) {
  114975. /**
  114976. * 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.
  114977. * @see http://doc.babylonjs.com/how_to/camera_behaviors#framing-behavior
  114978. */
  114979. var FramingBehavior = /** @class */ (function () {
  114980. function FramingBehavior() {
  114981. this._mode = FramingBehavior.FitFrustumSidesMode;
  114982. this._radiusScale = 1.0;
  114983. this._positionScale = 0.5;
  114984. this._defaultElevation = 0.3;
  114985. this._elevationReturnTime = 1500;
  114986. this._elevationReturnWaitTime = 1000;
  114987. this._zoomStopsAnimation = false;
  114988. this._framingTime = 1500;
  114989. /**
  114990. * Define if the behavior should automatically change the configured
  114991. * camera limits and sensibilities.
  114992. */
  114993. this.autoCorrectCameraLimitsAndSensibility = true;
  114994. this._isPointerDown = false;
  114995. this._lastInteractionTime = -Infinity;
  114996. // Framing control
  114997. this._animatables = new Array();
  114998. this._betaIsAnimating = false;
  114999. }
  115000. Object.defineProperty(FramingBehavior.prototype, "name", {
  115001. /**
  115002. * Gets the name of the behavior.
  115003. */
  115004. get: function () {
  115005. return "Framing";
  115006. },
  115007. enumerable: true,
  115008. configurable: true
  115009. });
  115010. Object.defineProperty(FramingBehavior.prototype, "mode", {
  115011. /**
  115012. * Gets current mode used by the behavior.
  115013. */
  115014. get: function () {
  115015. return this._mode;
  115016. },
  115017. /**
  115018. * Sets the current mode used by the behavior
  115019. */
  115020. set: function (mode) {
  115021. this._mode = mode;
  115022. },
  115023. enumerable: true,
  115024. configurable: true
  115025. });
  115026. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  115027. /**
  115028. * Gets the scale applied to the radius
  115029. */
  115030. get: function () {
  115031. return this._radiusScale;
  115032. },
  115033. /**
  115034. * Sets the scale applied to the radius (1 by default)
  115035. */
  115036. set: function (radius) {
  115037. this._radiusScale = radius;
  115038. },
  115039. enumerable: true,
  115040. configurable: true
  115041. });
  115042. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  115043. /**
  115044. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  115045. */
  115046. get: function () {
  115047. return this._positionScale;
  115048. },
  115049. /**
  115050. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  115051. */
  115052. set: function (scale) {
  115053. this._positionScale = scale;
  115054. },
  115055. enumerable: true,
  115056. configurable: true
  115057. });
  115058. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  115059. /**
  115060. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  115061. * behaviour is triggered, in radians.
  115062. */
  115063. get: function () {
  115064. return this._defaultElevation;
  115065. },
  115066. /**
  115067. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  115068. * behaviour is triggered, in radians.
  115069. */
  115070. set: function (elevation) {
  115071. this._defaultElevation = elevation;
  115072. },
  115073. enumerable: true,
  115074. configurable: true
  115075. });
  115076. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  115077. /**
  115078. * Gets the time (in milliseconds) taken to return to the default beta position.
  115079. * Negative value indicates camera should not return to default.
  115080. */
  115081. get: function () {
  115082. return this._elevationReturnTime;
  115083. },
  115084. /**
  115085. * Sets the time (in milliseconds) taken to return to the default beta position.
  115086. * Negative value indicates camera should not return to default.
  115087. */
  115088. set: function (speed) {
  115089. this._elevationReturnTime = speed;
  115090. },
  115091. enumerable: true,
  115092. configurable: true
  115093. });
  115094. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  115095. /**
  115096. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  115097. */
  115098. get: function () {
  115099. return this._elevationReturnWaitTime;
  115100. },
  115101. /**
  115102. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  115103. */
  115104. set: function (time) {
  115105. this._elevationReturnWaitTime = time;
  115106. },
  115107. enumerable: true,
  115108. configurable: true
  115109. });
  115110. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  115111. /**
  115112. * Gets the flag that indicates if user zooming should stop animation.
  115113. */
  115114. get: function () {
  115115. return this._zoomStopsAnimation;
  115116. },
  115117. /**
  115118. * Sets the flag that indicates if user zooming should stop animation.
  115119. */
  115120. set: function (flag) {
  115121. this._zoomStopsAnimation = flag;
  115122. },
  115123. enumerable: true,
  115124. configurable: true
  115125. });
  115126. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  115127. /**
  115128. * Gets the transition time when framing the mesh, in milliseconds
  115129. */
  115130. get: function () {
  115131. return this._framingTime;
  115132. },
  115133. /**
  115134. * Sets the transition time when framing the mesh, in milliseconds
  115135. */
  115136. set: function (time) {
  115137. this._framingTime = time;
  115138. },
  115139. enumerable: true,
  115140. configurable: true
  115141. });
  115142. /**
  115143. * Initializes the behavior.
  115144. */
  115145. FramingBehavior.prototype.init = function () {
  115146. // Do notihng
  115147. };
  115148. /**
  115149. * Attaches the behavior to its arc rotate camera.
  115150. * @param camera Defines the camera to attach the behavior to
  115151. */
  115152. FramingBehavior.prototype.attach = function (camera) {
  115153. var _this = this;
  115154. this._attachedCamera = camera;
  115155. var scene = this._attachedCamera.getScene();
  115156. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  115157. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  115158. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  115159. _this._isPointerDown = true;
  115160. return;
  115161. }
  115162. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  115163. _this._isPointerDown = false;
  115164. }
  115165. });
  115166. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  115167. if (mesh) {
  115168. _this.zoomOnMesh(mesh);
  115169. }
  115170. });
  115171. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  115172. // Stop the animation if there is user interaction and the animation should stop for this interaction
  115173. _this._applyUserInteraction();
  115174. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  115175. // back to the default position after a given timeout
  115176. _this._maintainCameraAboveGround();
  115177. });
  115178. };
  115179. /**
  115180. * Detaches the behavior from its current arc rotate camera.
  115181. */
  115182. FramingBehavior.prototype.detach = function () {
  115183. if (!this._attachedCamera) {
  115184. return;
  115185. }
  115186. var scene = this._attachedCamera.getScene();
  115187. if (this._onPrePointerObservableObserver) {
  115188. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  115189. }
  115190. if (this._onAfterCheckInputsObserver) {
  115191. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  115192. }
  115193. if (this._onMeshTargetChangedObserver) {
  115194. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  115195. }
  115196. this._attachedCamera = null;
  115197. };
  115198. /**
  115199. * Targets the given mesh and updates zoom level accordingly.
  115200. * @param mesh The mesh to target.
  115201. * @param radius Optional. If a cached radius position already exists, overrides default.
  115202. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  115203. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  115204. * @param onAnimationEnd Callback triggered at the end of the framing animation
  115205. */
  115206. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  115207. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  115208. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  115209. mesh.computeWorldMatrix(true);
  115210. var boundingBox = mesh.getBoundingInfo().boundingBox;
  115211. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  115212. };
  115213. /**
  115214. * Targets the given mesh with its children and updates zoom level accordingly.
  115215. * @param mesh The mesh to target.
  115216. * @param radius Optional. If a cached radius position already exists, overrides default.
  115217. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  115218. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  115219. * @param onAnimationEnd Callback triggered at the end of the framing animation
  115220. */
  115221. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  115222. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  115223. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  115224. mesh.computeWorldMatrix(true);
  115225. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  115226. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  115227. };
  115228. /**
  115229. * Targets the given meshes with their children and updates zoom level accordingly.
  115230. * @param meshes The mesh to target.
  115231. * @param radius Optional. If a cached radius position already exists, overrides default.
  115232. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  115233. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  115234. * @param onAnimationEnd Callback triggered at the end of the framing animation
  115235. */
  115236. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  115237. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  115238. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  115239. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  115240. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  115241. for (var i = 0; i < meshes.length; i++) {
  115242. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  115243. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  115244. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  115245. }
  115246. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  115247. };
  115248. /**
  115249. * Targets the bounding box info defined by its extends and updates zoom level accordingly.
  115250. * @param minimumWorld Determines the smaller position of the bounding box extend
  115251. * @param maximumWorld Determines the bigger position of the bounding box extend
  115252. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  115253. * @param onAnimationEnd Callback triggered at the end of the framing animation
  115254. */
  115255. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  115256. var _this = this;
  115257. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  115258. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  115259. var zoomTarget;
  115260. if (!this._attachedCamera) {
  115261. return;
  115262. }
  115263. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  115264. var bottom = minimumWorld.y;
  115265. var top = maximumWorld.y;
  115266. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  115267. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  115268. if (focusOnOriginXZ) {
  115269. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  115270. }
  115271. else {
  115272. var centerWorld = minimumWorld.add(radiusWorld);
  115273. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  115274. }
  115275. if (!this._vectorTransition) {
  115276. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  115277. }
  115278. this._betaIsAnimating = true;
  115279. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  115280. if (animatable) {
  115281. this._animatables.push(animatable);
  115282. }
  115283. // sets the radius and lower radius bounds
  115284. // Small delta ensures camera is not always at lower zoom limit.
  115285. var radius = 0;
  115286. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  115287. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  115288. if (this.autoCorrectCameraLimitsAndSensibility) {
  115289. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  115290. }
  115291. radius = position;
  115292. }
  115293. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  115294. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  115295. if (this.autoCorrectCameraLimitsAndSensibility && this._attachedCamera.lowerRadiusLimit === null) {
  115296. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  115297. }
  115298. }
  115299. // Set sensibilities
  115300. if (this.autoCorrectCameraLimitsAndSensibility) {
  115301. var extend = maximumWorld.subtract(minimumWorld).length();
  115302. this._attachedCamera.panningSensibility = 5000 / extend;
  115303. this._attachedCamera.wheelPrecision = 100 / radius;
  115304. }
  115305. // transition to new radius
  115306. if (!this._radiusTransition) {
  115307. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  115308. }
  115309. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  115310. _this.stopAllAnimations();
  115311. if (onAnimationEnd) {
  115312. onAnimationEnd();
  115313. }
  115314. if (_this._attachedCamera && _this._attachedCamera.useInputToRestoreState) {
  115315. _this._attachedCamera.storeState();
  115316. }
  115317. });
  115318. if (animatable) {
  115319. this._animatables.push(animatable);
  115320. }
  115321. };
  115322. /**
  115323. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  115324. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  115325. * frustum width.
  115326. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  115327. * to fully enclose the mesh in the viewing frustum.
  115328. */
  115329. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  115330. var size = maximumWorld.subtract(minimumWorld);
  115331. var boxVectorGlobalDiagonal = size.length();
  115332. var frustumSlope = this._getFrustumSlope();
  115333. // Formula for setting distance
  115334. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  115335. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  115336. // Horizon distance
  115337. var radius = radiusWithoutFraming * this._radiusScale;
  115338. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  115339. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  115340. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  115341. var camera = this._attachedCamera;
  115342. if (!camera) {
  115343. return 0;
  115344. }
  115345. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  115346. // Don't exceed the requested limit
  115347. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  115348. }
  115349. // Don't exceed the upper radius limit
  115350. if (camera.upperRadiusLimit) {
  115351. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  115352. }
  115353. return distance;
  115354. };
  115355. /**
  115356. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  115357. * is automatically returned to its default position (expected to be above ground plane).
  115358. */
  115359. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  115360. var _this = this;
  115361. if (this._elevationReturnTime < 0) {
  115362. return;
  115363. }
  115364. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  115365. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  115366. var limitBeta = Math.PI * 0.5;
  115367. // Bring the camera back up if below the ground plane
  115368. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  115369. this._betaIsAnimating = true;
  115370. //Transition to new position
  115371. this.stopAllAnimations();
  115372. if (!this._betaTransition) {
  115373. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  115374. }
  115375. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  115376. _this._clearAnimationLocks();
  115377. _this.stopAllAnimations();
  115378. });
  115379. if (animatabe) {
  115380. this._animatables.push(animatabe);
  115381. }
  115382. }
  115383. };
  115384. /**
  115385. * Returns the frustum slope based on the canvas ratio and camera FOV
  115386. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  115387. */
  115388. FramingBehavior.prototype._getFrustumSlope = function () {
  115389. // Calculate the viewport ratio
  115390. // Aspect Ratio is Height/Width.
  115391. var camera = this._attachedCamera;
  115392. if (!camera) {
  115393. return BABYLON.Vector2.Zero();
  115394. }
  115395. var engine = camera.getScene().getEngine();
  115396. var aspectRatio = engine.getAspectRatio(camera);
  115397. // Camera FOV is the vertical field of view (top-bottom) in radians.
  115398. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  115399. var frustumSlopeY = Math.tan(camera.fov / 2);
  115400. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  115401. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  115402. // along the forward vector.
  115403. var frustumSlopeX = frustumSlopeY * aspectRatio;
  115404. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  115405. };
  115406. /**
  115407. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  115408. */
  115409. FramingBehavior.prototype._clearAnimationLocks = function () {
  115410. this._betaIsAnimating = false;
  115411. };
  115412. /**
  115413. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  115414. */
  115415. FramingBehavior.prototype._applyUserInteraction = function () {
  115416. if (this.isUserIsMoving) {
  115417. this._lastInteractionTime = BABYLON.Tools.Now;
  115418. this.stopAllAnimations();
  115419. this._clearAnimationLocks();
  115420. }
  115421. };
  115422. /**
  115423. * Stops and removes all animations that have been applied to the camera
  115424. */
  115425. FramingBehavior.prototype.stopAllAnimations = function () {
  115426. if (this._attachedCamera) {
  115427. this._attachedCamera.animations = [];
  115428. }
  115429. while (this._animatables.length) {
  115430. if (this._animatables[0]) {
  115431. this._animatables[0].onAnimationEnd = null;
  115432. this._animatables[0].stop();
  115433. }
  115434. this._animatables.shift();
  115435. }
  115436. };
  115437. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  115438. /**
  115439. * Gets a value indicating if the user is moving the camera
  115440. */
  115441. get: function () {
  115442. if (!this._attachedCamera) {
  115443. return false;
  115444. }
  115445. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  115446. this._attachedCamera.inertialBetaOffset !== 0 ||
  115447. this._attachedCamera.inertialRadiusOffset !== 0 ||
  115448. this._attachedCamera.inertialPanningX !== 0 ||
  115449. this._attachedCamera.inertialPanningY !== 0 ||
  115450. this._isPointerDown;
  115451. },
  115452. enumerable: true,
  115453. configurable: true
  115454. });
  115455. /**
  115456. * The easing function used by animations
  115457. */
  115458. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  115459. /**
  115460. * The easing mode used by animations
  115461. */
  115462. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  115463. // Statics
  115464. /**
  115465. * The camera can move all the way towards the mesh.
  115466. */
  115467. FramingBehavior.IgnoreBoundsSizeMode = 0;
  115468. /**
  115469. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  115470. */
  115471. FramingBehavior.FitFrustumSidesMode = 1;
  115472. return FramingBehavior;
  115473. }());
  115474. BABYLON.FramingBehavior = FramingBehavior;
  115475. })(BABYLON || (BABYLON = {}));
  115476. //# sourceMappingURL=babylon.framingBehavior.js.map
  115477. var BABYLON;
  115478. (function (BABYLON) {
  115479. /**
  115480. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  115481. * @see http://doc.babylonjs.com/how_to/camera_behaviors#bouncing-behavior
  115482. */
  115483. var BouncingBehavior = /** @class */ (function () {
  115484. function BouncingBehavior() {
  115485. /**
  115486. * The duration of the animation, in milliseconds
  115487. */
  115488. this.transitionDuration = 450;
  115489. /**
  115490. * Length of the distance animated by the transition when lower radius is reached
  115491. */
  115492. this.lowerRadiusTransitionRange = 2;
  115493. /**
  115494. * Length of the distance animated by the transition when upper radius is reached
  115495. */
  115496. this.upperRadiusTransitionRange = -2;
  115497. this._autoTransitionRange = false;
  115498. // Animations
  115499. this._radiusIsAnimating = false;
  115500. this._radiusBounceTransition = null;
  115501. this._animatables = new Array();
  115502. }
  115503. Object.defineProperty(BouncingBehavior.prototype, "name", {
  115504. /**
  115505. * Gets the name of the behavior.
  115506. */
  115507. get: function () {
  115508. return "Bouncing";
  115509. },
  115510. enumerable: true,
  115511. configurable: true
  115512. });
  115513. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  115514. /**
  115515. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  115516. */
  115517. get: function () {
  115518. return this._autoTransitionRange;
  115519. },
  115520. /**
  115521. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  115522. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  115523. */
  115524. set: function (value) {
  115525. var _this = this;
  115526. if (this._autoTransitionRange === value) {
  115527. return;
  115528. }
  115529. this._autoTransitionRange = value;
  115530. var camera = this._attachedCamera;
  115531. if (!camera) {
  115532. return;
  115533. }
  115534. if (value) {
  115535. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  115536. if (!mesh) {
  115537. return;
  115538. }
  115539. mesh.computeWorldMatrix(true);
  115540. var diagonal = mesh.getBoundingInfo().diagonalLength;
  115541. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  115542. _this.upperRadiusTransitionRange = diagonal * 0.05;
  115543. });
  115544. }
  115545. else if (this._onMeshTargetChangedObserver) {
  115546. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  115547. }
  115548. },
  115549. enumerable: true,
  115550. configurable: true
  115551. });
  115552. /**
  115553. * Initializes the behavior.
  115554. */
  115555. BouncingBehavior.prototype.init = function () {
  115556. // Do notihng
  115557. };
  115558. /**
  115559. * Attaches the behavior to its arc rotate camera.
  115560. * @param camera Defines the camera to attach the behavior to
  115561. */
  115562. BouncingBehavior.prototype.attach = function (camera) {
  115563. var _this = this;
  115564. this._attachedCamera = camera;
  115565. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  115566. if (!_this._attachedCamera) {
  115567. return;
  115568. }
  115569. // Add the bounce animation to the lower radius limit
  115570. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  115571. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  115572. }
  115573. // Add the bounce animation to the upper radius limit
  115574. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  115575. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  115576. }
  115577. });
  115578. };
  115579. /**
  115580. * Detaches the behavior from its current arc rotate camera.
  115581. */
  115582. BouncingBehavior.prototype.detach = function () {
  115583. if (!this._attachedCamera) {
  115584. return;
  115585. }
  115586. if (this._onAfterCheckInputsObserver) {
  115587. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  115588. }
  115589. if (this._onMeshTargetChangedObserver) {
  115590. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  115591. }
  115592. this._attachedCamera = null;
  115593. };
  115594. /**
  115595. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  115596. * @param radiusLimit The limit to check against.
  115597. * @return Bool to indicate if at limit.
  115598. */
  115599. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  115600. if (!this._attachedCamera) {
  115601. return false;
  115602. }
  115603. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  115604. return true;
  115605. }
  115606. return false;
  115607. };
  115608. /**
  115609. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  115610. * @param radiusDelta The delta by which to animate to. Can be negative.
  115611. */
  115612. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  115613. var _this = this;
  115614. if (!this._attachedCamera) {
  115615. return;
  115616. }
  115617. if (!this._radiusBounceTransition) {
  115618. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  115619. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  115620. }
  115621. // Prevent zoom until bounce has completed
  115622. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  115623. this._attachedCamera.wheelPrecision = Infinity;
  115624. this._attachedCamera.inertialRadiusOffset = 0;
  115625. // Animate to the radius limit
  115626. this.stopAllAnimations();
  115627. this._radiusIsAnimating = true;
  115628. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  115629. if (animatable) {
  115630. this._animatables.push(animatable);
  115631. }
  115632. };
  115633. /**
  115634. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  115635. */
  115636. BouncingBehavior.prototype._clearAnimationLocks = function () {
  115637. this._radiusIsAnimating = false;
  115638. if (this._attachedCamera) {
  115639. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  115640. }
  115641. };
  115642. /**
  115643. * Stops and removes all animations that have been applied to the camera
  115644. */
  115645. BouncingBehavior.prototype.stopAllAnimations = function () {
  115646. if (this._attachedCamera) {
  115647. this._attachedCamera.animations = [];
  115648. }
  115649. while (this._animatables.length) {
  115650. this._animatables[0].onAnimationEnd = null;
  115651. this._animatables[0].stop();
  115652. this._animatables.shift();
  115653. }
  115654. };
  115655. /**
  115656. * The easing function used by animations
  115657. */
  115658. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  115659. /**
  115660. * The easing mode used by animations
  115661. */
  115662. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  115663. return BouncingBehavior;
  115664. }());
  115665. BABYLON.BouncingBehavior = BouncingBehavior;
  115666. })(BABYLON || (BABYLON = {}));
  115667. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  115668. var BABYLON;
  115669. (function (BABYLON) {
  115670. /**
  115671. * The autoRotation behavior (BABYLON.AutoRotationBehavior) is designed to create a smooth rotation of an ArcRotateCamera when there is no user interaction.
  115672. * @see http://doc.babylonjs.com/how_to/camera_behaviors#autorotation-behavior
  115673. */
  115674. var AutoRotationBehavior = /** @class */ (function () {
  115675. function AutoRotationBehavior() {
  115676. this._zoomStopsAnimation = false;
  115677. this._idleRotationSpeed = 0.05;
  115678. this._idleRotationWaitTime = 2000;
  115679. this._idleRotationSpinupTime = 2000;
  115680. this._isPointerDown = false;
  115681. this._lastFrameTime = null;
  115682. this._lastInteractionTime = -Infinity;
  115683. this._cameraRotationSpeed = 0;
  115684. this._lastFrameRadius = 0;
  115685. }
  115686. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  115687. /**
  115688. * Gets the name of the behavior.
  115689. */
  115690. get: function () {
  115691. return "AutoRotation";
  115692. },
  115693. enumerable: true,
  115694. configurable: true
  115695. });
  115696. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  115697. /**
  115698. * Gets the flag that indicates if user zooming should stop animation.
  115699. */
  115700. get: function () {
  115701. return this._zoomStopsAnimation;
  115702. },
  115703. /**
  115704. * Sets the flag that indicates if user zooming should stop animation.
  115705. */
  115706. set: function (flag) {
  115707. this._zoomStopsAnimation = flag;
  115708. },
  115709. enumerable: true,
  115710. configurable: true
  115711. });
  115712. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  115713. /**
  115714. * Gets the default speed at which the camera rotates around the model.
  115715. */
  115716. get: function () {
  115717. return this._idleRotationSpeed;
  115718. },
  115719. /**
  115720. * Sets the default speed at which the camera rotates around the model.
  115721. */
  115722. set: function (speed) {
  115723. this._idleRotationSpeed = speed;
  115724. },
  115725. enumerable: true,
  115726. configurable: true
  115727. });
  115728. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  115729. /**
  115730. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  115731. */
  115732. get: function () {
  115733. return this._idleRotationWaitTime;
  115734. },
  115735. /**
  115736. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  115737. */
  115738. set: function (time) {
  115739. this._idleRotationWaitTime = time;
  115740. },
  115741. enumerable: true,
  115742. configurable: true
  115743. });
  115744. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  115745. /**
  115746. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  115747. */
  115748. get: function () {
  115749. return this._idleRotationSpinupTime;
  115750. },
  115751. /**
  115752. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  115753. */
  115754. set: function (time) {
  115755. this._idleRotationSpinupTime = time;
  115756. },
  115757. enumerable: true,
  115758. configurable: true
  115759. });
  115760. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  115761. /**
  115762. * Gets a value indicating if the camera is currently rotating because of this behavior
  115763. */
  115764. get: function () {
  115765. return Math.abs(this._cameraRotationSpeed) > 0;
  115766. },
  115767. enumerable: true,
  115768. configurable: true
  115769. });
  115770. /**
  115771. * Initializes the behavior.
  115772. */
  115773. AutoRotationBehavior.prototype.init = function () {
  115774. // Do notihng
  115775. };
  115776. /**
  115777. * Attaches the behavior to its arc rotate camera.
  115778. * @param camera Defines the camera to attach the behavior to
  115779. */
  115780. AutoRotationBehavior.prototype.attach = function (camera) {
  115781. var _this = this;
  115782. this._attachedCamera = camera;
  115783. var scene = this._attachedCamera.getScene();
  115784. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  115785. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  115786. _this._isPointerDown = true;
  115787. return;
  115788. }
  115789. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  115790. _this._isPointerDown = false;
  115791. }
  115792. });
  115793. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  115794. var now = BABYLON.Tools.Now;
  115795. var dt = 0;
  115796. if (_this._lastFrameTime != null) {
  115797. dt = now - _this._lastFrameTime;
  115798. }
  115799. _this._lastFrameTime = now;
  115800. // Stop the animation if there is user interaction and the animation should stop for this interaction
  115801. _this._applyUserInteraction();
  115802. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  115803. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  115804. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  115805. // Step camera rotation by rotation speed
  115806. if (_this._attachedCamera) {
  115807. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  115808. }
  115809. });
  115810. };
  115811. /**
  115812. * Detaches the behavior from its current arc rotate camera.
  115813. */
  115814. AutoRotationBehavior.prototype.detach = function () {
  115815. if (!this._attachedCamera) {
  115816. return;
  115817. }
  115818. var scene = this._attachedCamera.getScene();
  115819. if (this._onPrePointerObservableObserver) {
  115820. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  115821. }
  115822. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  115823. this._attachedCamera = null;
  115824. };
  115825. /**
  115826. * Returns true if user is scrolling.
  115827. * @return true if user is scrolling.
  115828. */
  115829. AutoRotationBehavior.prototype._userIsZooming = function () {
  115830. if (!this._attachedCamera) {
  115831. return false;
  115832. }
  115833. return this._attachedCamera.inertialRadiusOffset !== 0;
  115834. };
  115835. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  115836. if (!this._attachedCamera) {
  115837. return false;
  115838. }
  115839. var zoomHasHitLimit = false;
  115840. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  115841. zoomHasHitLimit = true;
  115842. }
  115843. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  115844. this._lastFrameRadius = this._attachedCamera.radius;
  115845. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  115846. };
  115847. /**
  115848. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  115849. */
  115850. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  115851. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  115852. this._lastInteractionTime = BABYLON.Tools.Now;
  115853. }
  115854. };
  115855. // Tools
  115856. AutoRotationBehavior.prototype._userIsMoving = function () {
  115857. if (!this._attachedCamera) {
  115858. return false;
  115859. }
  115860. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  115861. this._attachedCamera.inertialBetaOffset !== 0 ||
  115862. this._attachedCamera.inertialRadiusOffset !== 0 ||
  115863. this._attachedCamera.inertialPanningX !== 0 ||
  115864. this._attachedCamera.inertialPanningY !== 0 ||
  115865. this._isPointerDown;
  115866. };
  115867. return AutoRotationBehavior;
  115868. }());
  115869. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  115870. })(BABYLON || (BABYLON = {}));
  115871. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  115872. var BABYLON;
  115873. (function (BABYLON) {
  115874. /**
  115875. * Options to create the null engine
  115876. */
  115877. var NullEngineOptions = /** @class */ (function () {
  115878. function NullEngineOptions() {
  115879. /**
  115880. * Render width (Default: 512)
  115881. */
  115882. this.renderWidth = 512;
  115883. /**
  115884. * Render height (Default: 256)
  115885. */
  115886. this.renderHeight = 256;
  115887. /**
  115888. * Texture size (Default: 512)
  115889. */
  115890. this.textureSize = 512;
  115891. /**
  115892. * If delta time between frames should be constant
  115893. * @see https://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  115894. */
  115895. this.deterministicLockstep = false;
  115896. /**
  115897. * Maximum about of steps between frames (Default: 4)
  115898. * @see https://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  115899. */
  115900. this.lockstepMaxSteps = 4;
  115901. }
  115902. return NullEngineOptions;
  115903. }());
  115904. BABYLON.NullEngineOptions = NullEngineOptions;
  115905. /**
  115906. * The null engine class provides support for headless version of babylon.js.
  115907. * This can be used in server side scenario or for testing purposes
  115908. */
  115909. var NullEngine = /** @class */ (function (_super) {
  115910. __extends(NullEngine, _super);
  115911. function NullEngine(options) {
  115912. if (options === void 0) { options = new NullEngineOptions(); }
  115913. var _this = _super.call(this, null) || this;
  115914. if (options.deterministicLockstep === undefined) {
  115915. options.deterministicLockstep = false;
  115916. }
  115917. if (options.lockstepMaxSteps === undefined) {
  115918. options.lockstepMaxSteps = 4;
  115919. }
  115920. _this._options = options;
  115921. // Init caps
  115922. // We consider we are on a webgl1 capable device
  115923. _this._caps = new BABYLON.EngineCapabilities();
  115924. _this._caps.maxTexturesImageUnits = 16;
  115925. _this._caps.maxVertexTextureImageUnits = 16;
  115926. _this._caps.maxTextureSize = 512;
  115927. _this._caps.maxCubemapTextureSize = 512;
  115928. _this._caps.maxRenderTextureSize = 512;
  115929. _this._caps.maxVertexAttribs = 16;
  115930. _this._caps.maxVaryingVectors = 16;
  115931. _this._caps.maxFragmentUniformVectors = 16;
  115932. _this._caps.maxVertexUniformVectors = 16;
  115933. // Extensions
  115934. _this._caps.standardDerivatives = false;
  115935. _this._caps.astc = null;
  115936. _this._caps.s3tc = null;
  115937. _this._caps.pvrtc = null;
  115938. _this._caps.etc1 = null;
  115939. _this._caps.etc2 = null;
  115940. _this._caps.textureAnisotropicFilterExtension = null;
  115941. _this._caps.maxAnisotropy = 0;
  115942. _this._caps.uintIndices = false;
  115943. _this._caps.fragmentDepthSupported = false;
  115944. _this._caps.highPrecisionShaderSupported = true;
  115945. _this._caps.colorBufferFloat = false;
  115946. _this._caps.textureFloat = false;
  115947. _this._caps.textureFloatLinearFiltering = false;
  115948. _this._caps.textureFloatRender = false;
  115949. _this._caps.textureHalfFloat = false;
  115950. _this._caps.textureHalfFloatLinearFiltering = false;
  115951. _this._caps.textureHalfFloatRender = false;
  115952. _this._caps.textureLOD = false;
  115953. _this._caps.drawBuffersExtension = false;
  115954. _this._caps.depthTextureExtension = false;
  115955. _this._caps.vertexArrayObject = false;
  115956. _this._caps.instancedArrays = false;
  115957. BABYLON.Tools.Log("Babylon.js v" + BABYLON.Engine.Version + " - Null engine");
  115958. // Wrappers
  115959. if (typeof URL === "undefined") {
  115960. URL = {
  115961. createObjectURL: function () { },
  115962. revokeObjectURL: function () { }
  115963. };
  115964. }
  115965. if (typeof Blob === "undefined") {
  115966. Blob = function () { };
  115967. }
  115968. return _this;
  115969. }
  115970. /**
  115971. * @see https://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  115972. */
  115973. NullEngine.prototype.isDeterministicLockStep = function () {
  115974. return this._options.deterministicLockstep;
  115975. };
  115976. /** @see https://doc.babylonjs.com/babylon101/animations#deterministic-lockstep */
  115977. NullEngine.prototype.getLockstepMaxSteps = function () {
  115978. return this._options.lockstepMaxSteps;
  115979. };
  115980. /**
  115981. * Sets hardware scaling, used to save performance if needed
  115982. * @see https://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  115983. */
  115984. NullEngine.prototype.getHardwareScalingLevel = function () {
  115985. return 1.0;
  115986. };
  115987. NullEngine.prototype.createVertexBuffer = function (vertices) {
  115988. return {
  115989. capacity: 0,
  115990. references: 1,
  115991. is32Bits: false
  115992. };
  115993. };
  115994. NullEngine.prototype.createIndexBuffer = function (indices) {
  115995. return {
  115996. capacity: 0,
  115997. references: 1,
  115998. is32Bits: false
  115999. };
  116000. };
  116001. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  116002. if (stencil === void 0) { stencil = false; }
  116003. };
  116004. NullEngine.prototype.getRenderWidth = function (useScreen) {
  116005. if (useScreen === void 0) { useScreen = false; }
  116006. if (!useScreen && this._currentRenderTarget) {
  116007. return this._currentRenderTarget.width;
  116008. }
  116009. return this._options.renderWidth;
  116010. };
  116011. NullEngine.prototype.getRenderHeight = function (useScreen) {
  116012. if (useScreen === void 0) { useScreen = false; }
  116013. if (!useScreen && this._currentRenderTarget) {
  116014. return this._currentRenderTarget.height;
  116015. }
  116016. return this._options.renderHeight;
  116017. };
  116018. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  116019. this._cachedViewport = viewport;
  116020. };
  116021. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  116022. return {
  116023. transformFeedback: null,
  116024. __SPECTOR_rebuildProgram: null,
  116025. isParallelCompiled: false
  116026. };
  116027. };
  116028. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  116029. return [];
  116030. };
  116031. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  116032. return [];
  116033. };
  116034. NullEngine.prototype.bindSamplers = function (effect) {
  116035. this._currentEffect = null;
  116036. };
  116037. NullEngine.prototype.enableEffect = function (effect) {
  116038. this._currentEffect = effect;
  116039. if (effect.onBind) {
  116040. effect.onBind(effect);
  116041. }
  116042. if (effect._onBindObservable) {
  116043. effect._onBindObservable.notifyObservers(effect);
  116044. }
  116045. };
  116046. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  116047. if (zOffset === void 0) { zOffset = 0; }
  116048. if (reverseSide === void 0) { reverseSide = false; }
  116049. };
  116050. NullEngine.prototype.setIntArray = function (uniform, array) {
  116051. };
  116052. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  116053. };
  116054. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  116055. };
  116056. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  116057. };
  116058. NullEngine.prototype.setFloatArray = function (uniform, array) {
  116059. };
  116060. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  116061. };
  116062. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  116063. };
  116064. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  116065. };
  116066. NullEngine.prototype.setArray = function (uniform, array) {
  116067. };
  116068. NullEngine.prototype.setArray2 = function (uniform, array) {
  116069. };
  116070. NullEngine.prototype.setArray3 = function (uniform, array) {
  116071. };
  116072. NullEngine.prototype.setArray4 = function (uniform, array) {
  116073. };
  116074. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  116075. };
  116076. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  116077. };
  116078. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  116079. };
  116080. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  116081. };
  116082. NullEngine.prototype.setFloat = function (uniform, value) {
  116083. };
  116084. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  116085. };
  116086. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  116087. };
  116088. NullEngine.prototype.setBool = function (uniform, bool) {
  116089. };
  116090. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  116091. };
  116092. NullEngine.prototype.setColor3 = function (uniform, color3) {
  116093. };
  116094. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  116095. };
  116096. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  116097. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  116098. if (this._alphaMode === mode) {
  116099. return;
  116100. }
  116101. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  116102. if (!noDepthWriteChange) {
  116103. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  116104. }
  116105. this._alphaMode = mode;
  116106. };
  116107. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  116108. };
  116109. NullEngine.prototype.wipeCaches = function (bruteForce) {
  116110. if (this.preventCacheWipeBetweenFrames) {
  116111. return;
  116112. }
  116113. this.resetTextureCache();
  116114. this._currentEffect = null;
  116115. if (bruteForce) {
  116116. this._currentProgram = null;
  116117. this._stencilState.reset();
  116118. this._depthCullingState.reset();
  116119. this._alphaState.reset();
  116120. }
  116121. this._cachedVertexBuffers = null;
  116122. this._cachedIndexBuffer = null;
  116123. this._cachedEffectForVertexBuffers = null;
  116124. };
  116125. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  116126. };
  116127. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  116128. };
  116129. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  116130. };
  116131. /** @hidden */
  116132. NullEngine.prototype._createTexture = function () {
  116133. return {};
  116134. };
  116135. /** @hidden */
  116136. NullEngine.prototype._releaseTexture = function (texture) {
  116137. };
  116138. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  116139. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  116140. if (onLoad === void 0) { onLoad = null; }
  116141. if (onError === void 0) { onError = null; }
  116142. if (buffer === void 0) { buffer = null; }
  116143. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  116144. var url = String(urlArg);
  116145. texture.url = url;
  116146. texture.generateMipMaps = !noMipmap;
  116147. texture.samplingMode = samplingMode;
  116148. texture.invertY = invertY;
  116149. texture.baseWidth = this._options.textureSize;
  116150. texture.baseHeight = this._options.textureSize;
  116151. texture.width = this._options.textureSize;
  116152. texture.height = this._options.textureSize;
  116153. if (format) {
  116154. texture.format = format;
  116155. }
  116156. texture.isReady = true;
  116157. if (onLoad) {
  116158. onLoad();
  116159. }
  116160. this._internalTexturesCache.push(texture);
  116161. return texture;
  116162. };
  116163. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  116164. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  116165. if (options !== undefined && typeof options === "object") {
  116166. fullOptions.generateMipMaps = options.generateMipMaps;
  116167. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  116168. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  116169. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  116170. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  116171. }
  116172. else {
  116173. fullOptions.generateMipMaps = options;
  116174. fullOptions.generateDepthBuffer = true;
  116175. fullOptions.generateStencilBuffer = false;
  116176. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  116177. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  116178. }
  116179. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  116180. var width = size.width || size;
  116181. var height = size.height || size;
  116182. texture._depthStencilBuffer = {};
  116183. texture._framebuffer = {};
  116184. texture.baseWidth = width;
  116185. texture.baseHeight = height;
  116186. texture.width = width;
  116187. texture.height = height;
  116188. texture.isReady = true;
  116189. texture.samples = 1;
  116190. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  116191. texture.samplingMode = fullOptions.samplingMode;
  116192. texture.type = fullOptions.type;
  116193. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  116194. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  116195. this._internalTexturesCache.push(texture);
  116196. return texture;
  116197. };
  116198. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  116199. texture.samplingMode = samplingMode;
  116200. };
  116201. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  116202. if (this._currentRenderTarget) {
  116203. this.unBindFramebuffer(this._currentRenderTarget);
  116204. }
  116205. this._currentRenderTarget = texture;
  116206. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  116207. if (this._cachedViewport && !forceFullscreenViewport) {
  116208. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  116209. }
  116210. };
  116211. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  116212. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  116213. this._currentRenderTarget = null;
  116214. if (onBeforeUnbind) {
  116215. if (texture._MSAAFramebuffer) {
  116216. this._currentFramebuffer = texture._framebuffer;
  116217. }
  116218. onBeforeUnbind();
  116219. }
  116220. this._currentFramebuffer = null;
  116221. };
  116222. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  116223. var vbo = {
  116224. capacity: 1,
  116225. references: 1,
  116226. is32Bits: false
  116227. };
  116228. return vbo;
  116229. };
  116230. NullEngine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  116231. if (premulAlpha === void 0) { premulAlpha = false; }
  116232. };
  116233. NullEngine.prototype.areAllEffectsReady = function () {
  116234. return true;
  116235. };
  116236. /**
  116237. * @hidden
  116238. * Get the current error code of the webGL context
  116239. * @returns the error code
  116240. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  116241. */
  116242. NullEngine.prototype.getError = function () {
  116243. return 0;
  116244. };
  116245. /** @hidden */
  116246. NullEngine.prototype._getUnpackAlignement = function () {
  116247. return 1;
  116248. };
  116249. /** @hidden */
  116250. NullEngine.prototype._unpackFlipY = function (value) {
  116251. };
  116252. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  116253. if (offset === void 0) { offset = 0; }
  116254. };
  116255. /**
  116256. * Updates a dynamic vertex buffer.
  116257. * @param vertexBuffer the vertex buffer to update
  116258. * @param data the data used to update the vertex buffer
  116259. * @param byteOffset the byte offset of the data (optional)
  116260. * @param byteLength the byte length of the data (optional)
  116261. */
  116262. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  116263. };
  116264. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  116265. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  116266. this._boundTexturesCache[this._activeChannel] = texture;
  116267. return true;
  116268. }
  116269. return false;
  116270. };
  116271. /** @hidden */
  116272. NullEngine.prototype._bindTexture = function (channel, texture) {
  116273. if (channel < 0) {
  116274. return;
  116275. }
  116276. this._bindTextureDirectly(0, texture);
  116277. };
  116278. /** @hidden */
  116279. NullEngine.prototype._releaseBuffer = function (buffer) {
  116280. buffer.references--;
  116281. if (buffer.references === 0) {
  116282. return true;
  116283. }
  116284. return false;
  116285. };
  116286. NullEngine.prototype.releaseEffects = function () {
  116287. };
  116288. NullEngine.prototype.displayLoadingUI = function () {
  116289. };
  116290. NullEngine.prototype.hideLoadingUI = function () {
  116291. };
  116292. /** @hidden */
  116293. NullEngine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
  116294. if (faceIndex === void 0) { faceIndex = 0; }
  116295. if (lod === void 0) { lod = 0; }
  116296. };
  116297. /** @hidden */
  116298. NullEngine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {
  116299. if (faceIndex === void 0) { faceIndex = 0; }
  116300. if (lod === void 0) { lod = 0; }
  116301. };
  116302. /** @hidden */
  116303. NullEngine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
  116304. if (faceIndex === void 0) { faceIndex = 0; }
  116305. if (lod === void 0) { lod = 0; }
  116306. };
  116307. /** @hidden */
  116308. NullEngine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
  116309. if (faceIndex === void 0) { faceIndex = 0; }
  116310. if (lod === void 0) { lod = 0; }
  116311. };
  116312. return NullEngine;
  116313. }(BABYLON.Engine));
  116314. BABYLON.NullEngine = NullEngine;
  116315. })(BABYLON || (BABYLON = {}));
  116316. //# sourceMappingURL=babylon.nullEngine.js.map
  116317. var BABYLON;
  116318. (function (BABYLON) {
  116319. /**
  116320. * This class can be used to get instrumentation data from a Babylon engine
  116321. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  116322. */
  116323. var EngineInstrumentation = /** @class */ (function () {
  116324. /**
  116325. * Instantiates a new engine instrumentation.
  116326. * This class can be used to get instrumentation data from a Babylon engine
  116327. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  116328. * @param engine Defines the engine to instrument
  116329. */
  116330. function EngineInstrumentation(
  116331. /**
  116332. * Define the instrumented engine.
  116333. */
  116334. engine) {
  116335. this.engine = engine;
  116336. this._captureGPUFrameTime = false;
  116337. this._gpuFrameTime = new BABYLON.PerfCounter();
  116338. this._captureShaderCompilationTime = false;
  116339. this._shaderCompilationTime = new BABYLON.PerfCounter();
  116340. // Observers
  116341. this._onBeginFrameObserver = null;
  116342. this._onEndFrameObserver = null;
  116343. this._onBeforeShaderCompilationObserver = null;
  116344. this._onAfterShaderCompilationObserver = null;
  116345. }
  116346. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  116347. // Properties
  116348. /**
  116349. * Gets the perf counter used for GPU frame time
  116350. */
  116351. get: function () {
  116352. return this._gpuFrameTime;
  116353. },
  116354. enumerable: true,
  116355. configurable: true
  116356. });
  116357. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  116358. /**
  116359. * Gets the GPU frame time capture status
  116360. */
  116361. get: function () {
  116362. return this._captureGPUFrameTime;
  116363. },
  116364. /**
  116365. * Enable or disable the GPU frame time capture
  116366. */
  116367. set: function (value) {
  116368. var _this = this;
  116369. if (value === this._captureGPUFrameTime) {
  116370. return;
  116371. }
  116372. this._captureGPUFrameTime = value;
  116373. if (value) {
  116374. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  116375. if (!_this._gpuFrameTimeToken) {
  116376. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  116377. }
  116378. });
  116379. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  116380. if (!_this._gpuFrameTimeToken) {
  116381. return;
  116382. }
  116383. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  116384. if (time > -1) {
  116385. _this._gpuFrameTimeToken = null;
  116386. _this._gpuFrameTime.fetchNewFrame();
  116387. _this._gpuFrameTime.addCount(time, true);
  116388. }
  116389. });
  116390. }
  116391. else {
  116392. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  116393. this._onBeginFrameObserver = null;
  116394. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  116395. this._onEndFrameObserver = null;
  116396. }
  116397. },
  116398. enumerable: true,
  116399. configurable: true
  116400. });
  116401. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  116402. /**
  116403. * Gets the perf counter used for shader compilation time
  116404. */
  116405. get: function () {
  116406. return this._shaderCompilationTime;
  116407. },
  116408. enumerable: true,
  116409. configurable: true
  116410. });
  116411. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  116412. /**
  116413. * Gets the shader compilation time capture status
  116414. */
  116415. get: function () {
  116416. return this._captureShaderCompilationTime;
  116417. },
  116418. /**
  116419. * Enable or disable the shader compilation time capture
  116420. */
  116421. set: function (value) {
  116422. var _this = this;
  116423. if (value === this._captureShaderCompilationTime) {
  116424. return;
  116425. }
  116426. this._captureShaderCompilationTime = value;
  116427. if (value) {
  116428. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  116429. _this._shaderCompilationTime.fetchNewFrame();
  116430. _this._shaderCompilationTime.beginMonitoring();
  116431. });
  116432. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  116433. _this._shaderCompilationTime.endMonitoring();
  116434. });
  116435. }
  116436. else {
  116437. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  116438. this._onBeforeShaderCompilationObserver = null;
  116439. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  116440. this._onAfterShaderCompilationObserver = null;
  116441. }
  116442. },
  116443. enumerable: true,
  116444. configurable: true
  116445. });
  116446. /**
  116447. * Dispose and release associated resources.
  116448. */
  116449. EngineInstrumentation.prototype.dispose = function () {
  116450. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  116451. this._onBeginFrameObserver = null;
  116452. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  116453. this._onEndFrameObserver = null;
  116454. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  116455. this._onBeforeShaderCompilationObserver = null;
  116456. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  116457. this._onAfterShaderCompilationObserver = null;
  116458. this.engine = null;
  116459. };
  116460. return EngineInstrumentation;
  116461. }());
  116462. BABYLON.EngineInstrumentation = EngineInstrumentation;
  116463. })(BABYLON || (BABYLON = {}));
  116464. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  116465. var BABYLON;
  116466. (function (BABYLON) {
  116467. /**
  116468. * This class can be used to get instrumentation data from a Babylon engine
  116469. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#sceneinstrumentation
  116470. */
  116471. var SceneInstrumentation = /** @class */ (function () {
  116472. /**
  116473. * Instantiates a new scene instrumentation.
  116474. * This class can be used to get instrumentation data from a Babylon engine
  116475. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#sceneinstrumentation
  116476. * @param scene Defines the scene to instrument
  116477. */
  116478. function SceneInstrumentation(
  116479. /**
  116480. * Defines the scene to instrument
  116481. */
  116482. scene) {
  116483. var _this = this;
  116484. this.scene = scene;
  116485. this._captureActiveMeshesEvaluationTime = false;
  116486. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  116487. this._captureRenderTargetsRenderTime = false;
  116488. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  116489. this._captureFrameTime = false;
  116490. this._frameTime = new BABYLON.PerfCounter();
  116491. this._captureRenderTime = false;
  116492. this._renderTime = new BABYLON.PerfCounter();
  116493. this._captureInterFrameTime = false;
  116494. this._interFrameTime = new BABYLON.PerfCounter();
  116495. this._captureParticlesRenderTime = false;
  116496. this._particlesRenderTime = new BABYLON.PerfCounter();
  116497. this._captureSpritesRenderTime = false;
  116498. this._spritesRenderTime = new BABYLON.PerfCounter();
  116499. this._capturePhysicsTime = false;
  116500. this._physicsTime = new BABYLON.PerfCounter();
  116501. this._captureAnimationsTime = false;
  116502. this._animationsTime = new BABYLON.PerfCounter();
  116503. this._captureCameraRenderTime = false;
  116504. this._cameraRenderTime = new BABYLON.PerfCounter();
  116505. // Observers
  116506. this._onBeforeActiveMeshesEvaluationObserver = null;
  116507. this._onAfterActiveMeshesEvaluationObserver = null;
  116508. this._onBeforeRenderTargetsRenderObserver = null;
  116509. this._onAfterRenderTargetsRenderObserver = null;
  116510. this._onAfterRenderObserver = null;
  116511. this._onBeforeDrawPhaseObserver = null;
  116512. this._onAfterDrawPhaseObserver = null;
  116513. this._onBeforeAnimationsObserver = null;
  116514. this._onBeforeParticlesRenderingObserver = null;
  116515. this._onAfterParticlesRenderingObserver = null;
  116516. this._onBeforeSpritesRenderingObserver = null;
  116517. this._onAfterSpritesRenderingObserver = null;
  116518. this._onBeforePhysicsObserver = null;
  116519. this._onAfterPhysicsObserver = null;
  116520. this._onAfterAnimationsObserver = null;
  116521. this._onBeforeCameraRenderObserver = null;
  116522. this._onAfterCameraRenderObserver = null;
  116523. // Before render
  116524. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  116525. if (_this._captureActiveMeshesEvaluationTime) {
  116526. _this._activeMeshesEvaluationTime.fetchNewFrame();
  116527. }
  116528. if (_this._captureRenderTargetsRenderTime) {
  116529. _this._renderTargetsRenderTime.fetchNewFrame();
  116530. }
  116531. if (_this._captureFrameTime) {
  116532. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  116533. _this._frameTime.beginMonitoring();
  116534. }
  116535. if (_this._captureInterFrameTime) {
  116536. _this._interFrameTime.endMonitoring();
  116537. }
  116538. if (_this._captureParticlesRenderTime) {
  116539. _this._particlesRenderTime.fetchNewFrame();
  116540. }
  116541. if (_this._captureSpritesRenderTime) {
  116542. _this._spritesRenderTime.fetchNewFrame();
  116543. }
  116544. if (_this._captureAnimationsTime) {
  116545. _this._animationsTime.beginMonitoring();
  116546. }
  116547. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  116548. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  116549. });
  116550. // After render
  116551. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  116552. if (_this._captureFrameTime) {
  116553. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  116554. _this._frameTime.endMonitoring();
  116555. }
  116556. if (_this._captureRenderTime) {
  116557. _this._renderTime.endMonitoring(false);
  116558. }
  116559. if (_this._captureInterFrameTime) {
  116560. _this._interFrameTime.beginMonitoring();
  116561. }
  116562. });
  116563. }
  116564. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  116565. // Properties
  116566. /**
  116567. * Gets the perf counter used for active meshes evaluation time
  116568. */
  116569. get: function () {
  116570. return this._activeMeshesEvaluationTime;
  116571. },
  116572. enumerable: true,
  116573. configurable: true
  116574. });
  116575. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  116576. /**
  116577. * Gets the active meshes evaluation time capture status
  116578. */
  116579. get: function () {
  116580. return this._captureActiveMeshesEvaluationTime;
  116581. },
  116582. /**
  116583. * Enable or disable the active meshes evaluation time capture
  116584. */
  116585. set: function (value) {
  116586. var _this = this;
  116587. if (value === this._captureActiveMeshesEvaluationTime) {
  116588. return;
  116589. }
  116590. this._captureActiveMeshesEvaluationTime = value;
  116591. if (value) {
  116592. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  116593. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  116594. _this._activeMeshesEvaluationTime.beginMonitoring();
  116595. });
  116596. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  116597. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  116598. _this._activeMeshesEvaluationTime.endMonitoring();
  116599. });
  116600. }
  116601. else {
  116602. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  116603. this._onBeforeActiveMeshesEvaluationObserver = null;
  116604. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  116605. this._onAfterActiveMeshesEvaluationObserver = null;
  116606. }
  116607. },
  116608. enumerable: true,
  116609. configurable: true
  116610. });
  116611. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  116612. /**
  116613. * Gets the perf counter used for render targets render time
  116614. */
  116615. get: function () {
  116616. return this._renderTargetsRenderTime;
  116617. },
  116618. enumerable: true,
  116619. configurable: true
  116620. });
  116621. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  116622. /**
  116623. * Gets the render targets render time capture status
  116624. */
  116625. get: function () {
  116626. return this._captureRenderTargetsRenderTime;
  116627. },
  116628. /**
  116629. * Enable or disable the render targets render time capture
  116630. */
  116631. set: function (value) {
  116632. var _this = this;
  116633. if (value === this._captureRenderTargetsRenderTime) {
  116634. return;
  116635. }
  116636. this._captureRenderTargetsRenderTime = value;
  116637. if (value) {
  116638. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  116639. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  116640. _this._renderTargetsRenderTime.beginMonitoring();
  116641. });
  116642. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  116643. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  116644. _this._renderTargetsRenderTime.endMonitoring(false);
  116645. });
  116646. }
  116647. else {
  116648. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  116649. this._onBeforeRenderTargetsRenderObserver = null;
  116650. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  116651. this._onAfterRenderTargetsRenderObserver = null;
  116652. }
  116653. },
  116654. enumerable: true,
  116655. configurable: true
  116656. });
  116657. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  116658. /**
  116659. * Gets the perf counter used for particles render time
  116660. */
  116661. get: function () {
  116662. return this._particlesRenderTime;
  116663. },
  116664. enumerable: true,
  116665. configurable: true
  116666. });
  116667. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  116668. /**
  116669. * Gets the particles render time capture status
  116670. */
  116671. get: function () {
  116672. return this._captureParticlesRenderTime;
  116673. },
  116674. /**
  116675. * Enable or disable the particles render time capture
  116676. */
  116677. set: function (value) {
  116678. var _this = this;
  116679. if (value === this._captureParticlesRenderTime) {
  116680. return;
  116681. }
  116682. this._captureParticlesRenderTime = value;
  116683. if (value) {
  116684. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  116685. BABYLON.Tools.StartPerformanceCounter("Particles");
  116686. _this._particlesRenderTime.beginMonitoring();
  116687. });
  116688. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  116689. BABYLON.Tools.EndPerformanceCounter("Particles");
  116690. _this._particlesRenderTime.endMonitoring(false);
  116691. });
  116692. }
  116693. else {
  116694. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  116695. this._onBeforeParticlesRenderingObserver = null;
  116696. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  116697. this._onAfterParticlesRenderingObserver = null;
  116698. }
  116699. },
  116700. enumerable: true,
  116701. configurable: true
  116702. });
  116703. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  116704. /**
  116705. * Gets the perf counter used for sprites render time
  116706. */
  116707. get: function () {
  116708. return this._spritesRenderTime;
  116709. },
  116710. enumerable: true,
  116711. configurable: true
  116712. });
  116713. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  116714. /**
  116715. * Gets the sprites render time capture status
  116716. */
  116717. get: function () {
  116718. return this._captureSpritesRenderTime;
  116719. },
  116720. /**
  116721. * Enable or disable the sprites render time capture
  116722. */
  116723. set: function (value) {
  116724. var _this = this;
  116725. if (value === this._captureSpritesRenderTime) {
  116726. return;
  116727. }
  116728. this._captureSpritesRenderTime = value;
  116729. if (!this.scene.spriteManagers) {
  116730. return;
  116731. }
  116732. if (value) {
  116733. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  116734. BABYLON.Tools.StartPerformanceCounter("Sprites");
  116735. _this._spritesRenderTime.beginMonitoring();
  116736. });
  116737. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  116738. BABYLON.Tools.EndPerformanceCounter("Sprites");
  116739. _this._spritesRenderTime.endMonitoring(false);
  116740. });
  116741. }
  116742. else {
  116743. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  116744. this._onBeforeSpritesRenderingObserver = null;
  116745. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  116746. this._onAfterSpritesRenderingObserver = null;
  116747. }
  116748. },
  116749. enumerable: true,
  116750. configurable: true
  116751. });
  116752. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  116753. /**
  116754. * Gets the perf counter used for physics time
  116755. */
  116756. get: function () {
  116757. return this._physicsTime;
  116758. },
  116759. enumerable: true,
  116760. configurable: true
  116761. });
  116762. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  116763. /**
  116764. * Gets the physics time capture status
  116765. */
  116766. get: function () {
  116767. return this._capturePhysicsTime;
  116768. },
  116769. /**
  116770. * Enable or disable the physics time capture
  116771. */
  116772. set: function (value) {
  116773. var _this = this;
  116774. if (value === this._capturePhysicsTime) {
  116775. return;
  116776. }
  116777. if (!this.scene.onBeforePhysicsObservable) {
  116778. return;
  116779. }
  116780. this._capturePhysicsTime = value;
  116781. if (value) {
  116782. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  116783. BABYLON.Tools.StartPerformanceCounter("Physics");
  116784. _this._physicsTime.beginMonitoring();
  116785. });
  116786. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  116787. BABYLON.Tools.EndPerformanceCounter("Physics");
  116788. _this._physicsTime.endMonitoring();
  116789. });
  116790. }
  116791. else {
  116792. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  116793. this._onBeforePhysicsObserver = null;
  116794. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  116795. this._onAfterPhysicsObserver = null;
  116796. }
  116797. },
  116798. enumerable: true,
  116799. configurable: true
  116800. });
  116801. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  116802. /**
  116803. * Gets the perf counter used for animations time
  116804. */
  116805. get: function () {
  116806. return this._animationsTime;
  116807. },
  116808. enumerable: true,
  116809. configurable: true
  116810. });
  116811. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  116812. /**
  116813. * Gets the animations time capture status
  116814. */
  116815. get: function () {
  116816. return this._captureAnimationsTime;
  116817. },
  116818. /**
  116819. * Enable or disable the animations time capture
  116820. */
  116821. set: function (value) {
  116822. var _this = this;
  116823. if (value === this._captureAnimationsTime) {
  116824. return;
  116825. }
  116826. this._captureAnimationsTime = value;
  116827. if (value) {
  116828. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  116829. _this._animationsTime.endMonitoring();
  116830. });
  116831. }
  116832. else {
  116833. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  116834. this._onAfterAnimationsObserver = null;
  116835. }
  116836. },
  116837. enumerable: true,
  116838. configurable: true
  116839. });
  116840. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  116841. /**
  116842. * Gets the perf counter used for frame time capture
  116843. */
  116844. get: function () {
  116845. return this._frameTime;
  116846. },
  116847. enumerable: true,
  116848. configurable: true
  116849. });
  116850. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  116851. /**
  116852. * Gets the frame time capture status
  116853. */
  116854. get: function () {
  116855. return this._captureFrameTime;
  116856. },
  116857. /**
  116858. * Enable or disable the frame time capture
  116859. */
  116860. set: function (value) {
  116861. this._captureFrameTime = value;
  116862. },
  116863. enumerable: true,
  116864. configurable: true
  116865. });
  116866. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  116867. /**
  116868. * Gets the perf counter used for inter-frames time capture
  116869. */
  116870. get: function () {
  116871. return this._interFrameTime;
  116872. },
  116873. enumerable: true,
  116874. configurable: true
  116875. });
  116876. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  116877. /**
  116878. * Gets the inter-frames time capture status
  116879. */
  116880. get: function () {
  116881. return this._captureInterFrameTime;
  116882. },
  116883. /**
  116884. * Enable or disable the inter-frames time capture
  116885. */
  116886. set: function (value) {
  116887. this._captureInterFrameTime = value;
  116888. },
  116889. enumerable: true,
  116890. configurable: true
  116891. });
  116892. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  116893. /**
  116894. * Gets the perf counter used for render time capture
  116895. */
  116896. get: function () {
  116897. return this._renderTime;
  116898. },
  116899. enumerable: true,
  116900. configurable: true
  116901. });
  116902. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  116903. /**
  116904. * Gets the render time capture status
  116905. */
  116906. get: function () {
  116907. return this._captureRenderTime;
  116908. },
  116909. /**
  116910. * Enable or disable the render time capture
  116911. */
  116912. set: function (value) {
  116913. var _this = this;
  116914. if (value === this._captureRenderTime) {
  116915. return;
  116916. }
  116917. this._captureRenderTime = value;
  116918. if (value) {
  116919. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  116920. _this._renderTime.beginMonitoring();
  116921. BABYLON.Tools.StartPerformanceCounter("Main render");
  116922. });
  116923. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  116924. _this._renderTime.endMonitoring(false);
  116925. BABYLON.Tools.EndPerformanceCounter("Main render");
  116926. });
  116927. }
  116928. else {
  116929. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  116930. this._onBeforeDrawPhaseObserver = null;
  116931. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  116932. this._onAfterDrawPhaseObserver = null;
  116933. }
  116934. },
  116935. enumerable: true,
  116936. configurable: true
  116937. });
  116938. Object.defineProperty(SceneInstrumentation.prototype, "cameraRenderTimeCounter", {
  116939. /**
  116940. * Gets the perf counter used for camera render time capture
  116941. */
  116942. get: function () {
  116943. return this._cameraRenderTime;
  116944. },
  116945. enumerable: true,
  116946. configurable: true
  116947. });
  116948. Object.defineProperty(SceneInstrumentation.prototype, "captureCameraRenderTime", {
  116949. /**
  116950. * Gets the camera render time capture status
  116951. */
  116952. get: function () {
  116953. return this._captureCameraRenderTime;
  116954. },
  116955. /**
  116956. * Enable or disable the camera render time capture
  116957. */
  116958. set: function (value) {
  116959. var _this = this;
  116960. if (value === this._captureCameraRenderTime) {
  116961. return;
  116962. }
  116963. this._captureCameraRenderTime = value;
  116964. if (value) {
  116965. this._onBeforeCameraRenderObserver = this.scene.onBeforeCameraRenderObservable.add(function (camera) {
  116966. _this._cameraRenderTime.beginMonitoring();
  116967. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + camera.name);
  116968. });
  116969. this._onAfterCameraRenderObserver = this.scene.onAfterCameraRenderObservable.add(function (camera) {
  116970. _this._cameraRenderTime.endMonitoring(false);
  116971. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + camera.name);
  116972. });
  116973. }
  116974. else {
  116975. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  116976. this._onBeforeCameraRenderObserver = null;
  116977. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  116978. this._onAfterCameraRenderObserver = null;
  116979. }
  116980. },
  116981. enumerable: true,
  116982. configurable: true
  116983. });
  116984. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  116985. /**
  116986. * Gets the perf counter used for draw calls
  116987. */
  116988. get: function () {
  116989. return this.scene.getEngine()._drawCalls;
  116990. },
  116991. enumerable: true,
  116992. configurable: true
  116993. });
  116994. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  116995. /**
  116996. * Gets the perf counter used for texture collisions
  116997. */
  116998. get: function () {
  116999. return this.scene.getEngine()._textureCollisions;
  117000. },
  117001. enumerable: true,
  117002. configurable: true
  117003. });
  117004. /**
  117005. * Dispose and release associated resources.
  117006. */
  117007. SceneInstrumentation.prototype.dispose = function () {
  117008. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  117009. this._onAfterRenderObserver = null;
  117010. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  117011. this._onBeforeActiveMeshesEvaluationObserver = null;
  117012. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  117013. this._onAfterActiveMeshesEvaluationObserver = null;
  117014. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  117015. this._onBeforeRenderTargetsRenderObserver = null;
  117016. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  117017. this._onAfterRenderTargetsRenderObserver = null;
  117018. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  117019. this._onBeforeAnimationsObserver = null;
  117020. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  117021. this._onBeforeParticlesRenderingObserver = null;
  117022. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  117023. this._onAfterParticlesRenderingObserver = null;
  117024. if (this._onBeforeSpritesRenderingObserver) {
  117025. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  117026. this._onBeforeSpritesRenderingObserver = null;
  117027. }
  117028. if (this._onAfterSpritesRenderingObserver) {
  117029. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  117030. this._onAfterSpritesRenderingObserver = null;
  117031. }
  117032. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  117033. this._onBeforeDrawPhaseObserver = null;
  117034. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  117035. this._onAfterDrawPhaseObserver = null;
  117036. if (this._onBeforePhysicsObserver) {
  117037. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  117038. this._onBeforePhysicsObserver = null;
  117039. }
  117040. if (this._onAfterPhysicsObserver) {
  117041. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  117042. this._onAfterPhysicsObserver = null;
  117043. }
  117044. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  117045. this._onAfterAnimationsObserver = null;
  117046. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  117047. this._onBeforeCameraRenderObserver = null;
  117048. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  117049. this._onAfterCameraRenderObserver = null;
  117050. this.scene = null;
  117051. };
  117052. return SceneInstrumentation;
  117053. }());
  117054. BABYLON.SceneInstrumentation = SceneInstrumentation;
  117055. })(BABYLON || (BABYLON = {}));
  117056. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  117057. var BABYLON;
  117058. (function (BABYLON) {
  117059. /**
  117060. * @hidden
  117061. **/
  117062. var _TimeToken = /** @class */ (function () {
  117063. function _TimeToken() {
  117064. this._timeElapsedQueryEnded = false;
  117065. }
  117066. return _TimeToken;
  117067. }());
  117068. BABYLON._TimeToken = _TimeToken;
  117069. })(BABYLON || (BABYLON = {}));
  117070. //# sourceMappingURL=babylon.timeToken.js.map
  117071. var BABYLON;
  117072. (function (BABYLON) {
  117073. /**
  117074. * Background material defines definition.
  117075. * @hidden Mainly internal Use
  117076. */
  117077. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  117078. __extends(BackgroundMaterialDefines, _super);
  117079. /**
  117080. * Constructor of the defines.
  117081. */
  117082. function BackgroundMaterialDefines() {
  117083. var _this = _super.call(this) || this;
  117084. /**
  117085. * True if the diffuse texture is in use.
  117086. */
  117087. _this.DIFFUSE = false;
  117088. /**
  117089. * The direct UV channel to use.
  117090. */
  117091. _this.DIFFUSEDIRECTUV = 0;
  117092. /**
  117093. * True if the diffuse texture is in gamma space.
  117094. */
  117095. _this.GAMMADIFFUSE = false;
  117096. /**
  117097. * True if the diffuse texture has opacity in the alpha channel.
  117098. */
  117099. _this.DIFFUSEHASALPHA = false;
  117100. /**
  117101. * True if you want the material to fade to transparent at grazing angle.
  117102. */
  117103. _this.OPACITYFRESNEL = false;
  117104. /**
  117105. * True if an extra blur needs to be added in the reflection.
  117106. */
  117107. _this.REFLECTIONBLUR = false;
  117108. /**
  117109. * True if you want the material to fade to reflection at grazing angle.
  117110. */
  117111. _this.REFLECTIONFRESNEL = false;
  117112. /**
  117113. * True if you want the material to falloff as far as you move away from the scene center.
  117114. */
  117115. _this.REFLECTIONFALLOFF = false;
  117116. /**
  117117. * False if the current Webgl implementation does not support the texture lod extension.
  117118. */
  117119. _this.TEXTURELODSUPPORT = false;
  117120. /**
  117121. * True to ensure the data are premultiplied.
  117122. */
  117123. _this.PREMULTIPLYALPHA = false;
  117124. /**
  117125. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  117126. */
  117127. _this.USERGBCOLOR = false;
  117128. /**
  117129. * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color
  117130. * stays aligned with the desired configuration.
  117131. */
  117132. _this.USEHIGHLIGHTANDSHADOWCOLORS = false;
  117133. /**
  117134. * True to add noise in order to reduce the banding effect.
  117135. */
  117136. _this.NOISE = false;
  117137. /**
  117138. * is the reflection texture in BGR color scheme?
  117139. * Mainly used to solve a bug in ios10 video tag
  117140. */
  117141. _this.REFLECTIONBGR = false;
  117142. _this.IMAGEPROCESSING = false;
  117143. _this.VIGNETTE = false;
  117144. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  117145. _this.VIGNETTEBLENDMODEOPAQUE = false;
  117146. _this.TONEMAPPING = false;
  117147. _this.TONEMAPPING_ACES = false;
  117148. _this.CONTRAST = false;
  117149. _this.COLORCURVES = false;
  117150. _this.COLORGRADING = false;
  117151. _this.COLORGRADING3D = false;
  117152. _this.SAMPLER3DGREENDEPTH = false;
  117153. _this.SAMPLER3DBGRMAP = false;
  117154. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  117155. _this.EXPOSURE = false;
  117156. // Reflection.
  117157. _this.REFLECTION = false;
  117158. _this.REFLECTIONMAP_3D = false;
  117159. _this.REFLECTIONMAP_SPHERICAL = false;
  117160. _this.REFLECTIONMAP_PLANAR = false;
  117161. _this.REFLECTIONMAP_CUBIC = false;
  117162. _this.REFLECTIONMAP_PROJECTION = false;
  117163. _this.REFLECTIONMAP_SKYBOX = false;
  117164. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  117165. _this.REFLECTIONMAP_EXPLICIT = false;
  117166. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  117167. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  117168. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  117169. _this.INVERTCUBICMAP = false;
  117170. _this.REFLECTIONMAP_OPPOSITEZ = false;
  117171. _this.LODINREFLECTIONALPHA = false;
  117172. _this.GAMMAREFLECTION = false;
  117173. _this.RGBDREFLECTION = false;
  117174. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  117175. // Default BJS.
  117176. _this.MAINUV1 = false;
  117177. _this.MAINUV2 = false;
  117178. _this.UV1 = false;
  117179. _this.UV2 = false;
  117180. _this.CLIPPLANE = false;
  117181. _this.CLIPPLANE2 = false;
  117182. _this.CLIPPLANE3 = false;
  117183. _this.CLIPPLANE4 = false;
  117184. _this.POINTSIZE = false;
  117185. _this.FOG = false;
  117186. _this.NORMAL = false;
  117187. _this.NUM_BONE_INFLUENCERS = 0;
  117188. _this.BonesPerMesh = 0;
  117189. _this.INSTANCES = false;
  117190. _this.SHADOWFLOAT = false;
  117191. _this.rebuild();
  117192. return _this;
  117193. }
  117194. return BackgroundMaterialDefines;
  117195. }(BABYLON.MaterialDefines));
  117196. /**
  117197. * Background material used to create an efficient environement around your scene.
  117198. */
  117199. var BackgroundMaterial = /** @class */ (function (_super) {
  117200. __extends(BackgroundMaterial, _super);
  117201. /**
  117202. * Instantiates a Background Material in the given scene
  117203. * @param name The friendly name of the material
  117204. * @param scene The scene to add the material to
  117205. */
  117206. function BackgroundMaterial(name, scene) {
  117207. var _this = _super.call(this, name, scene) || this;
  117208. /**
  117209. * Key light Color (multiply against the environement texture)
  117210. */
  117211. _this.primaryColor = BABYLON.Color3.White();
  117212. _this._primaryColorShadowLevel = 0;
  117213. _this._primaryColorHighlightLevel = 0;
  117214. /**
  117215. * Reflection Texture used in the material.
  117216. * Should be author in a specific way for the best result (refer to the documentation).
  117217. */
  117218. _this.reflectionTexture = null;
  117219. /**
  117220. * Reflection Texture level of blur.
  117221. *
  117222. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  117223. * texture twice.
  117224. */
  117225. _this.reflectionBlur = 0;
  117226. /**
  117227. * Diffuse Texture used in the material.
  117228. * Should be author in a specific way for the best result (refer to the documentation).
  117229. */
  117230. _this.diffuseTexture = null;
  117231. _this._shadowLights = null;
  117232. /**
  117233. * Specify the list of lights casting shadow on the material.
  117234. * All scene shadow lights will be included if null.
  117235. */
  117236. _this.shadowLights = null;
  117237. /**
  117238. * Helps adjusting the shadow to a softer level if required.
  117239. * 0 means black shadows and 1 means no shadows.
  117240. */
  117241. _this.shadowLevel = 0;
  117242. /**
  117243. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  117244. * It is usually zero but might be interesting to modify according to your setup.
  117245. */
  117246. _this.sceneCenter = BABYLON.Vector3.Zero();
  117247. /**
  117248. * This helps specifying that the material is falling off to the sky box at grazing angle.
  117249. * This helps ensuring a nice transition when the camera goes under the ground.
  117250. */
  117251. _this.opacityFresnel = true;
  117252. /**
  117253. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  117254. * This helps adding a mirror texture on the ground.
  117255. */
  117256. _this.reflectionFresnel = false;
  117257. /**
  117258. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  117259. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  117260. */
  117261. _this.reflectionFalloffDistance = 0.0;
  117262. /**
  117263. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  117264. */
  117265. _this.reflectionAmount = 1.0;
  117266. /**
  117267. * This specifies the weight of the reflection at grazing angle.
  117268. */
  117269. _this.reflectionReflectance0 = 0.05;
  117270. /**
  117271. * This specifies the weight of the reflection at a perpendicular point of view.
  117272. */
  117273. _this.reflectionReflectance90 = 0.5;
  117274. /**
  117275. * Helps to directly use the maps channels instead of their level.
  117276. */
  117277. _this.useRGBColor = true;
  117278. /**
  117279. * This helps reducing the banding effect that could occur on the background.
  117280. */
  117281. _this.enableNoise = false;
  117282. _this._fovMultiplier = 1.0;
  117283. /**
  117284. * Enable the FOV adjustment feature controlled by fovMultiplier.
  117285. */
  117286. _this.useEquirectangularFOV = false;
  117287. _this._maxSimultaneousLights = 4;
  117288. /**
  117289. * Number of Simultaneous lights allowed on the material.
  117290. */
  117291. _this.maxSimultaneousLights = 4;
  117292. /**
  117293. * Keep track of the image processing observer to allow dispose and replace.
  117294. */
  117295. _this._imageProcessingObserver = null;
  117296. /**
  117297. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  117298. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  117299. */
  117300. _this.switchToBGR = false;
  117301. // Temp values kept as cache in the material.
  117302. _this._renderTargets = new BABYLON.SmartArray(16);
  117303. _this._reflectionControls = BABYLON.Vector4.Zero();
  117304. _this._white = BABYLON.Color3.White();
  117305. _this._primaryShadowColor = BABYLON.Color3.Black();
  117306. _this._primaryHighlightColor = BABYLON.Color3.Black();
  117307. // Setup the default processing configuration to the scene.
  117308. _this._attachImageProcessingConfiguration(null);
  117309. _this.getRenderTargetTextures = function () {
  117310. _this._renderTargets.reset();
  117311. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  117312. _this._renderTargets.push(_this._diffuseTexture);
  117313. }
  117314. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  117315. _this._renderTargets.push(_this._reflectionTexture);
  117316. }
  117317. return _this._renderTargets;
  117318. };
  117319. return _this;
  117320. }
  117321. Object.defineProperty(BackgroundMaterial.prototype, "_perceptualColor", {
  117322. /**
  117323. * Experimental Internal Use Only.
  117324. *
  117325. * Key light Color in "perceptual value" meaning the color you would like to see on screen.
  117326. * This acts as a helper to set the primary color to a more "human friendly" value.
  117327. * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the
  117328. * output color as close as possible from the chosen value.
  117329. * (This does not account for contrast color grading and color curves as they are considered post effect and not directly
  117330. * part of lighting setup.)
  117331. */
  117332. get: function () {
  117333. return this.__perceptualColor;
  117334. },
  117335. set: function (value) {
  117336. this.__perceptualColor = value;
  117337. this._computePrimaryColorFromPerceptualColor();
  117338. this._markAllSubMeshesAsLightsDirty();
  117339. },
  117340. enumerable: true,
  117341. configurable: true
  117342. });
  117343. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorShadowLevel", {
  117344. /**
  117345. * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.
  117346. * The color opposite to the primary color is used at the level chosen to define what the black area would look.
  117347. */
  117348. get: function () {
  117349. return this._primaryColorShadowLevel;
  117350. },
  117351. set: function (value) {
  117352. this._primaryColorShadowLevel = value;
  117353. this._computePrimaryColors();
  117354. this._markAllSubMeshesAsLightsDirty();
  117355. },
  117356. enumerable: true,
  117357. configurable: true
  117358. });
  117359. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorHighlightLevel", {
  117360. /**
  117361. * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.
  117362. * The primary color is used at the level chosen to define what the white area would look.
  117363. */
  117364. get: function () {
  117365. return this._primaryColorHighlightLevel;
  117366. },
  117367. set: function (value) {
  117368. this._primaryColorHighlightLevel = value;
  117369. this._computePrimaryColors();
  117370. this._markAllSubMeshesAsLightsDirty();
  117371. },
  117372. enumerable: true,
  117373. configurable: true
  117374. });
  117375. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  117376. /**
  117377. * Sets the reflection reflectance fresnel values according to the default standard
  117378. * empirically know to work well :-)
  117379. */
  117380. set: function (value) {
  117381. var reflectionWeight = value;
  117382. if (reflectionWeight < 0.5) {
  117383. reflectionWeight = reflectionWeight * 2.0;
  117384. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  117385. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  117386. }
  117387. else {
  117388. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  117389. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  117390. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  117391. }
  117392. },
  117393. enumerable: true,
  117394. configurable: true
  117395. });
  117396. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  117397. /**
  117398. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  117399. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  117400. * Recommended to be keep at 1.0 except for special cases.
  117401. */
  117402. get: function () {
  117403. return this._fovMultiplier;
  117404. },
  117405. set: function (value) {
  117406. if (isNaN(value)) {
  117407. value = 1.0;
  117408. }
  117409. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  117410. },
  117411. enumerable: true,
  117412. configurable: true
  117413. });
  117414. /**
  117415. * Attaches a new image processing configuration to the PBR Material.
  117416. * @param configuration (if null the scene configuration will be use)
  117417. */
  117418. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  117419. var _this = this;
  117420. if (configuration === this._imageProcessingConfiguration) {
  117421. return;
  117422. }
  117423. // Detaches observer.
  117424. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  117425. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  117426. }
  117427. // Pick the scene configuration if needed.
  117428. if (!configuration) {
  117429. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  117430. }
  117431. else {
  117432. this._imageProcessingConfiguration = configuration;
  117433. }
  117434. // Attaches observer.
  117435. if (this._imageProcessingConfiguration) {
  117436. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  117437. _this._computePrimaryColorFromPerceptualColor();
  117438. _this._markAllSubMeshesAsImageProcessingDirty();
  117439. });
  117440. }
  117441. };
  117442. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  117443. /**
  117444. * Gets the image processing configuration used either in this material.
  117445. */
  117446. get: function () {
  117447. return this._imageProcessingConfiguration;
  117448. },
  117449. /**
  117450. * Sets the Default image processing configuration used either in the this material.
  117451. *
  117452. * If sets to null, the scene one is in use.
  117453. */
  117454. set: function (value) {
  117455. this._attachImageProcessingConfiguration(value);
  117456. // Ensure the effect will be rebuilt.
  117457. this._markAllSubMeshesAsTexturesDirty();
  117458. },
  117459. enumerable: true,
  117460. configurable: true
  117461. });
  117462. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  117463. /**
  117464. * Gets wether the color curves effect is enabled.
  117465. */
  117466. get: function () {
  117467. return this.imageProcessingConfiguration.colorCurvesEnabled;
  117468. },
  117469. /**
  117470. * Sets wether the color curves effect is enabled.
  117471. */
  117472. set: function (value) {
  117473. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  117474. },
  117475. enumerable: true,
  117476. configurable: true
  117477. });
  117478. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  117479. /**
  117480. * Gets wether the color grading effect is enabled.
  117481. */
  117482. get: function () {
  117483. return this.imageProcessingConfiguration.colorGradingEnabled;
  117484. },
  117485. /**
  117486. * Gets wether the color grading effect is enabled.
  117487. */
  117488. set: function (value) {
  117489. this.imageProcessingConfiguration.colorGradingEnabled = value;
  117490. },
  117491. enumerable: true,
  117492. configurable: true
  117493. });
  117494. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  117495. /**
  117496. * Gets wether tonemapping is enabled or not.
  117497. */
  117498. get: function () {
  117499. return this._imageProcessingConfiguration.toneMappingEnabled;
  117500. },
  117501. /**
  117502. * Sets wether tonemapping is enabled or not
  117503. */
  117504. set: function (value) {
  117505. this._imageProcessingConfiguration.toneMappingEnabled = value;
  117506. },
  117507. enumerable: true,
  117508. configurable: true
  117509. });
  117510. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  117511. /**
  117512. * The camera exposure used on this material.
  117513. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  117514. * This corresponds to a photographic exposure.
  117515. */
  117516. get: function () {
  117517. return this._imageProcessingConfiguration.exposure;
  117518. },
  117519. /**
  117520. * The camera exposure used on this material.
  117521. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  117522. * This corresponds to a photographic exposure.
  117523. */
  117524. set: function (value) {
  117525. this._imageProcessingConfiguration.exposure = value;
  117526. },
  117527. enumerable: true,
  117528. configurable: true
  117529. });
  117530. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  117531. /**
  117532. * Gets The camera contrast used on this material.
  117533. */
  117534. get: function () {
  117535. return this._imageProcessingConfiguration.contrast;
  117536. },
  117537. /**
  117538. * Sets The camera contrast used on this material.
  117539. */
  117540. set: function (value) {
  117541. this._imageProcessingConfiguration.contrast = value;
  117542. },
  117543. enumerable: true,
  117544. configurable: true
  117545. });
  117546. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  117547. /**
  117548. * Gets the Color Grading 2D Lookup Texture.
  117549. */
  117550. get: function () {
  117551. return this._imageProcessingConfiguration.colorGradingTexture;
  117552. },
  117553. /**
  117554. * Sets the Color Grading 2D Lookup Texture.
  117555. */
  117556. set: function (value) {
  117557. this.imageProcessingConfiguration.colorGradingTexture = value;
  117558. },
  117559. enumerable: true,
  117560. configurable: true
  117561. });
  117562. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  117563. /**
  117564. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  117565. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  117566. * 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;
  117567. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  117568. */
  117569. get: function () {
  117570. return this.imageProcessingConfiguration.colorCurves;
  117571. },
  117572. /**
  117573. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  117574. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  117575. * 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;
  117576. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  117577. */
  117578. set: function (value) {
  117579. this.imageProcessingConfiguration.colorCurves = value;
  117580. },
  117581. enumerable: true,
  117582. configurable: true
  117583. });
  117584. Object.defineProperty(BackgroundMaterial.prototype, "hasRenderTargetTextures", {
  117585. /**
  117586. * Gets a boolean indicating that current material needs to register RTT
  117587. */
  117588. get: function () {
  117589. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  117590. return true;
  117591. }
  117592. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  117593. return true;
  117594. }
  117595. return false;
  117596. },
  117597. enumerable: true,
  117598. configurable: true
  117599. });
  117600. /**
  117601. * The entire material has been created in order to prevent overdraw.
  117602. * @returns false
  117603. */
  117604. BackgroundMaterial.prototype.needAlphaTesting = function () {
  117605. return true;
  117606. };
  117607. /**
  117608. * The entire material has been created in order to prevent overdraw.
  117609. * @returns true if blending is enable
  117610. */
  117611. BackgroundMaterial.prototype.needAlphaBlending = function () {
  117612. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  117613. };
  117614. /**
  117615. * Checks wether the material is ready to be rendered for a given mesh.
  117616. * @param mesh The mesh to render
  117617. * @param subMesh The submesh to check against
  117618. * @param useInstances Specify wether or not the material is used with instances
  117619. * @returns true if all the dependencies are ready (Textures, Effects...)
  117620. */
  117621. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  117622. var _this = this;
  117623. if (useInstances === void 0) { useInstances = false; }
  117624. if (subMesh.effect && this.isFrozen) {
  117625. if (this._wasPreviouslyReady) {
  117626. return true;
  117627. }
  117628. }
  117629. if (!subMesh._materialDefines) {
  117630. subMesh._materialDefines = new BackgroundMaterialDefines();
  117631. }
  117632. var scene = this.getScene();
  117633. var defines = subMesh._materialDefines;
  117634. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  117635. if (defines._renderId === scene.getRenderId()) {
  117636. return true;
  117637. }
  117638. }
  117639. var engine = scene.getEngine();
  117640. // Lights
  117641. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  117642. defines._needNormals = true;
  117643. // Textures
  117644. if (defines._areTexturesDirty) {
  117645. defines._needUVs = false;
  117646. if (scene.texturesEnabled) {
  117647. if (scene.getEngine().getCaps().textureLOD) {
  117648. defines.TEXTURELODSUPPORT = true;
  117649. }
  117650. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  117651. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  117652. return false;
  117653. }
  117654. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  117655. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  117656. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  117657. defines.OPACITYFRESNEL = this._opacityFresnel;
  117658. }
  117659. else {
  117660. defines.DIFFUSE = false;
  117661. defines.DIFFUSEHASALPHA = false;
  117662. defines.GAMMADIFFUSE = false;
  117663. defines.OPACITYFRESNEL = false;
  117664. }
  117665. var reflectionTexture = this._reflectionTexture;
  117666. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  117667. if (!reflectionTexture.isReadyOrNotBlocking()) {
  117668. return false;
  117669. }
  117670. defines.REFLECTION = true;
  117671. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  117672. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  117673. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  117674. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  117675. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  117676. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  117677. defines.REFLECTIONBGR = this.switchToBGR;
  117678. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  117679. defines.INVERTCUBICMAP = true;
  117680. }
  117681. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  117682. switch (reflectionTexture.coordinatesMode) {
  117683. case BABYLON.Texture.EXPLICIT_MODE:
  117684. defines.REFLECTIONMAP_EXPLICIT = true;
  117685. break;
  117686. case BABYLON.Texture.PLANAR_MODE:
  117687. defines.REFLECTIONMAP_PLANAR = true;
  117688. break;
  117689. case BABYLON.Texture.PROJECTION_MODE:
  117690. defines.REFLECTIONMAP_PROJECTION = true;
  117691. break;
  117692. case BABYLON.Texture.SKYBOX_MODE:
  117693. defines.REFLECTIONMAP_SKYBOX = true;
  117694. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !reflectionTexture.getReflectionTextureMatrix().isIdentity();
  117695. break;
  117696. case BABYLON.Texture.SPHERICAL_MODE:
  117697. defines.REFLECTIONMAP_SPHERICAL = true;
  117698. break;
  117699. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  117700. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  117701. break;
  117702. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  117703. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  117704. break;
  117705. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  117706. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  117707. break;
  117708. case BABYLON.Texture.CUBIC_MODE:
  117709. case BABYLON.Texture.INVCUBIC_MODE:
  117710. default:
  117711. defines.REFLECTIONMAP_CUBIC = true;
  117712. break;
  117713. }
  117714. if (this.reflectionFresnel) {
  117715. defines.REFLECTIONFRESNEL = true;
  117716. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  117717. this._reflectionControls.x = this.reflectionAmount;
  117718. this._reflectionControls.y = this.reflectionReflectance0;
  117719. this._reflectionControls.z = this.reflectionReflectance90;
  117720. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  117721. }
  117722. else {
  117723. defines.REFLECTIONFRESNEL = false;
  117724. defines.REFLECTIONFALLOFF = false;
  117725. }
  117726. }
  117727. else {
  117728. defines.REFLECTION = false;
  117729. defines.REFLECTIONFRESNEL = false;
  117730. defines.REFLECTIONFALLOFF = false;
  117731. defines.REFLECTIONBLUR = false;
  117732. defines.REFLECTIONMAP_3D = false;
  117733. defines.REFLECTIONMAP_SPHERICAL = false;
  117734. defines.REFLECTIONMAP_PLANAR = false;
  117735. defines.REFLECTIONMAP_CUBIC = false;
  117736. defines.REFLECTIONMAP_PROJECTION = false;
  117737. defines.REFLECTIONMAP_SKYBOX = false;
  117738. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  117739. defines.REFLECTIONMAP_EXPLICIT = false;
  117740. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  117741. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  117742. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  117743. defines.INVERTCUBICMAP = false;
  117744. defines.REFLECTIONMAP_OPPOSITEZ = false;
  117745. defines.LODINREFLECTIONALPHA = false;
  117746. defines.GAMMAREFLECTION = false;
  117747. defines.RGBDREFLECTION = false;
  117748. }
  117749. }
  117750. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  117751. defines.USERGBCOLOR = this._useRGBColor;
  117752. defines.NOISE = this._enableNoise;
  117753. }
  117754. if (defines._areLightsDirty) {
  117755. defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
  117756. }
  117757. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  117758. if (!this._imageProcessingConfiguration.isReady()) {
  117759. return false;
  117760. }
  117761. this._imageProcessingConfiguration.prepareDefines(defines);
  117762. }
  117763. // Misc.
  117764. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  117765. // Values that need to be evaluated on every frame
  117766. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  117767. // Attribs
  117768. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  117769. if (mesh) {
  117770. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  117771. mesh.createNormals(true);
  117772. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  117773. }
  117774. }
  117775. }
  117776. // Get correct effect
  117777. if (defines.isDirty) {
  117778. defines.markAsProcessed();
  117779. scene.resetCachedMaterial();
  117780. // Fallbacks
  117781. var fallbacks = new BABYLON.EffectFallbacks();
  117782. if (defines.FOG) {
  117783. fallbacks.addFallback(0, "FOG");
  117784. }
  117785. if (defines.POINTSIZE) {
  117786. fallbacks.addFallback(1, "POINTSIZE");
  117787. }
  117788. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  117789. if (defines.NUM_BONE_INFLUENCERS > 0) {
  117790. fallbacks.addCPUSkinningFallback(0, mesh);
  117791. }
  117792. //Attributes
  117793. var attribs = [BABYLON.VertexBuffer.PositionKind];
  117794. if (defines.NORMAL) {
  117795. attribs.push(BABYLON.VertexBuffer.NormalKind);
  117796. }
  117797. if (defines.UV1) {
  117798. attribs.push(BABYLON.VertexBuffer.UVKind);
  117799. }
  117800. if (defines.UV2) {
  117801. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  117802. }
  117803. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  117804. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  117805. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  117806. "vFogInfos", "vFogColor", "pointSize",
  117807. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "mBones",
  117808. "vPrimaryColor", "vPrimaryColorShadow",
  117809. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  117810. "shadowLevel", "alpha",
  117811. "vBackgroundCenter", "vReflectionControl",
  117812. "vDiffuseInfos", "diffuseMatrix",
  117813. ];
  117814. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  117815. var uniformBuffers = ["Material", "Scene"];
  117816. if (BABYLON.ImageProcessingConfiguration) {
  117817. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  117818. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  117819. }
  117820. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  117821. uniformsNames: uniforms,
  117822. uniformBuffersNames: uniformBuffers,
  117823. samplers: samplers,
  117824. defines: defines,
  117825. maxSimultaneousLights: this._maxSimultaneousLights
  117826. });
  117827. var onCompiled = function (effect) {
  117828. if (_this.onCompiled) {
  117829. _this.onCompiled(effect);
  117830. }
  117831. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  117832. };
  117833. var join = defines.toString();
  117834. subMesh.setEffect(scene.getEngine().createEffect("background", {
  117835. attributes: attribs,
  117836. uniformsNames: uniforms,
  117837. uniformBuffersNames: uniformBuffers,
  117838. samplers: samplers,
  117839. defines: join,
  117840. fallbacks: fallbacks,
  117841. onCompiled: onCompiled,
  117842. onError: this.onError,
  117843. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  117844. }, engine), defines);
  117845. this.buildUniformLayout();
  117846. }
  117847. if (!subMesh.effect || !subMesh.effect.isReady()) {
  117848. return false;
  117849. }
  117850. defines._renderId = scene.getRenderId();
  117851. this._wasPreviouslyReady = true;
  117852. return true;
  117853. };
  117854. /**
  117855. * Compute the primary color according to the chosen perceptual color.
  117856. */
  117857. BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () {
  117858. if (!this.__perceptualColor) {
  117859. return;
  117860. }
  117861. this._primaryColor.copyFrom(this.__perceptualColor);
  117862. // Revert gamma space.
  117863. this._primaryColor.toLinearSpaceToRef(this._primaryColor);
  117864. // Revert image processing configuration.
  117865. if (this._imageProcessingConfiguration) {
  117866. // Revert Exposure.
  117867. this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);
  117868. }
  117869. this._computePrimaryColors();
  117870. };
  117871. /**
  117872. * Compute the highlights and shadow colors according to their chosen levels.
  117873. */
  117874. BackgroundMaterial.prototype._computePrimaryColors = function () {
  117875. if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {
  117876. return;
  117877. }
  117878. // Find the highlight color based on the configuration.
  117879. this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);
  117880. this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);
  117881. // Find the shadow color based on the configuration.
  117882. this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);
  117883. this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);
  117884. this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);
  117885. };
  117886. /**
  117887. * Build the uniform buffer used in the material.
  117888. */
  117889. BackgroundMaterial.prototype.buildUniformLayout = function () {
  117890. // Order is important !
  117891. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  117892. this._uniformBuffer.addUniform("vPrimaryColorShadow", 4);
  117893. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  117894. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  117895. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  117896. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  117897. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  117898. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  117899. this._uniformBuffer.addUniform("pointSize", 1);
  117900. this._uniformBuffer.addUniform("shadowLevel", 1);
  117901. this._uniformBuffer.addUniform("alpha", 1);
  117902. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  117903. this._uniformBuffer.addUniform("vReflectionControl", 4);
  117904. this._uniformBuffer.create();
  117905. };
  117906. /**
  117907. * Unbind the material.
  117908. */
  117909. BackgroundMaterial.prototype.unbind = function () {
  117910. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  117911. this._uniformBuffer.setTexture("diffuseSampler", null);
  117912. }
  117913. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  117914. this._uniformBuffer.setTexture("reflectionSampler", null);
  117915. }
  117916. _super.prototype.unbind.call(this);
  117917. };
  117918. /**
  117919. * Bind only the world matrix to the material.
  117920. * @param world The world matrix to bind.
  117921. */
  117922. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  117923. this._activeEffect.setMatrix("world", world);
  117924. };
  117925. /**
  117926. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  117927. * @param world The world matrix to bind.
  117928. * @param subMesh The submesh to bind for.
  117929. */
  117930. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  117931. var scene = this.getScene();
  117932. var defines = subMesh._materialDefines;
  117933. if (!defines) {
  117934. return;
  117935. }
  117936. var effect = subMesh.effect;
  117937. if (!effect) {
  117938. return;
  117939. }
  117940. this._activeEffect = effect;
  117941. // Matrices
  117942. this.bindOnlyWorldMatrix(world);
  117943. // Bones
  117944. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  117945. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  117946. if (mustRebind) {
  117947. this._uniformBuffer.bindToEffect(effect, "Material");
  117948. this.bindViewProjection(effect);
  117949. var reflectionTexture = this._reflectionTexture;
  117950. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  117951. // Texture uniforms
  117952. if (scene.texturesEnabled) {
  117953. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  117954. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  117955. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  117956. }
  117957. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  117958. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  117959. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  117960. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  117961. }
  117962. }
  117963. if (this.shadowLevel > 0) {
  117964. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  117965. }
  117966. this._uniformBuffer.updateFloat("alpha", this.alpha);
  117967. // Point size
  117968. if (this.pointsCloud) {
  117969. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  117970. }
  117971. if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {
  117972. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0);
  117973. this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0);
  117974. }
  117975. else {
  117976. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0);
  117977. }
  117978. }
  117979. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  117980. // Textures
  117981. if (scene.texturesEnabled) {
  117982. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  117983. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  117984. }
  117985. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  117986. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  117987. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  117988. }
  117989. else if (!defines.REFLECTIONBLUR) {
  117990. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  117991. }
  117992. else {
  117993. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  117994. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  117995. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  117996. }
  117997. if (defines.REFLECTIONFRESNEL) {
  117998. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  117999. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  118000. }
  118001. }
  118002. }
  118003. // Clip plane
  118004. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  118005. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  118006. }
  118007. if (mustRebind || !this.isFrozen) {
  118008. if (scene.lightsEnabled) {
  118009. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  118010. }
  118011. // View
  118012. this.bindView(effect);
  118013. // Fog
  118014. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect, true);
  118015. // image processing
  118016. if (this._imageProcessingConfiguration) {
  118017. this._imageProcessingConfiguration.bind(this._activeEffect);
  118018. }
  118019. }
  118020. this._uniformBuffer.update();
  118021. this._afterBind(mesh, this._activeEffect);
  118022. };
  118023. /**
  118024. * Dispose the material.
  118025. * @param forceDisposeEffect Force disposal of the associated effect.
  118026. * @param forceDisposeTextures Force disposal of the associated textures.
  118027. */
  118028. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  118029. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  118030. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  118031. if (forceDisposeTextures) {
  118032. if (this.diffuseTexture) {
  118033. this.diffuseTexture.dispose();
  118034. }
  118035. if (this.reflectionTexture) {
  118036. this.reflectionTexture.dispose();
  118037. }
  118038. }
  118039. this._renderTargets.dispose();
  118040. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  118041. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  118042. }
  118043. _super.prototype.dispose.call(this, forceDisposeEffect);
  118044. };
  118045. /**
  118046. * Clones the material.
  118047. * @param name The cloned name.
  118048. * @returns The cloned material.
  118049. */
  118050. BackgroundMaterial.prototype.clone = function (name) {
  118051. var _this = this;
  118052. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  118053. };
  118054. /**
  118055. * Serializes the current material to its JSON representation.
  118056. * @returns The JSON representation.
  118057. */
  118058. BackgroundMaterial.prototype.serialize = function () {
  118059. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  118060. serializationObject.customType = "BABYLON.BackgroundMaterial";
  118061. return serializationObject;
  118062. };
  118063. /**
  118064. * Gets the class name of the material
  118065. * @returns "BackgroundMaterial"
  118066. */
  118067. BackgroundMaterial.prototype.getClassName = function () {
  118068. return "BackgroundMaterial";
  118069. };
  118070. /**
  118071. * Parse a JSON input to create back a background material.
  118072. * @param source The JSON data to parse
  118073. * @param scene The scene to create the parsed material in
  118074. * @param rootUrl The root url of the assets the material depends upon
  118075. * @returns the instantiated BackgroundMaterial.
  118076. */
  118077. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  118078. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  118079. };
  118080. /**
  118081. * Standard reflectance value at parallel view angle.
  118082. */
  118083. BackgroundMaterial.StandardReflectance0 = 0.05;
  118084. /**
  118085. * Standard reflectance value at grazing angle.
  118086. */
  118087. BackgroundMaterial.StandardReflectance90 = 0.5;
  118088. __decorate([
  118089. BABYLON.serializeAsColor3()
  118090. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  118091. __decorate([
  118092. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  118093. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  118094. __decorate([
  118095. BABYLON.serializeAsColor3()
  118096. ], BackgroundMaterial.prototype, "__perceptualColor", void 0);
  118097. __decorate([
  118098. BABYLON.serialize()
  118099. ], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0);
  118100. __decorate([
  118101. BABYLON.serialize()
  118102. ], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0);
  118103. __decorate([
  118104. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  118105. ], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null);
  118106. __decorate([
  118107. BABYLON.serializeAsTexture()
  118108. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  118109. __decorate([
  118110. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  118111. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  118112. __decorate([
  118113. BABYLON.serialize()
  118114. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  118115. __decorate([
  118116. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  118117. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  118118. __decorate([
  118119. BABYLON.serializeAsTexture()
  118120. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  118121. __decorate([
  118122. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  118123. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  118124. __decorate([
  118125. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  118126. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  118127. __decorate([
  118128. BABYLON.serialize()
  118129. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  118130. __decorate([
  118131. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  118132. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  118133. __decorate([
  118134. BABYLON.serializeAsVector3()
  118135. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  118136. __decorate([
  118137. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  118138. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  118139. __decorate([
  118140. BABYLON.serialize()
  118141. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  118142. __decorate([
  118143. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  118144. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  118145. __decorate([
  118146. BABYLON.serialize()
  118147. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  118148. __decorate([
  118149. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  118150. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  118151. __decorate([
  118152. BABYLON.serialize()
  118153. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  118154. __decorate([
  118155. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  118156. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  118157. __decorate([
  118158. BABYLON.serialize()
  118159. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  118160. __decorate([
  118161. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  118162. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  118163. __decorate([
  118164. BABYLON.serialize()
  118165. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  118166. __decorate([
  118167. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  118168. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  118169. __decorate([
  118170. BABYLON.serialize()
  118171. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  118172. __decorate([
  118173. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  118174. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  118175. __decorate([
  118176. BABYLON.serialize()
  118177. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  118178. __decorate([
  118179. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  118180. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  118181. __decorate([
  118182. BABYLON.serialize()
  118183. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  118184. __decorate([
  118185. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  118186. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  118187. __decorate([
  118188. BABYLON.serialize()
  118189. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  118190. __decorate([
  118191. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  118192. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  118193. __decorate([
  118194. BABYLON.serializeAsImageProcessingConfiguration()
  118195. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  118196. return BackgroundMaterial;
  118197. }(BABYLON.PushMaterial));
  118198. BABYLON.BackgroundMaterial = BackgroundMaterial;
  118199. })(BABYLON || (BABYLON = {}));
  118200. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  118201. var __assign = (this && this.__assign) || function () {
  118202. __assign = Object.assign || function(t) {
  118203. for (var s, i = 1, n = arguments.length; i < n; i++) {
  118204. s = arguments[i];
  118205. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  118206. t[p] = s[p];
  118207. }
  118208. return t;
  118209. };
  118210. return __assign.apply(this, arguments);
  118211. };
  118212. var BABYLON;
  118213. (function (BABYLON) {
  118214. /**
  118215. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  118216. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  118217. * It also helps with the default setup of your imageProcessing configuration.
  118218. */
  118219. var EnvironmentHelper = /** @class */ (function () {
  118220. /**
  118221. * constructor
  118222. * @param options
  118223. * @param scene The scene to add the material to
  118224. */
  118225. function EnvironmentHelper(options, scene) {
  118226. var _this = this;
  118227. this._errorHandler = function (message, exception) {
  118228. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  118229. };
  118230. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  118231. this._scene = scene;
  118232. this.onErrorObservable = new BABYLON.Observable();
  118233. this._setupBackground();
  118234. this._setupImageProcessing();
  118235. }
  118236. /**
  118237. * Creates the default options for the helper.
  118238. */
  118239. EnvironmentHelper._getDefaultOptions = function () {
  118240. return {
  118241. createGround: true,
  118242. groundSize: 15,
  118243. groundTexture: this._groundTextureCDNUrl,
  118244. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  118245. groundOpacity: 0.9,
  118246. enableGroundShadow: true,
  118247. groundShadowLevel: 0.5,
  118248. enableGroundMirror: false,
  118249. groundMirrorSizeRatio: 0.3,
  118250. groundMirrorBlurKernel: 64,
  118251. groundMirrorAmount: 1,
  118252. groundMirrorFresnelWeight: 1,
  118253. groundMirrorFallOffDistance: 0,
  118254. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  118255. groundYBias: 0.00001,
  118256. createSkybox: true,
  118257. skyboxSize: 20,
  118258. skyboxTexture: this._skyboxTextureCDNUrl,
  118259. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  118260. backgroundYRotation: 0,
  118261. sizeAuto: true,
  118262. rootPosition: BABYLON.Vector3.Zero(),
  118263. setupImageProcessing: true,
  118264. environmentTexture: this._environmentTextureCDNUrl,
  118265. cameraExposure: 0.8,
  118266. cameraContrast: 1.2,
  118267. toneMappingEnabled: true,
  118268. };
  118269. };
  118270. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  118271. /**
  118272. * Gets the root mesh created by the helper.
  118273. */
  118274. get: function () {
  118275. return this._rootMesh;
  118276. },
  118277. enumerable: true,
  118278. configurable: true
  118279. });
  118280. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  118281. /**
  118282. * Gets the skybox created by the helper.
  118283. */
  118284. get: function () {
  118285. return this._skybox;
  118286. },
  118287. enumerable: true,
  118288. configurable: true
  118289. });
  118290. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  118291. /**
  118292. * Gets the skybox texture created by the helper.
  118293. */
  118294. get: function () {
  118295. return this._skyboxTexture;
  118296. },
  118297. enumerable: true,
  118298. configurable: true
  118299. });
  118300. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  118301. /**
  118302. * Gets the skybox material created by the helper.
  118303. */
  118304. get: function () {
  118305. return this._skyboxMaterial;
  118306. },
  118307. enumerable: true,
  118308. configurable: true
  118309. });
  118310. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  118311. /**
  118312. * Gets the ground mesh created by the helper.
  118313. */
  118314. get: function () {
  118315. return this._ground;
  118316. },
  118317. enumerable: true,
  118318. configurable: true
  118319. });
  118320. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  118321. /**
  118322. * Gets the ground texture created by the helper.
  118323. */
  118324. get: function () {
  118325. return this._groundTexture;
  118326. },
  118327. enumerable: true,
  118328. configurable: true
  118329. });
  118330. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  118331. /**
  118332. * Gets the ground mirror created by the helper.
  118333. */
  118334. get: function () {
  118335. return this._groundMirror;
  118336. },
  118337. enumerable: true,
  118338. configurable: true
  118339. });
  118340. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  118341. /**
  118342. * Gets the ground mirror render list to helps pushing the meshes
  118343. * you wish in the ground reflection.
  118344. */
  118345. get: function () {
  118346. if (this._groundMirror) {
  118347. return this._groundMirror.renderList;
  118348. }
  118349. return null;
  118350. },
  118351. enumerable: true,
  118352. configurable: true
  118353. });
  118354. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  118355. /**
  118356. * Gets the ground material created by the helper.
  118357. */
  118358. get: function () {
  118359. return this._groundMaterial;
  118360. },
  118361. enumerable: true,
  118362. configurable: true
  118363. });
  118364. /**
  118365. * Updates the background according to the new options
  118366. * @param options
  118367. */
  118368. EnvironmentHelper.prototype.updateOptions = function (options) {
  118369. var newOptions = __assign({}, this._options, options);
  118370. if (this._ground && !newOptions.createGround) {
  118371. this._ground.dispose();
  118372. this._ground = null;
  118373. }
  118374. if (this._groundMaterial && !newOptions.createGround) {
  118375. this._groundMaterial.dispose();
  118376. this._groundMaterial = null;
  118377. }
  118378. if (this._groundTexture) {
  118379. if (this._options.groundTexture != newOptions.groundTexture) {
  118380. this._groundTexture.dispose();
  118381. this._groundTexture = null;
  118382. }
  118383. }
  118384. if (this._skybox && !newOptions.createSkybox) {
  118385. this._skybox.dispose();
  118386. this._skybox = null;
  118387. }
  118388. if (this._skyboxMaterial && !newOptions.createSkybox) {
  118389. this._skyboxMaterial.dispose();
  118390. this._skyboxMaterial = null;
  118391. }
  118392. if (this._skyboxTexture) {
  118393. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  118394. this._skyboxTexture.dispose();
  118395. this._skyboxTexture = null;
  118396. }
  118397. }
  118398. if (this._groundMirror && !newOptions.enableGroundMirror) {
  118399. this._groundMirror.dispose();
  118400. this._groundMirror = null;
  118401. }
  118402. if (this._scene.environmentTexture) {
  118403. if (this._options.environmentTexture != newOptions.environmentTexture) {
  118404. this._scene.environmentTexture.dispose();
  118405. }
  118406. }
  118407. this._options = newOptions;
  118408. this._setupBackground();
  118409. this._setupImageProcessing();
  118410. };
  118411. /**
  118412. * Sets the primary color of all the available elements.
  118413. * @param color the main color to affect to the ground and the background
  118414. */
  118415. EnvironmentHelper.prototype.setMainColor = function (color) {
  118416. if (this.groundMaterial) {
  118417. this.groundMaterial.primaryColor = color;
  118418. }
  118419. if (this.skyboxMaterial) {
  118420. this.skyboxMaterial.primaryColor = color;
  118421. }
  118422. if (this.groundMirror) {
  118423. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  118424. }
  118425. };
  118426. /**
  118427. * Setup the image processing according to the specified options.
  118428. */
  118429. EnvironmentHelper.prototype._setupImageProcessing = function () {
  118430. if (this._options.setupImageProcessing) {
  118431. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  118432. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  118433. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  118434. this._setupEnvironmentTexture();
  118435. }
  118436. };
  118437. /**
  118438. * Setup the environment texture according to the specified options.
  118439. */
  118440. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  118441. if (this._scene.environmentTexture) {
  118442. return;
  118443. }
  118444. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  118445. this._scene.environmentTexture = this._options.environmentTexture;
  118446. return;
  118447. }
  118448. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  118449. this._scene.environmentTexture = environmentTexture;
  118450. };
  118451. /**
  118452. * Setup the background according to the specified options.
  118453. */
  118454. EnvironmentHelper.prototype._setupBackground = function () {
  118455. if (!this._rootMesh) {
  118456. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  118457. }
  118458. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  118459. var sceneSize = this._getSceneSize();
  118460. if (this._options.createGround) {
  118461. this._setupGround(sceneSize);
  118462. this._setupGroundMaterial();
  118463. this._setupGroundDiffuseTexture();
  118464. if (this._options.enableGroundMirror) {
  118465. this._setupGroundMirrorTexture(sceneSize);
  118466. }
  118467. this._setupMirrorInGroundMaterial();
  118468. }
  118469. if (this._options.createSkybox) {
  118470. this._setupSkybox(sceneSize);
  118471. this._setupSkyboxMaterial();
  118472. this._setupSkyboxReflectionTexture();
  118473. }
  118474. this._rootMesh.position.x = sceneSize.rootPosition.x;
  118475. this._rootMesh.position.z = sceneSize.rootPosition.z;
  118476. this._rootMesh.position.y = sceneSize.rootPosition.y;
  118477. };
  118478. /**
  118479. * Get the scene sizes according to the setup.
  118480. */
  118481. EnvironmentHelper.prototype._getSceneSize = function () {
  118482. var _this = this;
  118483. var groundSize = this._options.groundSize;
  118484. var skyboxSize = this._options.skyboxSize;
  118485. var rootPosition = this._options.rootPosition;
  118486. if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper.
  118487. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  118488. }
  118489. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  118490. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  118491. });
  118492. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  118493. if (this._options.sizeAuto) {
  118494. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  118495. this._scene.activeCamera.upperRadiusLimit) {
  118496. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  118497. skyboxSize = groundSize;
  118498. }
  118499. var sceneDiagonalLenght = sceneDiagonal.length();
  118500. if (sceneDiagonalLenght > groundSize) {
  118501. groundSize = sceneDiagonalLenght * 2;
  118502. skyboxSize = groundSize;
  118503. }
  118504. // 10 % bigger.
  118505. groundSize *= 1.1;
  118506. skyboxSize *= 1.5;
  118507. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  118508. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  118509. }
  118510. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  118511. };
  118512. /**
  118513. * Setup the ground according to the specified options.
  118514. */
  118515. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  118516. var _this = this;
  118517. if (!this._ground || this._ground.isDisposed()) {
  118518. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  118519. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  118520. this._ground.parent = this._rootMesh;
  118521. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  118522. }
  118523. this._ground.receiveShadows = this._options.enableGroundShadow;
  118524. };
  118525. /**
  118526. * Setup the ground material according to the specified options.
  118527. */
  118528. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  118529. if (!this._groundMaterial) {
  118530. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  118531. }
  118532. this._groundMaterial.alpha = this._options.groundOpacity;
  118533. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  118534. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  118535. this._groundMaterial.primaryColor = this._options.groundColor;
  118536. this._groundMaterial.useRGBColor = false;
  118537. this._groundMaterial.enableNoise = true;
  118538. if (this._ground) {
  118539. this._ground.material = this._groundMaterial;
  118540. }
  118541. };
  118542. /**
  118543. * Setup the ground diffuse texture according to the specified options.
  118544. */
  118545. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  118546. if (!this._groundMaterial) {
  118547. return;
  118548. }
  118549. if (this._groundTexture) {
  118550. return;
  118551. }
  118552. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  118553. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  118554. return;
  118555. }
  118556. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  118557. diffuseTexture.gammaSpace = false;
  118558. diffuseTexture.hasAlpha = true;
  118559. this._groundMaterial.diffuseTexture = diffuseTexture;
  118560. };
  118561. /**
  118562. * Setup the ground mirror texture according to the specified options.
  118563. */
  118564. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  118565. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  118566. if (!this._groundMirror) {
  118567. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  118568. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  118569. this._groundMirror.anisotropicFilteringLevel = 1;
  118570. this._groundMirror.wrapU = wrapping;
  118571. this._groundMirror.wrapV = wrapping;
  118572. this._groundMirror.gammaSpace = false;
  118573. if (this._groundMirror.renderList) {
  118574. for (var i = 0; i < this._scene.meshes.length; i++) {
  118575. var mesh = this._scene.meshes[i];
  118576. if (mesh !== this._ground &&
  118577. mesh !== this._skybox &&
  118578. mesh !== this._rootMesh) {
  118579. this._groundMirror.renderList.push(mesh);
  118580. }
  118581. }
  118582. }
  118583. }
  118584. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  118585. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  118586. };
  118587. /**
  118588. * Setup the ground to receive the mirror texture.
  118589. */
  118590. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  118591. if (this._groundMaterial) {
  118592. this._groundMaterial.reflectionTexture = this._groundMirror;
  118593. this._groundMaterial.reflectionFresnel = true;
  118594. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  118595. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  118596. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  118597. }
  118598. };
  118599. /**
  118600. * Setup the skybox according to the specified options.
  118601. */
  118602. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  118603. var _this = this;
  118604. if (!this._skybox || this._skybox.isDisposed()) {
  118605. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  118606. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  118607. }
  118608. this._skybox.parent = this._rootMesh;
  118609. };
  118610. /**
  118611. * Setup the skybox material according to the specified options.
  118612. */
  118613. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  118614. if (!this._skybox) {
  118615. return;
  118616. }
  118617. if (!this._skyboxMaterial) {
  118618. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  118619. }
  118620. this._skyboxMaterial.useRGBColor = false;
  118621. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  118622. this._skyboxMaterial.enableNoise = true;
  118623. this._skybox.material = this._skyboxMaterial;
  118624. };
  118625. /**
  118626. * Setup the skybox reflection texture according to the specified options.
  118627. */
  118628. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  118629. if (!this._skyboxMaterial) {
  118630. return;
  118631. }
  118632. if (this._skyboxTexture) {
  118633. return;
  118634. }
  118635. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  118636. this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;
  118637. return;
  118638. }
  118639. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  118640. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  118641. this._skyboxTexture.gammaSpace = false;
  118642. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  118643. };
  118644. /**
  118645. * Dispose all the elements created by the Helper.
  118646. */
  118647. EnvironmentHelper.prototype.dispose = function () {
  118648. if (this._groundMaterial) {
  118649. this._groundMaterial.dispose(true, true);
  118650. }
  118651. if (this._skyboxMaterial) {
  118652. this._skyboxMaterial.dispose(true, true);
  118653. }
  118654. this._rootMesh.dispose(false);
  118655. };
  118656. /**
  118657. * Default ground texture URL.
  118658. */
  118659. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  118660. /**
  118661. * Default skybox texture URL.
  118662. */
  118663. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  118664. /**
  118665. * Default environment texture URL.
  118666. */
  118667. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.env";
  118668. return EnvironmentHelper;
  118669. }());
  118670. BABYLON.EnvironmentHelper = EnvironmentHelper;
  118671. })(BABYLON || (BABYLON = {}));
  118672. //# sourceMappingURL=babylon.environmentHelper.js.map
  118673. var BABYLON;
  118674. (function (BABYLON) {
  118675. /** Internal class used to store shapes for emitters */
  118676. var ParticleSystemSetEmitterCreationOptions = /** @class */ (function () {
  118677. function ParticleSystemSetEmitterCreationOptions() {
  118678. }
  118679. return ParticleSystemSetEmitterCreationOptions;
  118680. }());
  118681. /**
  118682. * Represents a set of particle systems working together to create a specific effect
  118683. */
  118684. var ParticleSystemSet = /** @class */ (function () {
  118685. function ParticleSystemSet() {
  118686. /**
  118687. * Gets the particle system list
  118688. */
  118689. this.systems = new Array();
  118690. }
  118691. Object.defineProperty(ParticleSystemSet.prototype, "emitterNode", {
  118692. /**
  118693. * Gets the emitter node used with this set
  118694. */
  118695. get: function () {
  118696. return this._emitterNode;
  118697. },
  118698. enumerable: true,
  118699. configurable: true
  118700. });
  118701. /**
  118702. * Creates a new emitter mesh as a sphere
  118703. * @param options defines the options used to create the sphere
  118704. * @param renderingGroupId defines the renderingGroupId to use for the sphere
  118705. * @param scene defines the hosting scene
  118706. */
  118707. ParticleSystemSet.prototype.setEmitterAsSphere = function (options, renderingGroupId, scene) {
  118708. if (this._emitterNode) {
  118709. this._emitterNode.dispose();
  118710. }
  118711. this._emitterCreationOptions = {
  118712. kind: "Sphere",
  118713. options: options,
  118714. renderingGroupId: renderingGroupId
  118715. };
  118716. var emitterMesh = BABYLON.MeshBuilder.CreateSphere("emitterSphere", { diameter: options.diameter, segments: options.segments }, scene);
  118717. emitterMesh.renderingGroupId = renderingGroupId;
  118718. var material = new BABYLON.StandardMaterial("emitterSphereMaterial", scene);
  118719. material.emissiveColor = options.color;
  118720. emitterMesh.material = material;
  118721. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  118722. var system = _a[_i];
  118723. system.emitter = emitterMesh;
  118724. }
  118725. this._emitterNode = emitterMesh;
  118726. };
  118727. /**
  118728. * Starts all particle systems of the set
  118729. * @param emitter defines an optional mesh to use as emitter for the particle systems
  118730. */
  118731. ParticleSystemSet.prototype.start = function (emitter) {
  118732. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  118733. var system = _a[_i];
  118734. if (emitter) {
  118735. system.emitter = emitter;
  118736. }
  118737. system.start();
  118738. }
  118739. };
  118740. /**
  118741. * Release all associated resources
  118742. */
  118743. ParticleSystemSet.prototype.dispose = function () {
  118744. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  118745. var system = _a[_i];
  118746. system.dispose();
  118747. }
  118748. this.systems = [];
  118749. if (this._emitterNode) {
  118750. this._emitterNode.dispose();
  118751. this._emitterNode = null;
  118752. }
  118753. };
  118754. /**
  118755. * Serialize the set into a JSON compatible object
  118756. * @returns a JSON compatible representation of the set
  118757. */
  118758. ParticleSystemSet.prototype.serialize = function () {
  118759. var result = {};
  118760. result.systems = [];
  118761. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  118762. var system = _a[_i];
  118763. result.systems.push(system.serialize());
  118764. }
  118765. if (this._emitterNode) {
  118766. result.emitter = this._emitterCreationOptions;
  118767. }
  118768. return result;
  118769. };
  118770. /**
  118771. * Parse a new ParticleSystemSet from a serialized source
  118772. * @param data defines a JSON compatible representation of the set
  118773. * @param scene defines the hosting scene
  118774. * @param gpu defines if we want GPU particles or CPU particles
  118775. * @returns a new ParticleSystemSet
  118776. */
  118777. ParticleSystemSet.Parse = function (data, scene, gpu) {
  118778. if (gpu === void 0) { gpu = false; }
  118779. var result = new ParticleSystemSet();
  118780. var rootUrl = BABYLON.ParticleHelper.BaseAssetsUrl + "/textures/";
  118781. scene = scene || BABYLON.Engine.LastCreatedScene;
  118782. for (var _i = 0, _a = data.systems; _i < _a.length; _i++) {
  118783. var system = _a[_i];
  118784. result.systems.push(gpu ? BABYLON.GPUParticleSystem.Parse(system, scene, rootUrl, true) : BABYLON.ParticleSystem.Parse(system, scene, rootUrl, true));
  118785. }
  118786. if (data.emitter) {
  118787. var options = data.emitter.options;
  118788. switch (data.emitter.kind) {
  118789. case "Sphere":
  118790. result.setEmitterAsSphere({
  118791. diameter: options.diameter,
  118792. segments: options.segments,
  118793. color: BABYLON.Color3.FromArray(options.color)
  118794. }, data.emitter.renderingGroupId, scene);
  118795. break;
  118796. }
  118797. }
  118798. return result;
  118799. };
  118800. return ParticleSystemSet;
  118801. }());
  118802. BABYLON.ParticleSystemSet = ParticleSystemSet;
  118803. })(BABYLON || (BABYLON = {}));
  118804. //# sourceMappingURL=babylon.particleSystemSet.js.map
  118805. var BABYLON;
  118806. (function (BABYLON) {
  118807. /**
  118808. * This class is made for on one-liner static method to help creating particle system set.
  118809. */
  118810. var ParticleHelper = /** @class */ (function () {
  118811. function ParticleHelper() {
  118812. }
  118813. /**
  118814. * Create a default particle system that you can tweak
  118815. * @param emitter defines the emitter to use
  118816. * @param capacity defines the system capacity (default is 500 particles)
  118817. * @param scene defines the hosting scene
  118818. * @param useGPU defines if a GPUParticleSystem must be created (default is false)
  118819. * @returns the new Particle system
  118820. */
  118821. ParticleHelper.CreateDefault = function (emitter, capacity, scene, useGPU) {
  118822. if (capacity === void 0) { capacity = 500; }
  118823. if (useGPU === void 0) { useGPU = false; }
  118824. var system;
  118825. if (useGPU) {
  118826. system = new BABYLON.GPUParticleSystem("default system", { capacity: capacity }, scene);
  118827. }
  118828. else {
  118829. system = new BABYLON.ParticleSystem("default system", capacity, scene);
  118830. }
  118831. system.emitter = emitter;
  118832. system.particleTexture = new BABYLON.Texture("https://www.babylonjs.com/assets/Flare.png", system.getScene());
  118833. system.createConeEmitter(0.1, Math.PI / 4);
  118834. // Particle color
  118835. system.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  118836. system.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  118837. system.colorDead = new BABYLON.Color4(1.0, 1.0, 1.0, 0.0);
  118838. // Particle Size
  118839. system.minSize = 0.1;
  118840. system.maxSize = 0.1;
  118841. // Emission speed
  118842. system.minEmitPower = 2;
  118843. system.maxEmitPower = 2;
  118844. // Update speed
  118845. system.updateSpeed = 1 / 60;
  118846. system.emitRate = 30;
  118847. return system;
  118848. };
  118849. /**
  118850. * This is the main static method (one-liner) of this helper to create different particle systems
  118851. * @param type This string represents the type to the particle system to create
  118852. * @param scene The scene where the particle system should live
  118853. * @param gpu If the system will use gpu
  118854. * @returns the ParticleSystemSet created
  118855. */
  118856. ParticleHelper.CreateAsync = function (type, scene, gpu) {
  118857. if (gpu === void 0) { gpu = false; }
  118858. if (!scene) {
  118859. scene = BABYLON.Engine.LastCreatedScene;
  118860. }
  118861. var token = {};
  118862. scene._addPendingData(token);
  118863. return new Promise(function (resolve, reject) {
  118864. if (gpu && !BABYLON.GPUParticleSystem.IsSupported) {
  118865. scene._removePendingData(token);
  118866. return reject("Particle system with GPU is not supported.");
  118867. }
  118868. BABYLON.Tools.LoadFile(ParticleHelper.BaseAssetsUrl + "/systems/" + type + ".json", function (data, response) {
  118869. scene._removePendingData(token);
  118870. var newData = JSON.parse(data.toString());
  118871. return resolve(BABYLON.ParticleSystemSet.Parse(newData, scene, gpu));
  118872. }, undefined, undefined, undefined, function (req, exception) {
  118873. scene._removePendingData(token);
  118874. return reject("An error occured while the creation of your particle system. Check if your type '" + type + "' exists.");
  118875. });
  118876. });
  118877. };
  118878. /**
  118879. * Static function used to export a particle system to a ParticleSystemSet variable.
  118880. * Please note that the emitter shape is not exported
  118881. * @param systems defines the particle systems to export
  118882. * @returns the created particle system set
  118883. */
  118884. ParticleHelper.ExportSet = function (systems) {
  118885. var set = new BABYLON.ParticleSystemSet();
  118886. for (var _i = 0, systems_1 = systems; _i < systems_1.length; _i++) {
  118887. var system = systems_1[_i];
  118888. set.systems.push(system);
  118889. }
  118890. return set;
  118891. };
  118892. /**
  118893. * Gets or sets base Assets URL
  118894. */
  118895. ParticleHelper.BaseAssetsUrl = "https://assets.babylonjs.com/particles";
  118896. return ParticleHelper;
  118897. }());
  118898. BABYLON.ParticleHelper = ParticleHelper;
  118899. })(BABYLON || (BABYLON = {}));
  118900. //# sourceMappingURL=babylon.particleHelper.js.map
  118901. var BABYLON;
  118902. (function (BABYLON) {
  118903. /**
  118904. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  118905. * As a subclass of TransformNode, this allow parenting to the camera or multiple videos with different locations in the scene.
  118906. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  118907. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  118908. */
  118909. var VideoDome = /** @class */ (function (_super) {
  118910. __extends(VideoDome, _super);
  118911. /**
  118912. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  118913. * @param name Element's name, child elements will append suffixes for their own names.
  118914. * @param urlsOrVideo defines the url(s) or the video element to use
  118915. * @param options An object containing optional or exposed sub element properties
  118916. */
  118917. function VideoDome(name, urlsOrVideo, options, scene) {
  118918. var _this = _super.call(this, name, scene) || this;
  118919. _this._useDirectMapping = false;
  118920. // set defaults and manage values
  118921. name = name || "videoDome";
  118922. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  118923. options.clickToPlay = Boolean(options.clickToPlay);
  118924. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  118925. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  118926. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  118927. if (options.useDirectMapping === undefined) {
  118928. _this._useDirectMapping = true;
  118929. }
  118930. else {
  118931. _this._useDirectMapping = options.useDirectMapping;
  118932. }
  118933. _this._setReady(false);
  118934. // create
  118935. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true, poster: options.poster };
  118936. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  118937. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, _this._useDirectMapping, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  118938. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  118939. texture.onLoadObservable.addOnce(function () {
  118940. _this._setReady(true);
  118941. });
  118942. // configure material
  118943. material.useEquirectangularFOV = true;
  118944. material.fovMultiplier = 1.0;
  118945. material.opacityFresnel = false;
  118946. if (_this._useDirectMapping) {
  118947. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  118948. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  118949. material.diffuseTexture = texture;
  118950. }
  118951. else {
  118952. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  118953. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  118954. material.reflectionTexture = texture;
  118955. }
  118956. // configure mesh
  118957. _this._mesh.material = material;
  118958. _this._mesh.parent = _this;
  118959. // optional configuration
  118960. if (options.clickToPlay) {
  118961. scene.onPointerUp = function () {
  118962. _this._videoTexture.video.play();
  118963. };
  118964. }
  118965. return _this;
  118966. }
  118967. Object.defineProperty(VideoDome.prototype, "videoTexture", {
  118968. /**
  118969. * Gets the video texture being displayed on the sphere
  118970. */
  118971. get: function () {
  118972. return this._videoTexture;
  118973. },
  118974. enumerable: true,
  118975. configurable: true
  118976. });
  118977. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  118978. /**
  118979. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  118980. * Also see the options.resolution property.
  118981. */
  118982. get: function () {
  118983. return this._material.fovMultiplier;
  118984. },
  118985. set: function (value) {
  118986. this._material.fovMultiplier = value;
  118987. },
  118988. enumerable: true,
  118989. configurable: true
  118990. });
  118991. /**
  118992. * Releases resources associated with this node.
  118993. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  118994. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  118995. */
  118996. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  118997. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  118998. this._videoTexture.dispose();
  118999. this._mesh.dispose();
  119000. this._material.dispose();
  119001. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  119002. };
  119003. return VideoDome;
  119004. }(BABYLON.TransformNode));
  119005. BABYLON.VideoDome = VideoDome;
  119006. })(BABYLON || (BABYLON = {}));
  119007. //# sourceMappingURL=babylon.videoDome.js.map
  119008. var BABYLON;
  119009. (function (BABYLON) {
  119010. /**
  119011. * Display a 360 degree photo on an approximately spherical surface, useful for VR applications or skyboxes.
  119012. * As a subclass of TransformNode, this allow parenting to the camera with different locations in the scene.
  119013. * This class achieves its effect with a Texture and a correctly configured BackgroundMaterial on an inverted sphere.
  119014. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  119015. */
  119016. var PhotoDome = /** @class */ (function (_super) {
  119017. __extends(PhotoDome, _super);
  119018. /**
  119019. * Create an instance of this class and pass through the parameters to the relevant classes, Texture, StandardMaterial, and Mesh.
  119020. * @param name Element's name, child elements will append suffixes for their own names.
  119021. * @param urlsOfPhoto defines the url of the photo to display
  119022. * @param options defines an object containing optional or exposed sub element properties
  119023. * @param onError defines a callback called when an error occured while loading the texture
  119024. */
  119025. function PhotoDome(name, urlOfPhoto, options, scene, onError) {
  119026. if (onError === void 0) { onError = null; }
  119027. var _this = _super.call(this, name, scene) || this;
  119028. _this._useDirectMapping = false;
  119029. /**
  119030. * Observable raised when an error occured while loading the 360 image
  119031. */
  119032. _this.onLoadErrorObservable = new BABYLON.Observable();
  119033. // set defaults and manage values
  119034. name = name || "photoDome";
  119035. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  119036. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  119037. if (options.useDirectMapping === undefined) {
  119038. _this._useDirectMapping = true;
  119039. }
  119040. else {
  119041. _this._useDirectMapping = options.useDirectMapping;
  119042. }
  119043. _this._setReady(false);
  119044. // create
  119045. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  119046. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  119047. // configure material
  119048. material.opacityFresnel = false;
  119049. material.useEquirectangularFOV = true;
  119050. material.fovMultiplier = 1.0;
  119051. _this.photoTexture = new BABYLON.Texture(urlOfPhoto, scene, true, !_this._useDirectMapping, undefined, undefined, function (message, exception) {
  119052. _this.onLoadErrorObservable.notifyObservers(message || "Unknown error occured");
  119053. if (onError) {
  119054. onError(message, exception);
  119055. }
  119056. });
  119057. _this.photoTexture.onLoadObservable.addOnce(function () {
  119058. _this._setReady(true);
  119059. });
  119060. // configure mesh
  119061. _this._mesh.material = material;
  119062. _this._mesh.parent = _this;
  119063. return _this;
  119064. }
  119065. Object.defineProperty(PhotoDome.prototype, "photoTexture", {
  119066. /**
  119067. * Gets or sets the texture being displayed on the sphere
  119068. */
  119069. get: function () {
  119070. return this._photoTexture;
  119071. },
  119072. set: function (value) {
  119073. if (this._photoTexture === value) {
  119074. return;
  119075. }
  119076. this._photoTexture = value;
  119077. if (this._useDirectMapping) {
  119078. this._photoTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  119079. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  119080. this._material.diffuseTexture = this._photoTexture;
  119081. }
  119082. else {
  119083. this._photoTexture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  119084. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  119085. this._material.reflectionTexture = this._photoTexture;
  119086. }
  119087. },
  119088. enumerable: true,
  119089. configurable: true
  119090. });
  119091. Object.defineProperty(PhotoDome.prototype, "fovMultiplier", {
  119092. /**
  119093. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  119094. * Also see the options.resolution property.
  119095. */
  119096. get: function () {
  119097. return this._material.fovMultiplier;
  119098. },
  119099. set: function (value) {
  119100. this._material.fovMultiplier = value;
  119101. },
  119102. enumerable: true,
  119103. configurable: true
  119104. });
  119105. /**
  119106. * Releases resources associated with this node.
  119107. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  119108. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  119109. */
  119110. PhotoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  119111. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  119112. this._photoTexture.dispose();
  119113. this._mesh.dispose();
  119114. this._material.dispose();
  119115. this.onLoadErrorObservable.clear();
  119116. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  119117. };
  119118. return PhotoDome;
  119119. }(BABYLON.TransformNode));
  119120. BABYLON.PhotoDome = PhotoDome;
  119121. })(BABYLON || (BABYLON = {}));
  119122. //# sourceMappingURL=babylon.photoDome.js.map
  119123. var BABYLON;
  119124. (function (BABYLON) {
  119125. /** @hidden */
  119126. var _OcclusionDataStorage = /** @class */ (function () {
  119127. function _OcclusionDataStorage() {
  119128. /** @hidden */
  119129. this.occlusionInternalRetryCounter = 0;
  119130. /** @hidden */
  119131. this.isOcclusionQueryInProgress = false;
  119132. /** @hidden */
  119133. this.isOccluded = false;
  119134. /** @hidden */
  119135. this.occlusionRetryCount = -1;
  119136. /** @hidden */
  119137. this.occlusionType = BABYLON.AbstractMesh.OCCLUSION_TYPE_NONE;
  119138. /** @hidden */
  119139. this.occlusionQueryAlgorithmType = BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  119140. }
  119141. return _OcclusionDataStorage;
  119142. }());
  119143. BABYLON.Engine.prototype.createQuery = function () {
  119144. return this._gl.createQuery();
  119145. };
  119146. BABYLON.Engine.prototype.deleteQuery = function (query) {
  119147. this._gl.deleteQuery(query);
  119148. return this;
  119149. };
  119150. BABYLON.Engine.prototype.isQueryResultAvailable = function (query) {
  119151. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  119152. };
  119153. BABYLON.Engine.prototype.getQueryResult = function (query) {
  119154. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  119155. };
  119156. BABYLON.Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  119157. var glAlgorithm = this._getGlAlgorithmType(algorithmType);
  119158. this._gl.beginQuery(glAlgorithm, query);
  119159. return this;
  119160. };
  119161. BABYLON.Engine.prototype.endOcclusionQuery = function (algorithmType) {
  119162. var glAlgorithm = this._getGlAlgorithmType(algorithmType);
  119163. this._gl.endQuery(glAlgorithm);
  119164. return this;
  119165. };
  119166. BABYLON.Engine.prototype._createTimeQuery = function () {
  119167. var timerQuery = this.getCaps().timerQuery;
  119168. if (timerQuery.createQueryEXT) {
  119169. return timerQuery.createQueryEXT();
  119170. }
  119171. return this.createQuery();
  119172. };
  119173. BABYLON.Engine.prototype._deleteTimeQuery = function (query) {
  119174. var timerQuery = this.getCaps().timerQuery;
  119175. if (timerQuery.deleteQueryEXT) {
  119176. timerQuery.deleteQueryEXT(query);
  119177. return;
  119178. }
  119179. this.deleteQuery(query);
  119180. };
  119181. BABYLON.Engine.prototype._getTimeQueryResult = function (query) {
  119182. var timerQuery = this.getCaps().timerQuery;
  119183. if (timerQuery.getQueryObjectEXT) {
  119184. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  119185. }
  119186. return this.getQueryResult(query);
  119187. };
  119188. BABYLON.Engine.prototype._getTimeQueryAvailability = function (query) {
  119189. var timerQuery = this.getCaps().timerQuery;
  119190. if (timerQuery.getQueryObjectEXT) {
  119191. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  119192. }
  119193. return this.isQueryResultAvailable(query);
  119194. };
  119195. BABYLON.Engine.prototype.startTimeQuery = function () {
  119196. var caps = this.getCaps();
  119197. var timerQuery = caps.timerQuery;
  119198. if (!timerQuery) {
  119199. return null;
  119200. }
  119201. var token = new BABYLON._TimeToken();
  119202. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  119203. if (caps.canUseTimestampForTimerQuery) {
  119204. token._startTimeQuery = this._createTimeQuery();
  119205. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  119206. }
  119207. else {
  119208. if (this._currentNonTimestampToken) {
  119209. return this._currentNonTimestampToken;
  119210. }
  119211. token._timeElapsedQuery = this._createTimeQuery();
  119212. if (timerQuery.beginQueryEXT) {
  119213. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  119214. }
  119215. else {
  119216. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  119217. }
  119218. this._currentNonTimestampToken = token;
  119219. }
  119220. return token;
  119221. };
  119222. BABYLON.Engine.prototype.endTimeQuery = function (token) {
  119223. var caps = this.getCaps();
  119224. var timerQuery = caps.timerQuery;
  119225. if (!timerQuery || !token) {
  119226. return -1;
  119227. }
  119228. if (caps.canUseTimestampForTimerQuery) {
  119229. if (!token._startTimeQuery) {
  119230. return -1;
  119231. }
  119232. if (!token._endTimeQuery) {
  119233. token._endTimeQuery = this._createTimeQuery();
  119234. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  119235. }
  119236. }
  119237. else if (!token._timeElapsedQueryEnded) {
  119238. if (!token._timeElapsedQuery) {
  119239. return -1;
  119240. }
  119241. if (timerQuery.endQueryEXT) {
  119242. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  119243. }
  119244. else {
  119245. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  119246. }
  119247. token._timeElapsedQueryEnded = true;
  119248. }
  119249. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  119250. var available = false;
  119251. if (token._endTimeQuery) {
  119252. available = this._getTimeQueryAvailability(token._endTimeQuery);
  119253. }
  119254. else if (token._timeElapsedQuery) {
  119255. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  119256. }
  119257. if (available && !disjoint) {
  119258. var result = 0;
  119259. if (caps.canUseTimestampForTimerQuery) {
  119260. if (!token._startTimeQuery || !token._endTimeQuery) {
  119261. return -1;
  119262. }
  119263. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  119264. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  119265. result = timeEnd - timeStart;
  119266. this._deleteTimeQuery(token._startTimeQuery);
  119267. this._deleteTimeQuery(token._endTimeQuery);
  119268. token._startTimeQuery = null;
  119269. token._endTimeQuery = null;
  119270. }
  119271. else {
  119272. if (!token._timeElapsedQuery) {
  119273. return -1;
  119274. }
  119275. result = this._getTimeQueryResult(token._timeElapsedQuery);
  119276. this._deleteTimeQuery(token._timeElapsedQuery);
  119277. token._timeElapsedQuery = null;
  119278. token._timeElapsedQueryEnded = false;
  119279. this._currentNonTimestampToken = null;
  119280. }
  119281. return result;
  119282. }
  119283. return -1;
  119284. };
  119285. BABYLON.Engine.prototype._getGlAlgorithmType = function (algorithmType) {
  119286. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  119287. };
  119288. Object.defineProperty(BABYLON.AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  119289. get: function () {
  119290. return this._occlusionDataStorage.isOcclusionQueryInProgress;
  119291. },
  119292. enumerable: false,
  119293. configurable: true
  119294. });
  119295. Object.defineProperty(BABYLON.AbstractMesh.prototype, "_occlusionDataStorage", {
  119296. get: function () {
  119297. if (!this.__occlusionDataStorage) {
  119298. this.__occlusionDataStorage = new _OcclusionDataStorage();
  119299. }
  119300. return this.__occlusionDataStorage;
  119301. },
  119302. enumerable: false,
  119303. configurable: true
  119304. });
  119305. Object.defineProperty(BABYLON.AbstractMesh.prototype, "isOccluded", {
  119306. get: function () {
  119307. return this._occlusionDataStorage.isOccluded;
  119308. },
  119309. set: function (value) {
  119310. this._occlusionDataStorage.isOccluded = value;
  119311. },
  119312. enumerable: true,
  119313. configurable: true
  119314. });
  119315. Object.defineProperty(BABYLON.AbstractMesh.prototype, "occlusionQueryAlgorithmType", {
  119316. get: function () {
  119317. return this._occlusionDataStorage.occlusionQueryAlgorithmType;
  119318. },
  119319. set: function (value) {
  119320. this._occlusionDataStorage.occlusionQueryAlgorithmType = value;
  119321. },
  119322. enumerable: true,
  119323. configurable: true
  119324. });
  119325. Object.defineProperty(BABYLON.AbstractMesh.prototype, "occlusionType", {
  119326. get: function () {
  119327. return this._occlusionDataStorage.occlusionType;
  119328. },
  119329. set: function (value) {
  119330. this._occlusionDataStorage.occlusionType = value;
  119331. },
  119332. enumerable: true,
  119333. configurable: true
  119334. });
  119335. Object.defineProperty(BABYLON.AbstractMesh.prototype, "occlusionRetryCount", {
  119336. get: function () {
  119337. return this._occlusionDataStorage.occlusionRetryCount;
  119338. },
  119339. set: function (value) {
  119340. this._occlusionDataStorage.occlusionRetryCount = value;
  119341. },
  119342. enumerable: true,
  119343. configurable: true
  119344. });
  119345. // We also need to update AbstractMesh as there is a portion of the code there
  119346. BABYLON.AbstractMesh.prototype._checkOcclusionQuery = function () {
  119347. var dataStorage = this._occlusionDataStorage;
  119348. if (dataStorage.occlusionType === BABYLON.AbstractMesh.OCCLUSION_TYPE_NONE) {
  119349. dataStorage.isOccluded = false;
  119350. return false;
  119351. }
  119352. var engine = this.getEngine();
  119353. if (engine.webGLVersion < 2) {
  119354. dataStorage.isOccluded = false;
  119355. return false;
  119356. }
  119357. if (!engine.isQueryResultAvailable) { // Occlusion query where not referenced
  119358. dataStorage.isOccluded = false;
  119359. return false;
  119360. }
  119361. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  119362. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  119363. if (isOcclusionQueryAvailable) {
  119364. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  119365. dataStorage.isOcclusionQueryInProgress = false;
  119366. dataStorage.occlusionInternalRetryCounter = 0;
  119367. dataStorage.isOccluded = occlusionQueryResult === 1 ? false : true;
  119368. }
  119369. else {
  119370. dataStorage.occlusionInternalRetryCounter++;
  119371. if (dataStorage.occlusionRetryCount !== -1 && dataStorage.occlusionInternalRetryCounter > dataStorage.occlusionRetryCount) {
  119372. dataStorage.isOcclusionQueryInProgress = false;
  119373. dataStorage.occlusionInternalRetryCounter = 0;
  119374. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  119375. // if strict continue the last state of the object.
  119376. dataStorage.isOccluded = dataStorage.occlusionType === BABYLON.AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : dataStorage.isOccluded;
  119377. }
  119378. else {
  119379. return false;
  119380. }
  119381. }
  119382. }
  119383. var scene = this.getScene();
  119384. if (scene.getBoundingBoxRenderer) {
  119385. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  119386. if (!this._occlusionQuery) {
  119387. this._occlusionQuery = engine.createQuery();
  119388. }
  119389. engine.beginOcclusionQuery(dataStorage.occlusionQueryAlgorithmType, this._occlusionQuery);
  119390. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  119391. engine.endOcclusionQuery(dataStorage.occlusionQueryAlgorithmType);
  119392. this._occlusionDataStorage.isOcclusionQueryInProgress = true;
  119393. }
  119394. return dataStorage.isOccluded;
  119395. };
  119396. })(BABYLON || (BABYLON = {}));
  119397. //# sourceMappingURL=babylon.engine.occlusionQuery.js.map
  119398. var BABYLON;
  119399. (function (BABYLON) {
  119400. /**
  119401. * Class used to generate noise procedural textures
  119402. */
  119403. var NoiseProceduralTexture = /** @class */ (function (_super) {
  119404. __extends(NoiseProceduralTexture, _super);
  119405. /**
  119406. * Creates a new NoiseProceduralTexture
  119407. * @param name defines the name fo the texture
  119408. * @param size defines the size of the texture (default is 256)
  119409. * @param scene defines the hosting scene
  119410. * @param fallbackTexture defines the texture to use if the NoiseProceduralTexture can't be created
  119411. * @param generateMipMaps defines if mipmaps must be generated (true by default)
  119412. */
  119413. function NoiseProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  119414. if (size === void 0) { size = 256; }
  119415. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  119416. var _this = _super.call(this, name, size, "noise", scene, fallbackTexture, generateMipMaps) || this;
  119417. _this._time = 0;
  119418. /** Gets or sets a value between 0 and 1 indicating the overall brightness of the texture (default is 0.2) */
  119419. _this.brightness = 0.2;
  119420. /** Defines the number of octaves to process */
  119421. _this.octaves = 3;
  119422. /** Defines the level of persistence (0.8 by default) */
  119423. _this.persistence = 0.8;
  119424. /** Gets or sets animation speed factor (default is 1) */
  119425. _this.animationSpeedFactor = 1;
  119426. _this.autoClear = false;
  119427. _this._updateShaderUniforms();
  119428. return _this;
  119429. }
  119430. NoiseProceduralTexture.prototype._updateShaderUniforms = function () {
  119431. var scene = this.getScene();
  119432. if (!scene) {
  119433. return;
  119434. }
  119435. this._time += scene.getAnimationRatio() * this.animationSpeedFactor * 0.01;
  119436. this.setFloat("brightness", this.brightness);
  119437. this.setFloat("persistence", this.persistence);
  119438. this.setFloat("timeScale", this._time);
  119439. };
  119440. NoiseProceduralTexture.prototype._getDefines = function () {
  119441. return "#define OCTAVES " + (this.octaves | 0);
  119442. };
  119443. /** Generate the current state of the procedural texture */
  119444. NoiseProceduralTexture.prototype.render = function (useCameraPostProcess) {
  119445. this._updateShaderUniforms();
  119446. _super.prototype.render.call(this, useCameraPostProcess);
  119447. };
  119448. /**
  119449. * Serializes this noise procedural texture
  119450. * @returns a serialized noise procedural texture object
  119451. */
  119452. NoiseProceduralTexture.prototype.serialize = function () {
  119453. var serializationObject = {};
  119454. serializationObject.customType = "BABYLON.NoiseProceduralTexture";
  119455. serializationObject.brightness = this.brightness;
  119456. serializationObject.octaves = this.octaves;
  119457. serializationObject.persistence = this.persistence;
  119458. serializationObject.animationSpeedFactor = this.animationSpeedFactor;
  119459. serializationObject.size = this.getSize().width;
  119460. serializationObject.generateMipMaps = this._generateMipMaps;
  119461. return serializationObject;
  119462. };
  119463. /**
  119464. * Creates a NoiseProceduralTexture from parsed noise procedural texture data
  119465. * @param parsedTexture defines parsed texture data
  119466. * @param scene defines the current scene
  119467. * @param rootUrl defines the root URL containing noise procedural texture information
  119468. * @returns a parsed NoiseProceduralTexture
  119469. */
  119470. NoiseProceduralTexture.Parse = function (parsedTexture, scene, rootUrl) {
  119471. var texture = new NoiseProceduralTexture(parsedTexture.name, parsedTexture.size, scene, undefined, parsedTexture.generateMipMaps);
  119472. texture.brightness = parsedTexture.brightness;
  119473. texture.octaves = parsedTexture.octaves;
  119474. texture.persistence = parsedTexture.persistence;
  119475. texture.animationSpeedFactor = parsedTexture.animationSpeedFactor;
  119476. return texture;
  119477. };
  119478. return NoiseProceduralTexture;
  119479. }(BABYLON.ProceduralTexture));
  119480. BABYLON.NoiseProceduralTexture = NoiseProceduralTexture;
  119481. })(BABYLON || (BABYLON = {}));
  119482. //# sourceMappingURL=babylon.noiseProceduralTexture.js.map
  119483. var __assign = (this && this.__assign) || function () {
  119484. __assign = Object.assign || function(t) {
  119485. for (var s, i = 1, n = arguments.length; i < n; i++) {
  119486. s = arguments[i];
  119487. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  119488. t[p] = s[p];
  119489. }
  119490. return t;
  119491. };
  119492. return __assign.apply(this, arguments);
  119493. };
  119494. var BABYLON;
  119495. (function (BABYLON) {
  119496. /**
  119497. * This can helps recording videos from BabylonJS.
  119498. * This is based on the available WebRTC functionalities of the browser.
  119499. *
  119500. * @see http://doc.babylonjs.com/how_to/render_scene_on_a_video
  119501. */
  119502. var VideoRecorder = /** @class */ (function () {
  119503. /**
  119504. * Create a new VideoCapture object which can help converting what you see in Babylon to
  119505. * a video file.
  119506. * @param engine Defines the BabylonJS Engine you wish to record
  119507. * @param options Defines options that can be used to customized the capture
  119508. */
  119509. function VideoRecorder(engine, options) {
  119510. if (options === void 0) { options = null; }
  119511. if (!VideoRecorder.IsSupported(engine)) {
  119512. throw "Your browser does not support recording so far.";
  119513. }
  119514. var canvas = engine.getRenderingCanvas();
  119515. if (!canvas) {
  119516. throw "The babylon engine must have a canvas to be recorded";
  119517. }
  119518. this._canvas = canvas;
  119519. this._canvas.isRecording = false;
  119520. this._options = __assign({}, VideoRecorder._defaultOptions, options);
  119521. var stream = this._canvas.captureStream(this._options.fps);
  119522. this._mediaRecorder = new MediaRecorder(stream, { mimeType: this._options.mimeType });
  119523. this._mediaRecorder.ondataavailable = this._handleDataAvailable.bind(this);
  119524. this._mediaRecorder.onerror = this._handleError.bind(this);
  119525. this._mediaRecorder.onstop = this._handleStop.bind(this);
  119526. }
  119527. /**
  119528. * Returns wehther or not the VideoRecorder is available in your browser.
  119529. * @param engine Defines the Babylon Engine to check the support for
  119530. * @returns true if supported otherwise false
  119531. */
  119532. VideoRecorder.IsSupported = function (engine) {
  119533. var canvas = engine.getRenderingCanvas();
  119534. return (!!canvas && typeof canvas.captureStream === "function");
  119535. };
  119536. Object.defineProperty(VideoRecorder.prototype, "isRecording", {
  119537. /**
  119538. * True wether a recording is already in progress.
  119539. */
  119540. get: function () {
  119541. return !!this._canvas && this._canvas.isRecording;
  119542. },
  119543. enumerable: true,
  119544. configurable: true
  119545. });
  119546. /**
  119547. * Stops the current recording before the default capture timeout passed in the startRecording
  119548. * functions.
  119549. */
  119550. VideoRecorder.prototype.stopRecording = function () {
  119551. if (!this._canvas || !this._mediaRecorder) {
  119552. return;
  119553. }
  119554. if (!this.isRecording) {
  119555. return;
  119556. }
  119557. this._canvas.isRecording = false;
  119558. this._mediaRecorder.stop();
  119559. };
  119560. /**
  119561. * Starts recording the canvas for a max duration specified in parameters.
  119562. * @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.
  119563. * @param maxDuration Defines the maximum recording time in seconds.
  119564. * It default to 7 seconds. A value of zero will not stop automatically, you would need to call stopRecording manually.
  119565. * @return a promise callback at the end of the recording with the video data in Blob.
  119566. */
  119567. VideoRecorder.prototype.startRecording = function (fileName, maxDuration) {
  119568. var _this = this;
  119569. if (fileName === void 0) { fileName = "babylonjs.webm"; }
  119570. if (maxDuration === void 0) { maxDuration = 7; }
  119571. if (!this._canvas || !this._mediaRecorder) {
  119572. throw "Recorder has already been disposed";
  119573. }
  119574. if (this.isRecording) {
  119575. throw "Recording already in progress";
  119576. }
  119577. if (maxDuration > 0) {
  119578. setTimeout(function () {
  119579. _this.stopRecording();
  119580. }, maxDuration * 1000);
  119581. }
  119582. this._fileName = fileName;
  119583. this._recordedChunks = [];
  119584. this._resolve = null;
  119585. this._reject = null;
  119586. this._canvas.isRecording = true;
  119587. this._mediaRecorder.start(this._options.recordChunckSize);
  119588. return new Promise(function (resolve, reject) {
  119589. _this._resolve = resolve;
  119590. _this._reject = reject;
  119591. });
  119592. };
  119593. /**
  119594. * Releases internal resources used during the recording.
  119595. */
  119596. VideoRecorder.prototype.dispose = function () {
  119597. this._canvas = null;
  119598. this._mediaRecorder = null;
  119599. this._recordedChunks = [];
  119600. this._fileName = null;
  119601. this._resolve = null;
  119602. this._reject = null;
  119603. };
  119604. VideoRecorder.prototype._handleDataAvailable = function (event) {
  119605. if (event.data.size > 0) {
  119606. this._recordedChunks.push(event.data);
  119607. }
  119608. };
  119609. VideoRecorder.prototype._handleError = function (event) {
  119610. this.stopRecording();
  119611. if (this._reject) {
  119612. this._reject(event.error);
  119613. }
  119614. else {
  119615. throw new event.error();
  119616. }
  119617. };
  119618. VideoRecorder.prototype._handleStop = function () {
  119619. this.stopRecording();
  119620. var superBuffer = new Blob(this._recordedChunks);
  119621. if (this._resolve) {
  119622. this._resolve(superBuffer);
  119623. }
  119624. window.URL.createObjectURL(superBuffer);
  119625. if (this._fileName) {
  119626. BABYLON.Tools.Download(superBuffer, this._fileName);
  119627. }
  119628. };
  119629. VideoRecorder._defaultOptions = {
  119630. mimeType: "video/webm",
  119631. fps: 25,
  119632. recordChunckSize: 3000
  119633. };
  119634. return VideoRecorder;
  119635. }());
  119636. BABYLON.VideoRecorder = VideoRecorder;
  119637. })(BABYLON || (BABYLON = {}));
  119638. //# sourceMappingURL=babylon.videoRecorder.js.map
  119639. var BABYLON;
  119640. (function (BABYLON) {
  119641. BABYLON.Scene.prototype.createDefaultLight = function (replace) {
  119642. if (replace === void 0) { replace = false; }
  119643. // Dispose existing light in replace mode.
  119644. if (replace) {
  119645. if (this.lights) {
  119646. for (var i = 0; i < this.lights.length; i++) {
  119647. this.lights[i].dispose();
  119648. }
  119649. }
  119650. }
  119651. // Light
  119652. if (this.lights.length === 0) {
  119653. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  119654. }
  119655. };
  119656. BABYLON.Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  119657. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  119658. if (replace === void 0) { replace = false; }
  119659. if (attachCameraControls === void 0) { attachCameraControls = false; }
  119660. // Dispose existing camera in replace mode.
  119661. if (replace) {
  119662. if (this.activeCamera) {
  119663. this.activeCamera.dispose();
  119664. this.activeCamera = null;
  119665. }
  119666. }
  119667. // Camera
  119668. if (!this.activeCamera) {
  119669. var worldExtends = this.getWorldExtends();
  119670. var worldSize = worldExtends.max.subtract(worldExtends.min);
  119671. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  119672. var camera;
  119673. var radius = worldSize.length() * 1.5;
  119674. // empty scene scenario!
  119675. if (!isFinite(radius)) {
  119676. radius = 1;
  119677. worldCenter.copyFromFloats(0, 0, 0);
  119678. }
  119679. if (createArcRotateCamera) {
  119680. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  119681. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  119682. arcRotateCamera.wheelPrecision = 100 / radius;
  119683. camera = arcRotateCamera;
  119684. }
  119685. else {
  119686. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  119687. freeCamera.setTarget(worldCenter);
  119688. camera = freeCamera;
  119689. }
  119690. camera.minZ = radius * 0.01;
  119691. camera.maxZ = radius * 1000;
  119692. camera.speed = radius * 0.2;
  119693. this.activeCamera = camera;
  119694. var canvas = this.getEngine().getRenderingCanvas();
  119695. if (attachCameraControls && canvas) {
  119696. camera.attachControl(canvas);
  119697. }
  119698. }
  119699. };
  119700. BABYLON.Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  119701. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  119702. if (replace === void 0) { replace = false; }
  119703. if (attachCameraControls === void 0) { attachCameraControls = false; }
  119704. this.createDefaultLight(replace);
  119705. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  119706. };
  119707. BABYLON.Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur, setGlobalEnvTexture) {
  119708. if (pbr === void 0) { pbr = false; }
  119709. if (scale === void 0) { scale = 1000; }
  119710. if (blur === void 0) { blur = 0; }
  119711. if (setGlobalEnvTexture === void 0) { setGlobalEnvTexture = true; }
  119712. if (!environmentTexture) {
  119713. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  119714. return null;
  119715. }
  119716. if (setGlobalEnvTexture) {
  119717. if (environmentTexture) {
  119718. this.environmentTexture = environmentTexture;
  119719. }
  119720. }
  119721. // Skybox
  119722. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  119723. if (pbr) {
  119724. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  119725. hdrSkyboxMaterial.backFaceCulling = false;
  119726. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  119727. if (hdrSkyboxMaterial.reflectionTexture) {
  119728. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  119729. }
  119730. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  119731. hdrSkyboxMaterial.disableLighting = true;
  119732. hdrSkyboxMaterial.twoSidedLighting = true;
  119733. hdrSkybox.infiniteDistance = true;
  119734. hdrSkybox.material = hdrSkyboxMaterial;
  119735. }
  119736. else {
  119737. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  119738. skyboxMaterial.backFaceCulling = false;
  119739. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  119740. if (skyboxMaterial.reflectionTexture) {
  119741. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  119742. }
  119743. skyboxMaterial.disableLighting = true;
  119744. hdrSkybox.infiniteDistance = true;
  119745. hdrSkybox.material = skyboxMaterial;
  119746. }
  119747. return hdrSkybox;
  119748. };
  119749. BABYLON.Scene.prototype.createDefaultEnvironment = function (options) {
  119750. if (BABYLON.EnvironmentHelper) {
  119751. return new BABYLON.EnvironmentHelper(options, this);
  119752. }
  119753. return null;
  119754. };
  119755. BABYLON.Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  119756. if (webVROptions === void 0) { webVROptions = {}; }
  119757. return new BABYLON.VRExperienceHelper(this, webVROptions);
  119758. };
  119759. BABYLON.Scene.prototype.createDefaultXRExperienceAsync = function () {
  119760. var _this = this;
  119761. return BABYLON.WebXRExperienceHelper.CreateAsync(this).then(function (helper) {
  119762. var outputCanvas = new BABYLON.WebXRManagedOutputCanvas(helper);
  119763. return BABYLON.WebXREnterExitUI.CreateAsync(_this, helper, { outputCanvasContext: outputCanvas.canvasContext })
  119764. .then(function (ui) {
  119765. new BABYLON.WebXRInput(helper);
  119766. return helper;
  119767. });
  119768. });
  119769. };
  119770. })(BABYLON || (BABYLON = {}));
  119771. //# sourceMappingURL=babylon.sceneHelpers.js.map
  119772. 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 RGBDREFRACTION\nenvironmentRefraction.rgb=fromRGBD(environmentRefraction);\n#endif\n#ifdef GAMMAREFRACTION\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}\n","rgbdEncodePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<helperFunctions>\nvoid main(void) \n{\ngl_FragColor=toRGBD(texture2D(textureSampler,vUV).rgb);\n}","rgbdDecodePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<helperFunctions>\nvoid main(void) \n{\ngl_FragColor=vec4(fromRGBD(texture2D(textureSampler,vUV)),1.0);\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute float angle;\nattribute vec2 size;\n#ifdef ANIMATESHEET \nattribute float cellIndex;\n#endif\n#ifndef BILLBOARD \nattribute vec3 direction;\n#endif\n#ifdef BILLBOARDSTRETCHED\nattribute vec3 direction; \n#endif\n#ifdef RAMPGRADIENT\nattribute vec4 remapData;\n#endif\nattribute vec2 offset;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec2 translationPivot;\n#ifdef ANIMATESHEET \nuniform vec3 particlesInfos; \n#endif\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef RAMPGRADIENT\nvarying vec4 remapRanges;\n#endif\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4)\nuniform mat4 invView;\n#endif\n#include<clipPlaneVertexDeclaration>\n#ifdef BILLBOARD\nuniform vec3 eyePosition; \n#endif\nvec3 rotate(vec3 yaxis,vec3 rotatedCorner) {\nvec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));\nvec3 zaxis=normalize(cross(yaxis,xaxis));\nvec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);\nvec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);\nvec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner; \n}\n#ifdef BILLBOARDSTRETCHED\nvec3 rotateAlign(vec3 toCamera,vec3 rotatedCorner) {\nvec3 normalizedToCamera=normalize(toCamera);\nvec3 normalizedCrossDirToCamera=normalize(cross(normalize(direction),normalizedToCamera));\nvec3 crossProduct=normalize(cross(normalizedToCamera,normalizedCrossDirToCamera));\nvec3 row0=vec3(normalizedCrossDirToCamera.x,normalizedCrossDirToCamera.y,normalizedCrossDirToCamera.z);\nvec3 row1=vec3(crossProduct.x,crossProduct.y,crossProduct.z);\nvec3 row2=vec3(normalizedToCamera.x,normalizedToCamera.y,normalizedToCamera.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner; \n}\n#endif\nvoid main(void) { \nvec2 cornerPos;\ncornerPos=(vec2(offset.x-0.5,offset.y-0.5)-translationPivot)*size+translationPivot;\n#ifdef BILLBOARD \n\nvec3 rotatedCorner;\n#ifdef BILLBOARDY \nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=position-eyePosition;\nyaxis.y=0.;\nvec3 worldPos=rotate(normalize(yaxis),rotatedCorner);\nvec3 viewPos=(view*vec4(worldPos,1.0)).xyz; \n#elif defined(BILLBOARDSTRETCHED)\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\nvec3 toCamera=position-eyePosition; \nvec3 worldPos=rotateAlign(toCamera,rotatedCorner);\nvec3 viewPos=(view*vec4(worldPos,1.0)).xyz; \n#else\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\nvec3 viewPos=(view*vec4(position,1.0)).xyz+rotatedCorner; \n#endif\n#ifdef RAMPGRADIENT\nremapRanges=remapData;\n#endif\n\ngl_Position=projection*vec4(viewPos,1.0); \n#else\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=normalize(direction);\nvec3 worldPos=rotate(yaxis,rotatedCorner);\ngl_Position=projection*view*vec4(worldPos,1.0); \n#endif \nvColor=color;\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/particlesInfos.z);\nfloat columnOffset=cellIndex-rowOffset*particlesInfos.z;\nvec2 uvScale=particlesInfos.xy;\nvec2 uvOffset=vec2(offset.x ,1.0-offset.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=offset;\n#endif\n\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4)\nvec4 worldPos=invView*vec4(viewPos,1.0);\n#endif\n#include<clipPlaneVertex>\n}","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#include<clipPlaneFragmentDeclaration>\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n#ifdef RAMPGRADIENT\nvarying vec4 remapRanges;\nuniform sampler2D rampSampler;\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec4 textureColor=texture2D(diffuseSampler,vUV);\nvec4 baseColor=(textureColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n#ifdef RAMPGRADIENT\nfloat alpha=baseColor.a;\nfloat remappedColorIndex=clamp((alpha-remapRanges.x)/remapRanges.y,0.0,1.0);\nvec4 rampColor=texture2D(rampSampler,vec2(1.0-remappedColorIndex,0.));\nbaseColor.rgb*=rampColor.rgb;\n\nfloat finalAlpha=baseColor.a;\nbaseColor.a=clamp((alpha*rampColor.a-remapRanges.z)/remapRanges.w,0.0,1.0);\n#endif\n#ifdef BLENDMULTIPLYMODE\nfloat sourceAlpha=vColor.a*textureColor.a;\nbaseColor.rgb=baseColor.rgb*sourceAlpha+vec3(1.0)*(1.0-sourceAlpha);\n#endif\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\nbaseColor.rgb=toLinearSpace(baseColor.rgb);\n#else\n#ifdef IMAGEPROCESSING\nbaseColor.rgb=toLinearSpace(baseColor.rgb);\nbaseColor=applyImageProcessing(baseColor);\n#endif\n#endif\ngl_FragColor=baseColor;\n}","colorVertexShader":"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}","colorPixelShader":"#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}","gpuRenderParticlesVertexShader":"#version 300 es\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec2 translationPivot;\n\nin vec3 position;\nin float age;\nin float life;\nin vec3 size;\n#ifndef BILLBOARD\nin vec3 initialDirection;\n#endif\n#ifdef BILLBOARDSTRETCHED\nin vec3 direction;\n#endif\nin float angle;\n#ifdef ANIMATESHEET\nin float cellIndex;\n#endif\nin vec2 offset;\nin vec2 uv;\nout vec2 vUV;\nout vec4 vColor;\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4)\nuniform mat4 invView;\n#endif\n#include<clipPlaneVertexDeclaration2>\n#ifdef COLORGRADIENTS\nuniform sampler2D colorGradientSampler;\n#else\nuniform vec4 colorDead;\nin vec4 color;\n#endif\n#ifdef ANIMATESHEET\nuniform vec3 sheetInfos;\n#endif\n#ifdef BILLBOARD\nuniform vec3 eyePosition; \n#endif\nvec3 rotate(vec3 yaxis,vec3 rotatedCorner) {\nvec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));\nvec3 zaxis=normalize(cross(yaxis,xaxis));\nvec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);\nvec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);\nvec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner;\n}\n#ifdef BILLBOARDSTRETCHED\nvec3 rotateAlign(vec3 toCamera,vec3 rotatedCorner) {\nvec3 normalizedToCamera=normalize(toCamera);\nvec3 normalizedCrossDirToCamera=normalize(cross(normalize(direction),normalizedToCamera));\nvec3 crossProduct=normalize(cross(normalizedToCamera,normalizedCrossDirToCamera));\nvec3 row0=vec3(normalizedCrossDirToCamera.x,normalizedCrossDirToCamera.y,normalizedCrossDirToCamera.z);\nvec3 row1=vec3(crossProduct.x,crossProduct.y,crossProduct.z);\nvec3 row2=vec3(normalizedToCamera.x,normalizedToCamera.y,normalizedToCamera.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner; \n}\n#endif\nvoid main() {\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/sheetInfos.z);\nfloat columnOffset=cellIndex-rowOffset*sheetInfos.z;\nvec2 uvScale=sheetInfos.xy;\nvec2 uvOffset=vec2(uv.x ,1.0-uv.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else \nvUV=uv;\n#endif\nfloat ratio=age/life;\n#ifdef COLORGRADIENTS\nvColor=texture(colorGradientSampler,vec2(ratio,0));\n#else\nvColor=color*vec4(1.0-ratio)+colorDead*vec4(ratio);\n#endif\nvec2 cornerPos=(offset-translationPivot)*size.yz*size.x+translationPivot;\n#ifdef BILLBOARD\nvec4 rotatedCorner;\nrotatedCorner.w=0.;\n#ifdef BILLBOARDY \nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=position-eyePosition;\nyaxis.y=0.;\nvec3 worldPos=rotate(normalize(yaxis),rotatedCorner.xyz);\nvec4 viewPosition=(view*vec4(worldPos,1.0)); \n#elif defined(BILLBOARDSTRETCHED)\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\nvec3 toCamera=position-eyePosition; \nvec3 worldPos=rotateAlign(toCamera,rotatedCorner.xyz);\nvec4 viewPosition=(view*vec4(worldPos,1.0)); \n#else\n\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nvec4 viewPosition=view*vec4(position,1.0)+rotatedCorner;\n#endif\n#else\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=0.;\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nvec3 yaxis=normalize(initialDirection);\nvec3 worldPos=rotate(yaxis,rotatedCorner);\n\nvec4 viewPosition=view*vec4(worldPos,1.0); \n#endif\ngl_Position=projection*viewPosition;\n\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4)\nvec4 worldPos=invView*viewPosition;\n#endif \n#include<clipPlaneVertex>\n}","gpuRenderParticlesPixelShader":"#version 300 es\nuniform sampler2D textureSampler;\nin vec2 vUV;\nin vec4 vColor;\nout vec4 outFragColor;\n#include<clipPlaneFragmentDeclaration2> \n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main() {\n#include<clipPlaneFragment> \nvec4 textureColor=texture(textureSampler,vUV);\noutFragColor=textureColor*vColor;\n#ifdef BLENDMULTIPLYMODE\nfloat alpha=vColor.a*textureColor.a;\noutFragColor.rgb=outFragColor.rgb*alpha+vec3(1.0)*(1.0-alpha); \n#endif \n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\noutFragColor.rgb=toLinearSpace(outFragColor.rgb);\n#else\n#ifdef IMAGEPROCESSING\noutFragColor.rgb=toLinearSpace(outFragColor.rgb);\noutFragColor=applyImageProcessing(outFragColor);\n#endif\n#endif\n}\n","gpuUpdateParticlesVertexShader":"#version 300 es\n#define PI 3.14159\nuniform float currentCount;\nuniform float timeDelta;\nuniform float stopFactor;\nuniform mat4 emitterWM;\nuniform vec2 lifeTime;\nuniform vec2 emitPower;\nuniform vec2 sizeRange;\nuniform vec4 scaleRange;\n#ifndef COLORGRADIENTS\nuniform vec4 color1;\nuniform vec4 color2;\n#endif\nuniform vec3 gravity;\nuniform sampler2D randomSampler;\nuniform sampler2D randomSampler2;\nuniform vec4 angleRange;\n#ifdef BOXEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\nuniform vec3 minEmitBox;\nuniform vec3 maxEmitBox;\n#endif\n#ifdef POINTEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#endif\n#ifdef HEMISPHERICEMITTER\nuniform float radius;\nuniform float radiusRange;\nuniform float directionRandomizer;\n#endif\n#ifdef SPHEREEMITTER\nuniform float radius;\nuniform float radiusRange;\n#ifdef DIRECTEDSPHEREEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CYLINDEREMITTER\nuniform float radius;\nuniform float height;\nuniform float radiusRange;\n#ifdef DIRECTEDCYLINDEREMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CONEEMITTER\nuniform vec2 radius;\nuniform float coneAngle;\nuniform vec2 height;\nuniform float directionRandomizer;\n#endif\n\nin vec3 position;\nin float age;\nin float life;\nin vec4 seed;\nin vec3 size;\n#ifndef COLORGRADIENTS\nin vec4 color;\n#endif\nin vec3 direction;\n#ifndef BILLBOARD\nin vec3 initialDirection;\n#endif\n#ifdef ANGULARSPEEDGRADIENTS\nin float angle;\n#else\nin vec2 angle;\n#endif\n#ifdef ANIMATESHEET\nin float cellIndex;\n#ifdef ANIMATESHEETRANDOMSTART\nin float cellStartOffset;\n#endif\n#endif\n#ifdef NOISE\nin vec3 noiseCoordinates1;\nin vec3 noiseCoordinates2;\n#endif\n\nout vec3 outPosition;\nout float outAge;\nout float outLife;\nout vec4 outSeed;\nout vec3 outSize;\n#ifndef COLORGRADIENTS\nout vec4 outColor;\n#endif\nout vec3 outDirection;\n#ifndef BILLBOARD\nout vec3 outInitialDirection;\n#endif\n#ifdef ANGULARSPEEDGRADIENTS\nout float outAngle;\n#else\nout vec2 outAngle;\n#endif\n#ifdef ANIMATESHEET\nout float outCellIndex;\n#ifdef ANIMATESHEETRANDOMSTART\nout float outCellStartOffset;\n#endif\n#endif\n#ifdef NOISE\nout vec3 outNoiseCoordinates1;\nout vec3 outNoiseCoordinates2;\n#endif\n#ifdef SIZEGRADIENTS\nuniform sampler2D sizeGradientSampler;\n#endif \n#ifdef ANGULARSPEEDGRADIENTS\nuniform sampler2D angularSpeedGradientSampler;\n#endif \n#ifdef VELOCITYGRADIENTS\nuniform sampler2D velocityGradientSampler;\n#endif\n#ifdef LIMITVELOCITYGRADIENTS\nuniform sampler2D limitVelocityGradientSampler;\nuniform float limitVelocityDamping;\n#endif\n#ifdef DRAGGRADIENTS\nuniform sampler2D dragGradientSampler;\n#endif\n#ifdef NOISE\nuniform vec3 noiseStrength;\nuniform sampler2D noiseSampler;\n#endif\n#ifdef ANIMATESHEET\nuniform vec3 cellInfos;\n#endif\nvec3 getRandomVec3(float offset) {\nreturn texture(randomSampler2,vec2(float(gl_VertexID)*offset/currentCount,0)).rgb;\n}\nvec4 getRandomVec4(float offset) {\nreturn texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0));\n}\nvoid main() {\nfloat newAge=age+timeDelta; \n\nif (newAge>=life && stopFactor != 0.) {\nvec3 position;\nvec3 direction;\n\nvec4 randoms=getRandomVec4(seed.x);\n\noutLife=lifeTime.x+(lifeTime.y-lifeTime.x)*randoms.r;\noutAge=mod(newAge,outLife);\n\noutSeed=seed;\n\n#ifdef SIZEGRADIENTS \noutSize.x=texture(sizeGradientSampler,vec2(0,0)).r;\n#else\noutSize.x=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g;\n#endif\noutSize.y=scaleRange.x+(scaleRange.y-scaleRange.x)*randoms.b;\noutSize.z=scaleRange.z+(scaleRange.w-scaleRange.z)*randoms.a; \n#ifndef COLORGRADIENTS\n\noutColor=color1+(color2-color1)*randoms.b;\n#endif\n\n#ifndef ANGULARSPEEDGRADIENTS \noutAngle.y=angleRange.x+(angleRange.y-angleRange.x)*randoms.a;\noutAngle.x=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\n#else\noutAngle=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\n#endif \n\n#ifdef POINTEMITTER\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\nposition=vec3(0,0,0);\ndirection=direction1+(direction2-direction1)*randoms3;\n#elif defined(BOXEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\nposition=minEmitBox+(maxEmitBox-minEmitBox)*randoms2;\ndirection=direction1+(direction2-direction1)*randoms3; \n#elif defined(HEMISPHERICEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\n\nfloat phi=2.0*PI*randoms2.x;\nfloat theta=acos(2.0*randoms2.y-1.0);\nfloat randX=cos(phi)*sin(theta);\nfloat randY=cos(theta);\nfloat randZ=sin(phi)*sin(theta);\nposition=(radius-(radius*radiusRange*randoms2.z))*vec3(randX,abs(randY),randZ);\ndirection=position+directionRandomizer*randoms3; \n#elif defined(SPHEREEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\n\nfloat phi=2.0*PI*randoms2.x;\nfloat theta=acos(2.0*randoms2.y-1.0);\nfloat randX=cos(phi)*sin(theta);\nfloat randY=cos(theta);\nfloat randZ=sin(phi)*sin(theta);\nposition=(radius-(radius*radiusRange*randoms2.z))*vec3(randX,randY,randZ);\n#ifdef DIRECTEDSPHEREEMITTER\ndirection=direction1+(direction2-direction1)*randoms3;\n#else\n\ndirection=position+directionRandomizer*randoms3;\n#endif\n#elif defined(CYLINDEREMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\n\nfloat yPos=(randoms2.x-0.5)*height;\nfloat angle=randoms2.y*PI*2.;\nfloat inverseRadiusRangeSquared=((1.-radiusRange)*(1.-radiusRange));\nfloat positionRadius=radius*sqrt(inverseRadiusRangeSquared+(randoms2.z*(1.-inverseRadiusRangeSquared)));\nfloat xPos=positionRadius*cos(angle);\nfloat zPos=positionRadius*sin(angle);\nposition=vec3(xPos,yPos,zPos);\n#ifdef DIRECTEDCYLINDEREMITTER\ndirection=direction1+(direction2-direction1)*randoms3;\n#else\n\nangle=angle+((randoms3.x-0.5)*PI);\ndirection=vec3(cos(angle),randoms3.y-0.5,sin(angle));\ndirection=normalize(direction);\n#endif\n#elif defined(CONEEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nfloat s=2.0*PI*randoms2.x;\n#ifdef CONEEMITTERSPAWNPOINT\nfloat h=0.00001;\n#else\nfloat h=randoms2.y*height.y;\n\nh=1.-h*h; \n#endif\nfloat lRadius=radius.x-radius.x*randoms2.z*radius.y;\nlRadius=lRadius*h;\nfloat randX=lRadius*sin(s);\nfloat randZ=lRadius*cos(s);\nfloat randY=h*height.x;\nposition=vec3(randX,randY,randZ); \n\nif (abs(cos(coneAngle)) == 1.0) {\ndirection=vec3(0.,1.0,0.);\n} else {\nvec3 randoms3=getRandomVec3(seed.z);\ndirection=position+directionRandomizer*randoms3;\n}\n#else \n\nposition=vec3(0.,0.,0.);\n\ndirection=2.0*(getRandomVec3(seed.w)-vec3(0.5,0.5,0.5));\n#endif\nfloat power=emitPower.x+(emitPower.y-emitPower.x)*randoms.a;\noutPosition=(emitterWM*vec4(position,1.)).xyz;\nvec3 initial=(emitterWM*vec4(direction,0.)).xyz;\noutDirection=initial*power;\n#ifndef BILLBOARD \noutInitialDirection=initial;\n#endif\n#ifdef ANIMATESHEET \noutCellIndex=cellInfos.x;\n#ifdef ANIMATESHEETRANDOMSTART\noutCellStartOffset=randoms.a*outLife;\n#endif \n#endif\n#ifdef NOISE\noutNoiseCoordinates1=noiseCoordinates1;\noutNoiseCoordinates2=noiseCoordinates2;\n#endif\n} else {\nfloat directionScale=timeDelta;\noutAge=newAge;\nfloat ageGradient=newAge/life;\n#ifdef VELOCITYGRADIENTS\ndirectionScale*=texture(velocityGradientSampler,vec2(ageGradient,0)).r;\n#endif\n#ifdef DRAGGRADIENTS\ndirectionScale*=1.0-texture(dragGradientSampler,vec2(ageGradient,0)).r;\n#endif\noutPosition=position+direction*directionScale;\noutLife=life;\noutSeed=seed;\n#ifndef COLORGRADIENTS \noutColor=color;\n#endif\n#ifdef SIZEGRADIENTS\noutSize.x=texture(sizeGradientSampler,vec2(ageGradient,0)).r;\noutSize.yz=size.yz;\n#else\noutSize=size;\n#endif \n#ifndef BILLBOARD \noutInitialDirection=initialDirection;\n#endif\nvec3 updatedDirection=direction+gravity*timeDelta;\n#ifdef LIMITVELOCITYGRADIENTS\nfloat limitVelocity=texture(limitVelocityGradientSampler,vec2(ageGradient,0)).r;\nfloat currentVelocity=length(updatedDirection);\nif (currentVelocity>limitVelocity) {\nupdatedDirection=updatedDirection*limitVelocityDamping;\n}\n#endif\noutDirection=updatedDirection;\n#ifdef NOISE\nvec3 localPosition=outPosition-emitterWM[3].xyz;\nfloat fetchedR=texture(noiseSampler,vec2(noiseCoordinates1.x,noiseCoordinates1.y)*vec2(0.5)+vec2(0.5)).r;\nfloat fetchedG=texture(noiseSampler,vec2(noiseCoordinates1.z,noiseCoordinates2.x)*vec2(0.5)+vec2(0.5)).r;\nfloat fetchedB=texture(noiseSampler,vec2(noiseCoordinates2.y,noiseCoordinates2.z)*vec2(0.5)+vec2(0.5)).r;\nvec3 force=vec3(2.*fetchedR-1.,2.*fetchedG-1.,2.*fetchedB-1.)*noiseStrength;\noutDirection=outDirection+force*timeDelta;\noutNoiseCoordinates1=noiseCoordinates1;\noutNoiseCoordinates2=noiseCoordinates2;\n#endif \n#ifdef ANGULARSPEEDGRADIENTS\nfloat angularSpeed=texture(angularSpeedGradientSampler,vec2(ageGradient,0)).r;\noutAngle=angle+angularSpeed*timeDelta;\n#else\noutAngle=vec2(angle.x+angle.y*timeDelta,angle.y);\n#endif\n#ifdef ANIMATESHEET \nfloat offsetAge=outAge;\nfloat dist=cellInfos.y-cellInfos.x;\n#ifdef ANIMATESHEETRANDOMSTART\noutCellStartOffset=cellStartOffset;\noffsetAge+=cellStartOffset;\n#endif \nfloat ratio=clamp(mod(offsetAge*cellInfos.z,life)/life,0.,1.0);\noutCellIndex=float(int(cellInfos.x+ratio*dist));\n#endif\n}\n}","gpuUpdateParticlesPixelShader":"#version 300 es\nvoid main() {\ndiscard;\n}\n","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","passCubePixelShader":"\nvarying vec2 vUV;\nuniform samplerCube textureSampler;\nvoid main(void) \n{\nvec2 uv=vUV*2.0-1.0;\n#ifdef POSITIVEX\ngl_FragColor=textureCube(textureSampler,vec3(1.001,uv.y,uv.x));\n#endif\n#ifdef NEGATIVEX\ngl_FragColor=textureCube(textureSampler,vec3(-1.001,uv.y,uv.x));\n#endif\n#ifdef POSITIVEY\ngl_FragColor=textureCube(textureSampler,vec3(uv.y,1.001,uv.x));\n#endif\n#ifdef NEGATIVEY\ngl_FragColor=textureCube(textureSampler,vec3(uv.y,-1.001,uv.x));\n#endif\n#ifdef POSITIVEZ\ngl_FragColor=textureCube(textureSampler,vec3(uv,1.001));\n#endif\n#ifdef NEGATIVEZ\ngl_FragColor=textureCube(textureSampler,vec3(uv,-1.001));\n#endif\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\nuniform vec3 lightData;\n#endif\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\n#include<helperFunctions>\nuniform mat4 viewProjection;\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\n\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvec3 worldNor=normalize(normalWorld*normal);\n#ifdef DIRECTIONINLIGHTDATA\nvec3 worldLightDir=normalize(-lightData.xyz);\n#else\nvec3 directionToLight=lightData.xyz-worldPos.xyz;\nvec3 worldLightDir=normalize(directionToLight);\n#endif\nfloat ndl=dot(worldNor,worldLightDir);\nfloat sinNL=sqrt(1.0-ndl*ndl);\nfloat normalBias=biasAndScale.y*sinNL;\nworldPos.xyz-=worldNor*normalBias;\n#endif\n\ngl_Position=viewProjection*worldPos;\n#ifdef DEPTHTEXTURE\n\ngl_Position.z+=biasAndScale.x*gl_Position.w;\n#endif\n\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y))+biasAndScale.x;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","shadowMapPixelShader":"#ifndef FLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=vDepthMetric;\n#ifdef ESM\ndepth=clamp(exp(-min(87.,biasAndScale.z*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(vDepthMetric,vDepthMetric*vDepthMetric,0.0,1.0);\n}","geometryVertexShader":"precision highp float;\nprecision highp int;\n#include<bonesDeclaration>\n#include<instancesDeclaration>\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef VELOCITY\nuniform mat4 previousWorldViewProjection;\nvarying vec4 vCurrentPosition;\nvarying vec4 vPreviousPosition;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\n#ifdef VELOCITY\nvCurrentPosition=viewProjection*finalWorld*vec4(position,1.0);\nvPreviousPosition=previousWorldViewProjection*vec4(position,1.0);\n#endif\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","geometryPixelShader":"#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef VELOCITY\nvarying vec4 vCurrentPosition;\nvarying vec4 vPreviousPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<mrtFragmentDeclaration>[RENDER_TARGET_COUNT]\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[POSITION_INDEX]=vec4(vPosition,1.0);\n#endif\n#ifdef VELOCITY\nvec2 a=(vCurrentPosition.xy/vCurrentPosition.w)*0.5+0.5;\nvec2 b=(vPreviousPosition.xy/vPreviousPosition.w)*0.5+0.5;\nvec2 velocity=(a-b)*0.5+0.5;\nvelocity*=0.5+0.5;\nvelocity=vec2(pow(velocity.x,3.0),pow(velocity.y,3.0));\ngl_FragData[VELOCITY_INDEX]=vec4(velocity,0.0,1.0);\n#endif\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n","ssao2PixelShader":"\nprecision highp float;\nuniform sampler2D textureSampler;\nuniform float near;\nuniform float far;\nuniform float radius;\nfloat scales[16]=float[16](\n0.1,\n0.11406250000000001,\n0.131640625,\n0.15625,\n0.187890625,\n0.2265625,\n0.272265625,\n0.325,\n0.384765625,\n0.4515625,\n0.525390625,\n0.60625,\n0.694140625,\n0.7890625,\n0.891015625,\n1.0\n);\nvarying vec2 vUV;\nfloat perspectiveDepthToViewZ( const in float invClipZ,const in float near,const in float far ) {\nreturn ( near*far )/( ( far-near )*invClipZ-far );\n}\nfloat viewZToPerspectiveDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( near*far/viewZ+far)/( far-near );\n}\nfloat viewZToOrthographicDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( viewZ+near )/( near-far );\n}\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform sampler2D normalSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float base;\nuniform float xViewport;\nuniform float yViewport;\nuniform float maxZ;\nuniform float minZAspect;\nuniform vec2 texelSize;\nuniform mat4 projection;\nvoid main()\n{\nvec3 random=texture2D(randomSampler,vUV*randTextureTiles).rgb;\nfloat depth=texture2D(textureSampler,vUV).r;\nfloat depthSign=depth/abs(depth);\ndepth=depth*depthSign;\nvec3 normal=texture2D(normalSampler,vUV).rgb; \nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign);\nvec3 origin=vViewRay*depth;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\n\nfloat dotProduct=dot(rvec,normal);\nrvec=1.0-abs(dotProduct)>1e-2 ? rvec : vec3(-rvec.y,0.0,rvec.x);\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=scales[(i+int(random.x*16.0)) % 16]*tbn*sampleSphere[(i+int(random.y*16.0)) % 16];\nsamplePosition=samplePosition*correctedRadius+origin;\n\nvec4 offset=vec4(samplePosition,1.0);\noffset=projection*offset;\noffset.xyz/=offset.w;\noffset.xy=offset.xy*0.5+0.5;\nif (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\n\ndifference=depthSign*samplePosition.z-sampleDepth;\nfloat rangeCheck=1.0-smoothstep(correctedRadius*0.5,correctedRadius,difference);\nocclusion+=(difference>=0.0 ? 1.0 : 0.0)*rangeCheck;\n}\nocclusion=occlusion*(1.0-smoothstep(maxZ*0.75,maxZ,depth));\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 direction=vec2(0.0,1.0);\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=abs(texture2D(depthSampler,samplePos).r);\nfloat weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30000.0);\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n#else\nvec4 color;\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#else\nvec2 direction=vec2(0.0,1.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#endif\ngl_FragColor.rgb=vec3(color.r);\ngl_FragColor.a=1.0;\n#endif\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nuniform vec4 viewport;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,viewport.xy+vUV*viewport.zw);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\n\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric=(worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\n#ifndef MALI\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\n#endif\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\n#ifdef MALI\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\n}\nelse\n{\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}\n#else\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n#endif\n}","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float radialIntensity;\nuniform vec2 direction;\nuniform vec2 centerPosition;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-centerPosition.x,vUV.y-centerPosition.y);\nvec2 directionOfEffect=direction;\nif(directionOfEffect.x == 0. && directionOfEffect.y == 0.){\ndirectionOfEffect=normalize(centered_screen_pos);\n}\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.x/screen_width;\nfloat ref_shiftY=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.y/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\noriginal.a=clamp(texture2D(textureSampler,ref_coords_r).a+texture2D(textureSampler,ref_coords_g).a+texture2D(textureSampler,ref_coords_b).a,0.,1.);\ngl_FragColor=original;\n}","grainPixelShader":"#include<helperFunctions>\n\nuniform sampler2D textureSampler; \n\nuniform float intensity;\nuniform float animatedSeed;\n\nvarying vec2 vUV;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec2 seed=vUV*(animatedSeed);\nfloat grain=dither(seed,intensity);\n\nfloat lum=getLuminance(gl_FragColor.rgb);\nfloat grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;\ngl_FragColor.rgb+=grain*grainAmount;\ngl_FragColor.rgb=max(gl_FragColor.rgb,0.0);\n}","sharpenPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform vec2 sharpnessAmounts;\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 color=texture2D(textureSampler,vUV);\nvec4 edgeDetection=texture2D(textureSampler,vUV+onePixel*vec2(0,-1)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1)) -\ncolor*4.0;\ngl_FragColor=max(vec4(color.rgb*sharpnessAmounts.y,color.a)-(sharpnessAmounts.x*vec4(edgeDetection.rgb,0)),0.);\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#ifdef DOF\nuniform sampler2D circleOfConfusionSampler;\nuniform vec2 cameraMinMaxZ;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(circleOfConfusionSampler,offset).g; \nreturn cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth; \n}\nfloat sampleCoC(const in vec2 offset) {\nfloat coc=texture2D(circleOfConfusionSampler,offset).r; \nreturn coc; \n}\n#endif\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nvoid main(void)\n{\nfloat computedWeight=0.0;\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#ifdef DOF\nfloat sumOfWeights=CENTER_WEIGHT; \nfloat factor=0.0;\n\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter))*CENTER_WEIGHT;\n#else\nblend+=texture2D(textureSampler,sampleCenter)*CENTER_WEIGHT;\n#endif\n#endif\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n#ifdef DOF\ngl_FragColor/=sumOfWeights;\n#endif\n}","depthOfFieldMergePixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\nuniform sampler2D circleOfConfusionSampler;\nuniform sampler2D blurStep0;\n#if BLUR_LEVEL>0\nuniform sampler2D blurStep1;\n#endif\n#if BLUR_LEVEL>1\nuniform sampler2D blurStep2;\n#endif\nvoid main(void)\n{\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\n#if BLUR_LEVEL == 0\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred0=texture2D(blurStep0,vUV);\ngl_FragColor=mix(original,blurred0,coc);\n#endif\n#if BLUR_LEVEL == 1\nif(coc<0.5){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(original,blurred1,coc/0.5);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV); \nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.5)/0.5);\n}\n#endif\n#if BLUR_LEVEL == 2\nif(coc<0.33){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(original,blurred2,coc/0.33);\n}else if(coc<0.66){\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(blurred2,blurred1,(coc-0.33)/0.33);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.66)/0.34);\n}\n#endif\n}\n","circleOfConfusionPixelShader":"\nuniform sampler2D depthSampler;\n\nvarying vec2 vUV;\n\nuniform vec2 cameraMinMaxZ;\n\nuniform float focusDistance;\nuniform float cocPrecalculation;\nvoid main(void)\n{\nfloat depth=texture2D(depthSampler,vUV).r;\nfloat pixelDistance=(cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth)*1000.0; \nfloat coc=abs(cocPrecalculation* ((focusDistance-pixelDistance)/pixelDistance));\ncoc=clamp(coc,0.0,1.0);\ngl_FragColor=vec4(coc,depth,coc,1.0);\n}\n","bloomMergePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D bloomBlur;\nvarying vec2 vUV;\nuniform float bloomWeight;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec3 blurred=texture2D(bloomBlur,vUV).rgb;\ngl_FragColor.rgb=gl_FragColor.rgb+(blurred.rgb*bloomWeight); \n}\n","extractHighlightsPixelShader":"#include<helperFunctions>\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float threshold;\nuniform float exposure;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\nfloat luma=getLuminance(gl_FragColor.rgb*exposure);\ngl_FragColor.rgb=step(threshold,luma)*gl_FragColor.rgb;\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","motionBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D velocitySampler;\nuniform float motionStrength;\nuniform float motionScale;\nuniform vec2 screenSize;\nvoid main(void)\n{\n#ifdef GEOMETRY_SUPPORTED\nvec2 texelSize=1.0/screenSize;\nvec2 velocityColor=texture2D(velocitySampler,vUV).rg;\nvec2 velocity=vec2(pow(velocityColor.r,1.0/3.0),pow(velocityColor.g,1.0/3.0))*2.0-1.0;\nvelocity*=motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint samplesCount=int(clamp(speed,1.0,SAMPLES));\nvelocity=normalize(velocity)*texelSize;\nfloat hlim=float(-samplesCount)*0.5+0.5;\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(SAMPLES); ++i)\n{\nif (i>=samplesCount)\nbreak;\nvec2 offset=vUV+velocity*(hlim+float(i));\nresult+=texture2D(textureSampler,offset);\n}\ngl_FragColor=result/float(samplesCount);\n#else\ngl_FragColor=texture2D(textureSampler,vUV);\n#endif\n}\n","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive)*color;\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(positionUpdated,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#ifdef EMISSIVE\nuniform sampler2D textureSampler2;\n#endif\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef EMISSIVE\nbaseColor+=texture2D(textureSampler2,vUV);\nbaseColor*=offset;\n#else\nbaseColor.a=abs(offset-baseColor.a);\n#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);\nbaseColor.a=alpha;\nbaseColor.rgb=baseColor.rgb*alpha;\n#endif\n#endif\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include<logDepthDeclaration>\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<logDepthVertex>\n}\n","outlinePixelShader":"#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include<logDepthFragment>\ngl_FragColor=color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","backgroundVertexShader":"precision highp float;\n#include<__decl__backgroundVertex>\n#include<helperFunctions>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n\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"};
  119773. BABYLON.Effect.IncludesShadersStore={"depthPrePass":"#ifdef DEPTHPREPASS\ngl_FragColor=vec4(0.,0.,0.,1.0);\nreturn;\n#endif","bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\n#ifdef BONETEXTURE\nuniform sampler2D boneSampler;\nuniform float boneTextureWidth;\n#else\nuniform mat4 mBones[BonesPerMesh];\n#endif \nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#ifdef BONETEXTURE\nmat4 readMatrixFromRawSampler(sampler2D smp,float index)\n{\nfloat offset=index*4.0; \nfloat dx=1.0/boneTextureWidth;\nvec4 m0=texture2D(smp,vec2(dx*(offset+0.5),0.));\nvec4 m1=texture2D(smp,vec2(dx*(offset+1.5),0.));\nvec4 m2=texture2D(smp,vec2(dx*(offset+2.5),0.));\nvec4 m3=texture2D(smp,vec2(dx*(offset+3.5),0.));\nreturn mat4(m0,m1,m2,m3);\n}\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;\n#ifdef BONETEXTURE\ninfluence=readMatrixFromRawSampler(boneSampler,matricesIndices[0])*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=readMatrixFromRawSampler(boneSampler,matricesIndices[1])*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=readMatrixFromRawSampler(boneSampler,matricesIndices[2])*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=readMatrixFromRawSampler(boneSampler,matricesIndices[3])*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=readMatrixFromRawSampler(boneSampler,matricesIndicesExtra[0])*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=readMatrixFromRawSampler(boneSampler,matricesIndicesExtra[1])*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=readMatrixFromRawSampler(boneSampler,matricesIndicesExtra[2])*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=readMatrixFromRawSampler(boneSampler,matricesIndicesExtra[3])*matricesWeightsExtra[3];\n#endif \n#else \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 \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\n#ifdef BONETEXTURE\nuniform sampler2D boneSampler;\n#else\nuniform mat4 mBones[BonesPerMesh];\n#endif \nin vec4 matricesIndices;\nin vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nin vec4 matricesIndicesExtra;\nin vec4 matricesWeightsExtra;\n#endif\n#ifdef BONETEXTURE\nmat4 readMatrixFromRawSampler(sampler2D smp,float index)\n{\nmat4 result;\nfloat offset=index*4.0; \nfloat dx=1.0/boneTextureWidth;\nresult[0]=texture(smp,vec2(dx*(offset+0.5),0.));\nresult[1]=texture(smp,vec2(dx*(offset+1.5),0.));\nresult[2]=texture(smp,vec2(dx*(offset+2.5),0.));\nresult[3]=texture(smp,vec2(dx*(offset+3.5),0.));\nreturn result;\n}\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};"};
  119774. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  119775. globalObject["BABYLON"] = BABYLON;
  119776. //backwards compatibility
  119777. if(typeof earcut !== 'undefined') {
  119778. globalObject["Earcut"] = {
  119779. earcut: earcut
  119780. };
  119781. }
  119782. return BABYLON;
  119783. });